0% found this document useful (0 votes)
5 views11 pages

Clasificación con Python y Sklearn

This document serves as a guide for applying classification models using Python and sklearn, detailing the process from data loading to model evaluation. It covers various supervised classification methods including Logistic Regression, Decision Trees, Random Forests, Support Vector Machines, and K-Nearest Neighbors. Visualizations are provided to compare the performance of different models on a dataset.

Uploaded by

Jackson Sibo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views11 pages

Clasificación con Python y Sklearn

This document serves as a guide for applying classification models using Python and sklearn, detailing the process from data loading to model evaluation. It covers various supervised classification methods including Logistic Regression, Decision Trees, Random Forests, Support Vector Machines, and K-Nearest Neighbors. Visualizations are provided to compare the performance of different models on a dataset.

Uploaded by

Jackson Sibo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Guía para la aplicación de modelos

de clasificación con Python y


sklearn
Metodos supervisados para Clasificación
Autor: Sergio Diaz Paredes

Contacto: Linkedin

In [1]: import pandas as pd


import numpy as np
import [Link] as plt
import sklearn as skl
import seaborn as sns

Data: DataSet

In [2]: df = pd.read_csv("[Link]

In [3]: [Link]()

Out[3]: x y c

0 1.04 4.51 1

1 1.26 13.07 0

2 0.64 3.14 1

3 0.81 13.21 0

4 2.02 4.83 1

In [4]: [Link]()

<class '[Link]'>
RangeIndex: 60 entries, 0 to 59
Data columns (total 3 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 x 60 non-null float64
1 y 60 non-null float64
2 c 60 non-null int64
dtypes: float64(2), int64(1)
memory usage: 1.5 KB

In [5]: [Link](df,hue='c')

<[Link] at 0x7babb2696440>
Out[5]:
Seleccion de variables
In [6]: y_var = ['c']
x_vars = ['x','y']

In [7]: [Link](df,x='c',y='x')

<Axes: xlabel='c', ylabel='x'>


Out[7]:
In [8]: [Link](df,x='c',y='y')

<Axes: xlabel='c', ylabel='y'>


Out[8]:

In [9]: [Link](df,x='x',y='y',hue='c', edgecolor=None)

<Axes: xlabel='x', ylabel='y'>


Out[9]:
Particion de la data
In [10]: from sklearn.model_selection import train_test_split

In [11]: X_train, X_test, y_train, y_test = train_test_split(df[x_vars], df[y_var], test_siz

Modelos
In [12]: rango_variable1 = [Link](0, 16,101)
rango_variable2 = [Link](0, 18,101)
combinaciones = [Link]([Link](rango_variable1, rango_variable2)).[Link](-

df_combinaciones = [Link](combinaciones, columns=['x', 'y'])


df_combinaciones.head()

Out[12]: x y

0 0.0 0.00

1 0.0 0.18

2 0.0 0.36

3 0.0 0.54

4 0.0 0.72

Regresion logistica
In [13]: from sklearn.linear_model import LogisticRegression
reg_lin = LogisticRegression().fit(X_train, y_train)

/usr/local/lib/python3.10/dist-packages/sklearn/utils/[Link]: DataConv
ersionWarning: A column-vector y was passed when a 1d array was expected. Please c
hange the shape of y to (n_samples, ), for example using ravel().
y = column_or_1d(y, warn=True)

In [14]: df_combinaciones['class_logit'] = reg_lin.predict(df_combinaciones[['x','y']])

In [15]: [Link](df_combinaciones,x='x',y='y',hue='class_logit', edgecolor=None)

<Axes: xlabel='x', ylabel='y'>


Out[15]:

Arbol de clasificacion
In [16]: from [Link] import DecisionTreeClassifier

In [17]: tree_reg = DecisionTreeClassifier(max_depth=3).fit(X_train[x_vars], y_train)

In [18]: df_combinaciones['class_tree'] = tree_reg.predict(df_combinaciones[['x','y']])

In [19]: [Link](df_combinaciones,x='x',y='y',hue='class_tree', edgecolor=None)

<Axes: xlabel='x', ylabel='y'>


Out[19]:
Random Forest
In [20]: from [Link] import RandomForestClassifier
rand_for = RandomForestClassifier(n_estimators=50,max_depth=3).fit(X_train[x_vars],

<ipython-input-20-8dd62c1c2f75>:2: DataConversionWarning: A column-vector y was pa


ssed when a 1d array was expected. Please change the shape of y to (n_samples,), f
or example using ravel().
rand_for = RandomForestClassifier(n_estimators=50,max_depth=3).fit(X_train[x_var
s], y_train)

In [21]: df_combinaciones['class_fore'] = rand_for.predict(df_combinaciones[['x','y']])

In [22]: [Link](df_combinaciones,x='x',y='y',hue='class_fore', edgecolor=None)

<Axes: xlabel='x', ylabel='y'>


Out[22]:
Maquina de soporte vectorial
In [23]: from [Link] import SVC

In [24]: maq_sopv = [Link](kernel='rbf').fit(X_train[x_vars], y_train)

/usr/local/lib/python3.10/dist-packages/sklearn/utils/[Link]: DataConv
ersionWarning: A column-vector y was passed when a 1d array was expected. Please c
hange the shape of y to (n_samples, ), for example using ravel().
y = column_or_1d(y, warn=True)

In [25]: df_combinaciones['class_sv'] = maq_sopv.predict(df_combinaciones[['x','y']])

In [26]: [Link](df_combinaciones,x='x',y='y',hue='class_sv', edgecolor=None)

<Axes: xlabel='x', ylabel='y'>


Out[26]:
K Vecinos más Cercanos (KNN)
In [27]: len(X_train)**0.5

6.48074069840786
Out[27]:

In [28]: from [Link] import KNeighborsClassifier


model_knn = KNeighborsClassifier(n_neighbors=6).fit(X_train[x_vars], y_train)

/usr/local/lib/python3.10/dist-packages/sklearn/neighbors/_classification.py:215:
DataConversionWarning: A column-vector y was passed when a 1d array was expected.
Please change the shape of y to (n_samples,), for example using ravel().
return self._fit(X, y)

In [29]: df_combinaciones['class_knn'] = model_knn.predict(df_combinaciones[['x','y']])

In [30]: [Link](df_combinaciones,x='x',y='y',hue='class_knn', edgecolor=None)

<Axes: xlabel='x', ylabel='y'>


Out[30]:
Resumen
In [31]: fig, ax = [Link](3, 2, figsize=(9, 9))

[Link](df, x='x', y='y', hue='c', edgecolor=None, ax=ax[0, 0], legend=Fals


ax[0, 0].set_title("Real")
ax[0, 0].set_xticks([])
ax[0, 0].set_yticks([])

[Link](df_combinaciones, x='x', y='y', hue='class_logit', edgecolor=None,


ax[0, 1].set_title("Logit")
ax[0, 1].set_xticks([])
ax[0, 1].set_yticks([])

[Link](df_combinaciones, x='x', y='y', hue='class_tree', edgecolor=None, a


ax[1, 0].set_title("Arbol de clasificación")
ax[1, 0].set_xticks([])
ax[1, 0].set_yticks([])

[Link](df_combinaciones, x='x', y='y', hue='class_fore', edgecolor=None, a


ax[1, 1].set_title("Random Forest")
ax[1, 1].set_xticks([])
ax[1, 1].set_yticks([])

[Link](df_combinaciones, x='x', y='y', hue='class_sv', edgecolor=None, ax=


ax[2, 0].set_title("Maquina de soporte")
ax[2, 0].set_xticks([])
ax[2, 0].set_yticks([])

[Link](df_combinaciones, x='x', y='y', hue='class_knn', edgecolor=None, ax


ax[2, 1].set_title("K Vecinos")
ax[2, 1].set_xticks([])
ax[2, 1].set_yticks([])

[Link]()

You might also like