Aprendizaje supervisado
Regresión Lineal
import numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1,1],[1,2],[2,2],[2,3]])
# y = 1 * x_0 + 2 * x_1 + 3
y = np.dot(X, np.array([1,2])) + 3
reg = LinearRegression().fit(X,y)
reg.score(X,y)
# parámetros w_1 y w_0
reg.coef_
reg.intercept_
reg.predict(np.array([[3,5]]))
Regresión Logística
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
X,y = load_iris(return_X_y = True)
clf = LogisticRegression(random_state=0).fit(X,y)
clf.predict(X[:2,:])
clf.score(X,y)
/shared-libs/python3.7/py/lib/python3.7/site-packages/sklearn/linear_model/_logistic.py:818: ConvergenceWarning: lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.
Increase the number of iterations (max_iter) or scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
extra_warning_msg=_LOGISTIC_SOLVER_CONVERGENCE_MSG,
Bosques aleatorios
from sklearn.ensemble import RandomForestClassifier
from sklearn.datasets import make_classification
X,y = make_classification(n_samples=1000, n_features=4, n_informative=2,
n_redundant=0, random_state=0, shuffle=False)
clf = RandomForestClassifier(max_depth=2, random_state=0)
clf.fit(X,y)
clf.predict([[0,0,0,0]])
K - NN
X = [[0],[1],[2],[3]]
y = [0,0,1,1]
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=3) # k
knn.fit(X,y)
knn.predict([[1.1]])
knn.predict_proba([[0.9]])
Máquinas de soporte de vectores
import numpy as np
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X = np.array([[-1,-1],[-2,-1],[1,1],[2,1]])
y = np.array([1,1,2,2])
from sklearn.svm import SVC
clf = make_pipeline(StandardScaler(), SVC(gamma='auto'))
clf.fit(X,y)
Aprendizaje no supervisado
K - means
from sklearn.cluster import KMeans
import numpy as np
X = np.array([[1,2],[1,4],[1,0],[10,2],[10,4],[10,0]])
kmeans = KMeans(n_clusters=2, random_state=0).fit(X)
kmeans.labels_
kmeans.predict([[0,0],[12,3]])
kmeans.cluster_centers_
Antes de comenzar con ML se debe tratar de encontrar una solución sencilla: BASELINE.
nos ayuda a revelar si nuestro problemas es posible solucionarlo con ML
Métricas de clasificación
ACCURACY - exactitud. La más utilizada
RECALL - exhaustividad
PRESITION - precisión. Relación de las instancias clasificadas
F1 score - Media armónica. Combina la precisión y la exhaustividad
Métricas de regresión
Error acumulado
Promedio de las distancias de las cantidades. Error promedio absoluto. Fácil de entender e interpretar.
Root mean squared error: raíz del error cuadrático promedio. Recalca los grandes errores.
No necesariamente debemos elegir uno