In [3]:
# Ejercicio 1
# Alumnos: Cristhian Rodríguez Gomez y Jesus Perucha Perez

'''
 1. Cargar un el conjunto de datos del IRIS data set
'''
# Importamos la libreria ''
from sklearn.datasets import load_iris

data = load_iris()

In [4]:
'''
2. Una vez cargado convertir a pandas
'''
import pandas as pd
import numpy as np
from sklearn.datasets import load_iris

iris = load_iris()
data_panda = pd.DataFrame(data=np.c_[iris['data'], iris['target']],
                     columns= iris['feature_names'] + ['target'])

print(data_panda)


     sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)  \
0                  5.1               3.5                1.4               0.2   
1                  4.9               3.0                1.4               0.2   
2                  4.7               3.2                1.3               0.2   
3                  4.6               3.1                1.5               0.2   
4                  5.0               3.6                1.4               0.2   
5                  5.4               3.9                1.7               0.4   
6                  4.6               3.4                1.4               0.3   
7                  5.0               3.4                1.5               0.2   
8                  4.4               2.9                1.4               0.2   
9                  4.9               3.1                1.5               0.1   
10                 5.4               3.7                1.5               0.2   
11                 4.8               3.4                1.6               0.2   
12                 4.8               3.0                1.4               0.1   
13                 4.3               3.0                1.1               0.1   
14                 5.8               4.0                1.2               0.2   
15                 5.7               4.4                1.5               0.4   
16                 5.4               3.9                1.3               0.4   
17                 5.1               3.5                1.4               0.3   
18                 5.7               3.8                1.7               0.3   
19                 5.1               3.8                1.5               0.3   
20                 5.4               3.4                1.7               0.2   
21                 5.1               3.7                1.5               0.4   
22                 4.6               3.6                1.0               0.2   
23                 5.1               3.3                1.7               0.5   
24                 4.8               3.4                1.9               0.2   
25                 5.0               3.0                1.6               0.2   
26                 5.0               3.4                1.6               0.4   
27                 5.2               3.5                1.5               0.2   
28                 5.2               3.4                1.4               0.2   
29                 4.7               3.2                1.6               0.2   
..                 ...               ...                ...               ...   
120                6.9               3.2                5.7               2.3   
121                5.6               2.8                4.9               2.0   
122                7.7               2.8                6.7               2.0   
123                6.3               2.7                4.9               1.8   
124                6.7               3.3                5.7               2.1   
125                7.2               3.2                6.0               1.8   
126                6.2               2.8                4.8               1.8   
127                6.1               3.0                4.9               1.8   
128                6.4               2.8                5.6               2.1   
129                7.2               3.0                5.8               1.6   
130                7.4               2.8                6.1               1.9   
131                7.9               3.8                6.4               2.0   
132                6.4               2.8                5.6               2.2   
133                6.3               2.8                5.1               1.5   
134                6.1               2.6                5.6               1.4   
135                7.7               3.0                6.1               2.3   
136                6.3               3.4                5.6               2.4   
137                6.4               3.1                5.5               1.8   
138                6.0               3.0                4.8               1.8   
139                6.9               3.1                5.4               2.1   
140                6.7               3.1                5.6               2.4   
141                6.9               3.1                5.1               2.3   
142                5.8               2.7                5.1               1.9   
143                6.8               3.2                5.9               2.3   
144                6.7               3.3                5.7               2.5   
145                6.7               3.0                5.2               2.3   
146                6.3               2.5                5.0               1.9   
147                6.5               3.0                5.2               2.0   
148                6.2               3.4                5.4               2.3   
149                5.9               3.0                5.1               1.8   

     target  
0       0.0  
1       0.0  
2       0.0  
3       0.0  
4       0.0  
5       0.0  
6       0.0  
7       0.0  
8       0.0  
9       0.0  
10      0.0  
11      0.0  
12      0.0  
13      0.0  
14      0.0  
15      0.0  
16      0.0  
17      0.0  
18      0.0  
19      0.0  
20      0.0  
21      0.0  
22      0.0  
23      0.0  
24      0.0  
25      0.0  
26      0.0  
27      0.0  
28      0.0  
29      0.0  
..      ...  
120     2.0  
121     2.0  
122     2.0  
123     2.0  
124     2.0  
125     2.0  
126     2.0  
127     2.0  
128     2.0  
129     2.0  
130     2.0  
131     2.0  
132     2.0  
133     2.0  
134     2.0  
135     2.0  
136     2.0  
137     2.0  
138     2.0  
139     2.0  
140     2.0  
141     2.0  
142     2.0  
143     2.0  
144     2.0  
145     2.0  
146     2.0  
147     2.0  
148     2.0  
149     2.0  

[150 rows x 5 columns]

In [5]:
'''
3. Obtener información básica:3
'''
# - Numero de features
features = iris.feature_names    

numeroFeatures = len(features)
print('numero de features:',numeroFeatures)

# - Nombre de las features
print('features:', features)

# - Rango de valores del target
target = iris.target
minimo = min(target)
maximo = max(target)
print('Rango -> ','min:',minimo, ' max:', maximo)

# - Valor medio de las features
media_features = np.mean(data_panda) 
print('media de las features:','\n',media_features)  #mean : hace la media de cada una de  las columnas de la tabla


('numero de features:', 4)
('features:', ['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)', 'petal width (cm)'])
('Rango -> ', 'min:', 0, ' max:', 2)
('media de las features:', '\n', sepal length (cm)    5.843333
sepal width (cm)     3.054000
petal length (cm)    3.758667
petal width (cm)     1.198667
target               1.000000
dtype: float64)

In [6]:
'''
4. Obtener información estadística:
'''
# 4.1 La media de los valores de cada feature, para cada tipo de flor (flor = target)
import numpy as np
target = iris.target
print('<--- Media de los valores de cada feature ')
print('<----', data.target_names[0])
print(np.mean(data_panda[target == 0]))
print('<----', data.target_names[1])
print(np.mean(data_panda[target == 1]))
print('<----', data.target_names[2])
print(np.mean(data_panda[target == 2]))

# 4.2 Los valores de la flor sepal length más grande y más pequeño
# argmax: funcion que devuelve el indice del max 
indice_grande = data_panda["sepal length (cm)"].argmax()
# argmin: funcion que devuelve el indice del min
indice_pequeno = data_panda["sepal length (cm)"].argmin()
# Loc: funcion que devulve la fila de (indice) que se le pasa como parametro
fila_grande = data_panda.loc[indice_grande]
fila_pequeno = data_panda.loc[indice_pequeno]

print('<--- Valoress de la flor sepal length más grande ')
print(fila_grande)
print('<--- Valoress de la flor sepal length más pequeño ')
print(fila_pequeno)


<--- Media de los valores de cada feature 
('<----', 'setosa')
sepal length (cm)    5.006
sepal width (cm)     3.418
petal length (cm)    1.464
petal width (cm)     0.244
target               0.000
dtype: float64
('<----', 'versicolor')
sepal length (cm)    5.936
sepal width (cm)     2.770
petal length (cm)    4.260
petal width (cm)     1.326
target               1.000
dtype: float64
('<----', 'virginica')
sepal length (cm)    6.588
sepal width (cm)     2.974
petal length (cm)    5.552
petal width (cm)     2.026
target               2.000
dtype: float64
<--- Valoress de la flor sepal length más grande 
sepal length (cm)    7.9
sepal width (cm)     3.8
petal length (cm)    6.4
petal width (cm)     2.0
target               2.0
Name: 131, dtype: float64
<--- Valoress de la flor sepal length más pequeño 
sepal length (cm)    4.3
sepal width (cm)     3.0
petal length (cm)    1.1
petal width (cm)     0.1
target               0.0
Name: 13, dtype: float64

In [7]:
'''
 5. Obtener la correlación cruzada de todas las features (etiquetas)
'''
data_panda.corr(method='pearson')
data_panda.corr(method='kendall')


Out[7]:
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target
sepal length (cm) 1.000000 -0.072112 0.717624 0.654960 0.670444
sepal width (cm) -0.072112 1.000000 -0.182391 -0.146988 -0.333435
petal length (cm) 0.717624 -0.182391 1.000000 0.803014 0.822949
petal width (cm) 0.654960 -0.146988 0.803014 1.000000 0.838757
target 0.670444 -0.333435 0.822949 0.838757 1.000000

In [41]:
'''
6. Visualiza las con Seaborn Pairplot la correlación de las features
   Sirve para poder visualizar las graficas online
'''
%matplotlib inline

# libreria para usar las graficas
import seaborn as sns; sns.set(style="ticks", color_codes=True)

# Mostramos la grafica y pintamos los puntos segun el target
sns.pairplot(data_panda, hue="target")



In [8]:
''' 
7. Utiliza train/split y KNN para entrenar un modelo
http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html
- Repítelo para diferentes valores K del, 1 al 50
'''
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
import pandas as pd

iris = load_iris()
data_frame = pd.DataFrame(   data=np.c_[iris['data'], iris['target']],
                     columns= iris['feature_names'] + ['target'])

# Lo transformamos en un pandas
X = data_frame[iris['feature_names']]  # features
y = data_frame['target']               # targets

print(X.shape) # muestra el numero de filas y columnas
print(y.shape)

# Vamos a entrenar 
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=20)
knn.fit(X,y)

# Vamos a predecir las siquientes filas con las siguientes 'features' 
fila1 = [1,2,4,4]
fila2 = [5,5,3,1]
fila3 = [0,2,1,3]
knn.predict([fila1, fila2, fila3])
data_frame


(150, 4)
(150L,)
Out[8]:
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm) target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
136 6.3 3.4 5.6 2.4 2.0
137 6.4 3.1 5.5 1.8 2.0
138 6.0 3.0 4.8 1.8 2.0
139 6.9 3.1 5.4 2.1 2.0
140 6.7 3.1 5.6 2.4 2.0
141 6.9 3.1 5.1 2.3 2.0
142 5.8 2.7 5.1 1.9 2.0
143 6.8 3.2 5.9 2.3 2.0
144 6.7 3.3 5.7 2.5 2.0
145 6.7 3.0 5.2 2.3 2.0
146 6.3 2.5 5.0 1.9 2.0
147 6.5 3.0 5.2 2.0 2.0
148 6.2 3.4 5.4 2.3 2.0
149 5.9 3.0 5.1 1.8 2.0

150 rows × 5 columns


In [63]:
# Vamos a entrenar el algoritmo para algun k (numero de vecinoa)

maximo = 0
minimo = 1
for k in range(1, 50):
    
    knn = KNeighborsClassifier(n_neighbors=k)

    # Vamos a dividir nuestros conjuntos (40% para entrenar y 60% para test)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)

    # entrenamos el algoritmo con el 60% de los datos 
    knn.fit(X_train,y_train)

    # realizamos la prediccion con el otro 40% de los datos 
    y_pred = knn.predict(X_test)

    # Con esta libreria nos dira como de bien esta mi modelo 
    from sklearn.metrics import accuracy_score
    
    resultado = accuracy_score(y_test, y_pred)

    if resultado > maximo:
        maximo = resultado
    if resultado < minimo:
        minimo = resultado
        
# Mostramos el max y el min        
print(maximo)   
print(minimo)   

#- ¿Cuál es el mejor modelo? ¿Cuál es el peor?
# Mejor -> k = [11-21], 23, [25,30], 32, 34
# Peor -> K = 44


1.0
0.933333333333

In [46]:



Out[46]:
96

In [70]:
for k in range(1, 50):
    # Modelo 
    knn = KNeighborsClassifier(n_neighbors=k)

    # Vamos a dividir nuestros conjuntos (40% para entrenar y 60% para test)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=42)

    # entrenamos el algoritmo con el 60% de los datos 
    knn.fit(X_train,y_train)

    # realizamos la prediccion con el otro 40% de los datos 
    y_pred = knn.predict(X_test)

    # Con esta libreria nos dira como de bien esta mi modelo 
    from sklearn.metrics import accuracy_score
    
    resultado = accuracy_score(y_test, y_pred)

    
    #- ¿Qué matriz de confusión de da el mejor model? ¿y el peor? 
    from sklearn.metrics import confusion_matrix
    matriz = confusion_matrix(y_test, y_pred)
    
    #print(matriz)
    #print(k,"-------------")

# SCORE
scores = cross_val_score(knn, iris.data, iris.target, cv=10)
print(scores)


[ 0.86666667  0.93333333  0.93333333  0.93333333  1.          0.86666667
  0.93333333  0.93333333  1.          1.        ]

In [69]:
#Matriz de confusion
from sklearn.metrics import confusion_matrix
confusion_matrix(y_test, y_pred)


Out[69]:
array([[23,  0,  0],
       [ 0, 19,  0],
       [ 0,  1, 17]])

In [61]:
from sklearn import svm
from sklearn.model_selection import cross_val_score
# modelo
clf = svm.SVC(kernel='linear', C=1)

#SCORE
scores = cross_val_score(clf, iris.data, iris.target, cv=10)
print(scores) 

# Uno de los  mejores 11


[ 1.          0.93333333  1.          1.          0.86666667  1.
  0.93333333  1.          1.          1.        ]

In [14]:
from sklearn.externals import joblib
# Guarda el modelo, sea knn, svm(clf)
joblib.dump(knn, 'filename.pkl') 

#Carga el modelo
modelo = joblib.load('filename.pkl') 

modelo.predict([[1,2,3,4]])
# Uno de los  mejores 11


Out[14]:
array([ 1.])

In [68]:
'''
10. En lugar de KNN utiliza otros métodos y comprueba cual te da mejor score:
- SVM (support vector classification)
- Random Forest
'''
from sklearn.ensemble import RandomForestClassifier
rf1 = RandomForestClassifier(n_estimators=10)
rf2 = rf1.fit(X_train,y_train)

y_pred = rf2.predict(X_test)

# Con esta libreria nos dira como de bien esta mi modelo 
from sklearn.metrics import accuracy_score

resultado = accuracy_score(y_test, y_pred)
print(resultado)


scores = cross_val_score(rf2, iris.data, iris.target, cv=10)
print (scores)

# Scores
# + randomForest 5(unos)
# + svm 7(unos)
# + knn 3(unos)


0.983333333333
[ 1.          0.93333333  1.          0.93333333  0.93333333  0.93333333
  0.93333333  1.          1.          1.        ]