Documentos de Académico
Documentos de Profesional
Documentos de Cultura
02 Machinelearning Clasico
02 Machinelearning Clasico
por computadora
Datos
Machine Modelo
Salida Learning
Datos
Modelo Computadora Salida
5
ALCANCE DEL APRENDIZAJE AUTOMÁTICO
VENTAJAS DESVENTAJAS
- Buen funcionamiento con bases de - Dificultad para aprender de grandes bases
datos pequeñas de datos
- Interpretación fácil de resultados - Requieren feature engineering
- Su desarrollo no requiere de - Dificultad para aprender funciones
equipos con grandes capacidades complejas
ALCANCE DEL APRENDIZAJE AUTOMÁTICO
- Reconocer Imágenes
- Lenguaje natural
- Interactuar con el mundo real (exploración, ubicación, reconocimiento)
Machine Learning
⚫ ¿Qué necesitamos para ml?
Performance
Datos
Machine learning Reglas
Respuestas (modelos)
⚫ ml pipeline
Mejorarlos/
Adquisición de Preprocesamiento Procesamiento Medir su Mantenerlos/
datos exactitud Actualizarlos
Adquisición de Preprocesamiento
datos Procesamiento Medir su Mejorarlos
exactitud
Datos
Machine Modelo
Salida Learning
PASOS CLAVE PARA ML PROJECT
(ML PIPELINE)
⚫ Adquisición de datos
Data
Numerical Categorical
Tipos de datos
Data
Sequence
Strings Location data
data
1) Etiquetado manual:
2) De datos observados
Adquisición de Preprocesamiento
datos Procesamiento Medir su Mejorarlos
exactitud
Limpiar los datos,
transformarlos, reducirlos y
separarlos
Entrenamiento Evaluación
20 2. Machine Learning
Adquisición de Preprocesamiento
datos Procesamiento Medir su Mejorarlos
exactitud
Seleccionar el o los
algoritmos
⚫ tipos de sistemas de ml
PCA SVD
No
¿Tienes respuestas?
K-MEANS C-MEANS
Sí
APRENDIZAJE SUPERVISADO
Sí
No
Logistic
Decisicion
Númericas Decisicion
Linear Regression
Tree
Tree Regression
SVM
Dog
Reducción de
Regresión
dimensionalidad
Clasificación Asociación
25
REGRESIÓN LINEAL
𝑦 = 𝑎𝑥 + 𝑏
https://drive.google.com/file/d/1ck9sBcHeJbn7SgUF9TDI40mGhgUTs1DM/view?usp=sharing
Penalizaciones
https://drive.google.com/file/d/1lgzTIzDoVBwYXVIzr3wuNNAlbV30Ymwl/view?usp=sharing
REGRESIÓN MÚLTIPLE
𝑀𝑡 = 𝛽1 (𝑇𝑡 − 𝑇) + 𝛽2 𝑃𝑡 + 𝜀
Notebook
https://colab.research.google.com/drive/1ESOdWY3CfsKjXfMRzVbt5ui-2LbvAENX?usp=sharing
PROPHET
⚫ INTRODUCCIÓN
El análisis de series de tiempo es un enfoque para analizar datos de
series de tiempo para extraer características significativas de los
datos y generar otros conocimientos útiles aplicados en la situación
empresarial.
Esta compuesto principalmente por un patrón más una desviación (bias) o aleatoriedad.
Tendencia+ Estacionalidad
Ruido Blanco
⚫ FA C E B O O K P R O P H E T
Facebook desarrolló un Prophet de código abierto, una Aspectos destacados de Facebook Prophet
herramienta de pronóstico disponible tanto en Python
1. Muy rápido, ya que está integrado en Stan, un lenguaje de programación para
como en R.
inferencia estadística escrito en C ++.
2. Un modelo de regresión aditiva en el que las tendencias no lineales se ajustan
Proporciona parámetros intuitivos que son fáciles de a la estacionalidad anual, semanal y diaria, además de los efectos de las
ajustar. vacaciones:
3. Prophet detecta automáticamente cambios en las tendencias seleccionando
puntos de cambio de los datos
4. Un componente estacional anual modelado utilizando series de Fourier
5. Una lista de días festivos importantes proporcionada por el usuario.
6. Resistente a los datos faltantes y los cambios en la tendencia, y generalmente
maneja valores atípicos.
7. Procedimiento sencillo para modificar y ajustar el pronóstico al tiempo que
agrega conocimientos de dominio o perspectivas comerciales.
⚫ MODELO DE PROPHET
The Prophet utiliza un modelo de series de tiempo con tres componentes principales del modelo: tendencia, estacionalidad y días festivos.
Se combinan en la siguiente ecuación:
Usando el tiempo como regresor, Prophet está tratando de ajustar varias funciones lineales y no lineales del tiempo como componentes.
⚫ MODELO DE PROPHET
Saturación
Change points
El modelo podría estar sobreajustado o desajustado
mientras trabaja con el componente de tendencia.
Para aminorar estos efectos se ha incorporado de
puntos de cambio a Prophet para hacer un ajuste
flexible.
https://colab.research.google.com/drive/1qiR5HtoV9mqo4hnPZ8
WTzm-RCM5_TCc2?usp=sharing
https://peerj.com/preprints/3190/
⚫ ml supervisado
DECISION TREE
- Algoritmo caja blanca
- Tareas de clasificación y regresión y tareas
multiclase
From ‘Hands-On Machine Learning with Scikit-Learn and TensorFlow’ by Aurélien Géron.
Decision Trees
From ‘Hands-On Machine Learning with Scikit-Learn and TensorFlow’ by Aurélien Géron.
Decision Trees
- Decision Trees are white box models, their decisions are easy to interpret and easy to explain
how the predictions were made.
- Decision Trees can also estimate the probability that an instance belongs to a particular class k.
From ‘Hands-On Machine Learning with Scikit-Learn and TensorFlow’ by Aurélien Géron.
Decision Trees
CART (Classification and Regression Trees) Algorithm
- CART algorithm produces only binary trees (the one used by Scikit Learn).
- For classification, while training the model on observations, at each step, pick a feature and split
the dataset into two parts based on how best to reduce node impurities at the next lower level.
- As the number of features in each observation increases, it gets more difficult to find and select
the right feature, and the right value to split on.
- For regression, the continuous value of the dependent variable can be computed to be the
‘average’ of the other nodes within that leaf node.
- Since the nodes are close in n-dimensional space among the features that matter the most, it is
logically similar to perform piecewise linear regression of related or close data (graded by purity) vs
performing a global regression.
Decision Trees
CART (Classification and Regression Trees) Algorithm
To reduce variance, a stopping criterion may be used:
1- stop growing the tree at a specific number of leaf nodes (pruning)
2- when leaves contain a certain minimum number of observations.
CART (Classification and Regression Trees) algorithm first splits the training set into two
subsets using a single feature k and a threshold tk (e.g. petal length < 2.45 cm ).
It searches for the pair (k, tk) that produces the purest subsets (weighted by their size).
It tries to minimize a cost function:
𝑚𝑙𝑒𝑓 𝑚𝑟𝑖𝑔ℎ
𝐽 𝑘, 𝑡𝑘 = 𝐺𝑙𝑒𝑓 + 𝐺𝑟𝑖𝑔ℎ
𝑚 𝑚
where:
Gleft/right measures the impurity of the left/right subset
mleft/right is the number of instances in the left/right subset
Decision Trees
- Most of the time there is no big difference between Gini and entropy.
- Gini impurity is slightly faster to compute.
- When Gini and entropy differ, entropy tends to produce slightly more balanced trees while
Gini tends to isolate the most frequent class in its own branch of the tree.
Decision Trees
Regularization Hyperparameters
- Nonparametric model: Decision Trees make few assumptions about the training data,
the number of parameters is not determined prior to training.
where:
𝑖 2
𝑀𝑆𝐸𝑛𝑜𝑑𝑒 = 𝑦𝑛𝑜𝑑𝑒
̰ −𝑦
𝑖∈𝑛𝑜𝑑𝑒
1 𝑖
𝑦𝑛𝑜𝑑𝑒
̰ = 𝑦
𝑚𝑛𝑜𝑑𝑒
𝑖∈𝑛𝑜𝑑𝑒
Ensemble, voting & Random
Forest
⚫ Ensemble classifiers Hard voting
Soft voting Prob
⚫ Bagging and Pasting
Bagging= ?
Pasting=?
⚫ ml supervisado
RANDOM FOREST
- At each node only a random subset of the features is considered for splitting.
- Each tree in the ensemble is built from a sample drawn with replacement (i.e., a bootstrap
sample) from the training set.
- Feature importance: Random Forest measures the relative importance of each feature.
In Scikit Learn: how much the tree nodes that use that feature reduce impurity on average
across all trees in the forest. It is a weight average, where each nodes weight is equal to the
number of training samples that are associated with it (feature_importances_ variable).
ML supervisado
SVM
SVM realiza:
- Regresión lineal y no lineal
- Clasificación y detección de valores atípicos.
- Un modelo SVM es una representación de los ejemplos como
puntos en el espacio, de modo que los ejemplos de las
categorías separadas estén divididos por un espacio lo más
amplio posible.
Existe la versión lineal y con kernel.
- SVM lineal: la línea que maximiza este margen es la elegida
como modelo óptimo. Support vectors son los puntos de
entrenamiento tocan el margen.
- Kernel SVM: los datos separables de forma no lineal, son
proyectados en un espacio de mayor dimensión para ajustarse
a relaciones no lineales con un clasificador lineal.
NOTEBOOKS
DECISION TREES
https://drive.google.com/file/d/1Gi_IBvRdSXQALJJ_F99-L-KRiww-IwED/view?usp=sharing
RANDOM FOREST
https://drive.google.com/file/d/1aDoZqWmpMHq_xcHDcjotKzgrnbFUeP81/view?usp=sh
aring
(si aparece solo texto darle en la opción de abrir con google colab)
Bases de datos
desbalanceadas
¿QUÉ HACER CON LOS DATOS
IMBALANCEADOS?
Es importante contar con una medida que nos de una vista real de
lo que está pasando en los datos.
¿QUÉ HACER CON LOS DATOS
IMBALANCEADOS?
Es importante contar con una medida que nos de una vista real de lo que está pasando en los datos.
Matriz de confusión
0 1
0 699,991 0
1 602 0
⚫ precisión-recall
EJEMPLO MARKETING BANCO
A TRAVÉS DE MODELO PREDICTIVO PARA NUEVA TC
•habrá clientes con los que contactaremos porque el modelo ha predicho que aceptarían y en realidad no lo hacen (False Positive
[FP], Positivos Falsos).
•habrá también clientes con los que no contactaremos porque el modelo ha predicho que no aceptarían que en realidad si lo
hubieran hecho (False Negative [FN], Negativos Falsos).
El modelo de Machine Learning también acertará (esperemos que mucho). A efectos prácticos esto significa que:
•habrá clientes con los que contactaremos porque el modelo ha predicho que aceptarían y en realidad sí que lo hacen (True
Positive [TP], Positivos Verdaderos).
•habrá clientes que no contactaremos porque el modelo ha predicho que no aceptarían la oferta y en realidad no lo hacen (True
Negative [TN], Negativos Verdaderos).
Precision (Precisión)
Con la métrica de precisión podemos medir la calidad del modelo de machine
learning en tareas de clasificación. En el ejemplo, se refiere a que la precisión es la
respuesta a la pregunta ¿qué porcentaje de los clientes que contactemos estarán
interesados?
Es decir, que sólo un 33% de los clientes a los que contactemos estarán
realmente interesados. Esto significa que el modelo del ejemplo se
equivocará un 66% de las veces cuando prediga que un cliente va a
estar interesado.
Recall (Exhaustividad)
La métrica de exhaustividad nos va a informar sobre la cantidad que el modelo
de machine learning es capaz de identificar. En el ejemplo, se refiere a que la
exhaustividad (recall) es la respuesta a la pregunta ¿qué porcentaje de los clientes
están interesados somos capaces de identificar?
Es decir, el modelo sólo es capaz de identificar un 25% de los clientes que estarían
interesados en adquirir el producto. Esto significa que el modelo del ejemplo sólo
es capaz de identificar 1 de cada 4 de los clientes que sí aceptarían la oferta.
¿QUÉ HACER CON LOS DATOS IMBALANCEADOS?
•Ejemplo:
n_samples= 43400, n_classes= 2(0&1), n_sample0= 42617, n_samples1= 783
import math
from sklearn.utils import class_weight
weights=class_weight.compute_class_weight('balanced',
np.unique(train_batches.classes),train_batches.classes)
class_weight=dict(zip(keys,list(weights)))
print(class_weight)
⚫ PRACTICA
⚫ https://colab.research.google.com/drive/12lNeaaCD_yt
zX8BCUIH4V-Mfkf5kc7iF?usp=sharing
Machine Learning
Reducción de
Regresión
dimensionalidad
Clasificación Asociación
89
Machine Learning
Unsupervised Learning
k-Means
- Dimensionality reduction: when there are many features (e.g. thousands or millions) for each
training instance it makes training slow and it could be hard to find a good solution.
- PCA:
From ‘Hands-On Machine Learning with Scikit-Learn and TensorFlow’ by Aurélien Géron.
Dimensionality Reduction
- When there are many features (e.g. thousands or millions) for each training instance it
- Reducing dimensionality of the training set before training a model speeds up training.
- High-dimensional datasets are risk of being very sparse: most training instances are far
away from each other making predictions less reliable since they will be based on larger
extrapolations.
- Sparsity is a problem for statistical significance, the amount of data needed to support the
From ‘Hands-On Machine Learning with Scikit-Learn and TensorFlow’ by Aurélien Géron.
Principal Component Analysis(PCA)
https://colab.research.google.com/drive/1V8u6wDNiAnW
jMtOBEEJ4TIXEvTLKhbEs?usp=sharing
Principal Component Analysis(PCA)
Principal Components
- PCA identifies the axis that accounts for the largest amount of variance in the training set.
- PCA finds a second axis, orthogonal to the first one, that accounts for the largest amount
of remaining variance.
- PCA would also find a third axis, orthogonal to the both previous axis, etc.
- The unit vector that identifies the ith axis is called principal component.
- PCA assumes that the dataset is centered around the origin. Scikit-Learn’s PCA classes
centers the data.
Principal Component Analysis(PCA)
Scikit-Learn
- After fitting PCA transformer to the dataset, the principal components can be accessed using
- Explained variance ratio of each principal component: the proportion of the dataset’s variance
that lies along the axis of each principal component, explained_variance_ratio_ variable.
PCA (Principal Component Analysis)
Choosing the Right Number of Dimensions
- It is generally useful to choose the number of dimensions that add up to a large proportion of
the variance (i.e. 95%).
- In case of data visualization the dimensionality is usually reduced to 2 or 3 dimensions.
- Scikit_Learn: set n_components to a float between 0.0 and 1.0, indicating the ratio of
variance to preserve, PCA(n-components=0.95).
- Plot the explained variance as a function of the number of dimensions.
n° of components / dimensions From ‘Python Data Science Handbook’ by Jake Vander Plas.
Principal Component Analysis(PCA)
- It’s possible to decompress the reduced dataset by applying the inverse transformation
of the PCA.
PCA (Principal Component Analysis)
Disadvantages
- PCA assumes that the principle components are a linear combination of the original features.
- PCA uses variance as the measure of how important a particular dimension is.
- Dimensionality reduction: tries to keep similar instances close and dissimilar instances apart.
https://towardsdatascience.com/an-introduction-to-t-sne-with-python-example-5a3a293108d1