Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
6 Hrs
33 Min
31 Seg

Tu primera clasificación con regresión logística

2/17
Resources
Transcript

How do you set up the environment and load the data into a logistic regression model?

Logistic regression is a powerful and versatile technique in the field of Machine Learning, especially for data classification. The use of Python and Scikit Learn facilitates its implementation, allowing us to tackle complex tasks with relative simplicity. We will begin by discussing how to set up the environment and efficiently load the necessary data.

What libraries are needed?

For this project, we need several libraries that will help us in different aspects of the process:

  • Scikit Learn: Essential for manipulating datasets and applying logistic regression.
  • Pandas: For structured data manipulation and analysis.
  • Matplotlib and Seaborn: For data visualization.
  • NumPy: Used to perform operations on matrices and arrays.

These libraries, already preloaded in the environment, allow us to work without complications. The specific dataset we will use are images of handwritten digits, available through LogDigit from Scikit Learn.dataset.

How do we load the data?

We start by loading the data into an object called Digits:

from sklearn.datasets import load_digitsdigits digits = load_digits().

The Digits object contains several relevant properties, including thedata, thefeature_names, and a Target variable, which indicates which digit is represented in each image.

How is the data displayed?

To see these digit images more clearly, we use NumPy to restructure them into an 8x8 format, which is the structure documented in the original dataset.

import numpy as np
image = np.reshape(digits.data[0], (8, 8))

We can visualize the image using Matplotlib:

import matplotlib.pyplot as plt
plt.imshow(image,  cmap='gray')plt.show()

This visualization allows us to better understand the data we are manipulating, providing a firm foundation for learning the model.

How to divide the data into training and testing?

Properly dividing our data between training and test sets is crucial to validate and evaluate the performance of our model. This responsibility not only underpins the results obtained, but also ensures the reliability of the algorithm in the face of previously unseen data.

Why is this division important?

The separation of the data into training and testing allows:

  • Ensure that our model is not "learning by heart" the entire dataset.
  • Validate the model with data it has not seen before, allowing us to evaluate its accuracy objectively.

How do we do the data split?

Scikit Learn's train_test_split function is used to split the data:

from sklearn.model_selection import train_test_split
 x_train, x_test, y_train, y_test = train_test_split(digits.data, digits.target,  test_size=0.2, random_state=0).

Here, test_size=0.2 indicates that 20% of the dataset will be used for testing. The random_state ensures that the split is reproducible in future runs.

How is a logistic regression model trained and evaluated?

Once the data is ready and split, the next step is to train the logistic regression model. Here, we will highlight how to set up a model, train it, predict results, and finally, evaluate its performance.

How to set up and train the model?

Setting up and training the model is extremely simple:

from sklearn.linear_model import LogisticRegression
logistic_reg = LogisticRegression(max_iter=200)logistic_reg.fit(x_train, y_train).

The fit function trains the model using the training set.

How are predictions made?

With the model trained, we can obtain predictions on the test set:

predictions = logistic_reg.predict(x_test).

These predictions will allow us to evaluate the performance of the model by comparing them with the actual values of y_test.

How do we evaluate the model?

To evaluate the effectiveness of the model, we use a confusion matrix:

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, predictions).

And to visualize it:

import seaborn as sns
plt.figure(figsize=(9, 9))sns.heatmap(cm, annot=True,  linewidths=0.5, square=True,  cmap='coolwarm')plt.ylabel('Actual label')plt.xlabel('Predicted label')plt.show()

This matrix allows us to identify mostly hits and misses in the model; the values on the diagonal indicate the number of correct predictions.

Exploring logistic regression using Python and Scikit Learn is an excellent starting point to enter the world of machine learning. The simplicity of the code and the accuracy of the classification demonstrate the effectiveness of this technique. I invite you to keep digging and practicing with more complex models, following this course or exploring other datasets and algorithms. Learning never ends!

Contributions 15

Questions 2

Sort by:

Want to see more contributions, questions and answers from the community?

Ojalá este profe diera el de regresión lineal. Todo es tan claro…

Para evitar que se muestren esas advertencias de ConvergeWarning al usar el modelo de regresión logística
es recomendable SIEMPRE poner max_iter=10000, algunas veces basta con solo poner 1000

Para determinar el accuracy o evaluar rápidamente un modelo de Regresion Logistica podemos usar el la función score ( esto no es recomendable cuando se tienen clases muy desbalanceadas pero para “ganar tiempo” resulta muy util)

Con este código pueden subir sus propias fotos de dígitos a mano (Escritos sobre fondo negro) y se genera una predicción

from PIL import Image
import math

def classify(img_path):
  image = Image.open(img_path).convert('L')
  plt.imshow(image, cmap='gray')
  plt.title('Your photo')
  plt.show()
  x, y = image.size
  x2, y2 = 8, 8
  image = image.resize((x2,y2))
  image = [np.array(image).flatten()]
  prediction = logistic_reg.predict(image)[0]
  print(f'\n The image has a {prediction}')

classify('/content/example.png')

![](

A mi no me engañan mas, el random_state=42 es la eleccion correcta.

Otra forma de visualizar la matríz de confusión es haciendo uso de la función plot_confussion_matrix , sin embargo, dado que esta función esta algo “obsoleta” es recomensable importar los warnings que se muestran arriba a fin de evitar cualquier “advertencia” o “palabras raras” arriba del gráfica, es mas que todo para mantener la estética del gráfico

Qué clase tan completa en solo una se hizo todo…

Hay una pequeña corrección en el grafico de la matriz de confusión. La manera como está declarada la matriz el eje x serian los valores actuales mientras que el eje y seria el valor predicho

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test,predictions)
plt.figure(figsize=(9,9))
sns.heatmap(cm, annot=True, linewidths=.5, square=True, cmap='coolwarm')
plt.ylabel('Predicted label')
plt.xlabel('Actual label')
plt.ylabel('Predicted label')
plt.xlabel('Actual label')

Para evitar esas letras “raras” luego de usar matplotlib se puede usar ; como se muestra aquí:

No hay necesidad de utilizar el reshape de numpy, ya que digits ya cuenta con los datos en el formato 8x8 y se puede acceder a ellos con: `digits.images`
Me saqué las ganas de meter un poco de código: ```python plt.figure(figsize=(10, 10)) sns.heatmap(cm, annot=True, fmt=".0f", linewidths=.5, square=True, cmap='Blues_r') plt.ylabel('Actual label') plt.xlabel('Predicted label') all_sample_title = 'Accuracy Score: {:.2f}%'.format(logistic_reg.score(X_test, y_test) * 100) plt.title(all_sample_title, size=15) plt.show() ``` ![](https://static.platzi.com/media/user_upload/image-e7393330-3d6d-4a7a-848c-7b9df1745a64.jpg)
A hacer el Split me da el siguiente error: ![](https://static.platzi.com/media/user_upload/image-06f682ab-3827-42d0-8627-b02979165559.jpg) ![](https://static.platzi.com/media/user_upload/image-e7754ade-51c0-4d33-a7a8-48b2e5b09144.jpg)
**<u>INTERPRETACION DE LA MATRIZ DE CONFUSION</u>** array(\[\[27, 0, 0, 0, 0, 0, 0, 0, 0, 0], \[ 0, 34, 0, 0, 0, 0, 0, 0, 1, 0], \[ 0, 0, 35, 1, 0, 0, 0, 0, 0, 0], \[ 0, 0, 0, 29, 0, 0, 0, 0, 0, 0], \[ 0, 0, 0, 0, 29, 0, 0, 1, 0, 0], \[ 0, 0, 0, 0, 0, 37, 0, 0, 0, 3], \[ 0, 1, 0, 0, 0, 0, 43, 0, 0, 0], \[ 0, 0, 0, 0, 1, 0, 0, 38, 0, 0], \[ 0, 2, 1, 0, 0, 0, 0, 0, 36, 0], \[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 40]]) La matriz que has proporcionado parece ser una matriz de confusión. En una matriz de confusión, los elementos en la diagonal principal representan las predicciones correctas para cada clase, mientras que los elementos fuera de la diagonal principal representan las predicciones incorrectas. Veamos cómo interpretar los elementos fuera de la diagonal: * **Fila 1, Columna 9 (1, 9):** Hay un 1 en esta posición, lo que indica que hay 1 instancia que pertenece a la clase 1 pero fue incorrectamente clasificada como clase 9. * **Fila 2, Columna 8 (2, 8):** Hay un 1 en esta posición, lo que indica que hay 1 instancia que pertenece a la clase 2 pero fue incorrectamente clasificada como clase 8. * **Fila 5, Columna 8 (5, 8):** Hay un 1 en esta posición, lo que indica que hay 1 instancia que pertenece a la clase 5 pero fue incorrectamente clasificada como clase 8. * **Fila 6, Columna 10 (6, 10):** Hay un 3 en esta posición, lo que indica que hay 3 instancias que pertenecen a la clase 6 pero fueron incorrectamente clasificadas como clase 10. * **Fila 8, Columna 2 (8, 2):** Hay un 2 en esta posición, lo que indica que hay 2 instancias que pertenecen a la clase 8 pero fueron incorrectamente clasificadas como clase 2. * **Fila 9, Columna 3 (9, 3):** Hay un 1 en esta posición, lo que indica que hay 1 instancia que pertenece a la clase 9 pero fue incorrectamente clasificada como clase 3. También, hay un 2 en la posición (9, 2), lo que indica que hay 2 instancias que pertenecen a la clase 9 pero fueron incorrectamente clasificadas como clase 2. Estos valores indican las instancias que fueron clasificadas incorrectamente para cada par de clases. En general, una matriz de confusión proporciona información detallada sobre el rendimiento del modelo de clasificación, permitiendo identificar los tipos y cantidades de errores cometidos por el modelo.
<u>INTERPRETACION DE LA MATRIX DE CONFUSION</u> ```js array([[27, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 34, 0, 0, 0, 0, 0, 0, 1, 0], [ 0, 0, 35, 1, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 29, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 29, 0, 0, 1, 0, 0], [ 0, 0, 0, 0, 0, 37, 0, 0, 0, 3], [ 0, 1, 0, 0, 0, 0, 43, 0, 0, 0], [ 0, 0, 0, 0, 1, 0, 0, 38, 0, 0], [ 0, 2, 1, 0, 0, 0, 0, 0, 36, 0], [ 0, 0, 0, 0, 0, 1, 0, 0, 0, 40]]) ```array(\[\[27, 0, 0, 0, 0, 0, 0, 0, 0, 0], \[ 0, 34, 0, 0, 0, 0, 0, 0, 1, 0], \[ 0, 0, 35, 1, 0, 0, 0, 0, 0, 0], \[ 0, 0, 0, 29, 0, 0, 0, 0, 0, 0], \[ 0, 0, 0, 0, 29, 0, 0, 1, 0, 0], \[ 0, 0, 0, 0, 0, 37, 0, 0, 0, 3], \[ 0, 1, 0, 0, 0, 0, 43, 0, 0, 0], \[ 0, 0, 0, 0, 1, 0, 0, 38, 0, 0], \[ 0, 2, 1, 0, 0, 0, 0, 0, 36, 0], \[ 0, 0, 0, 0, 0, 1, 0, 0, 0, 40]]) La matriz que has proporcionado parece ser una matriz de confusión. En una matriz de confusión, los elementos en la diagonal principal representan las predicciones correctas para cada clase, mientras que los elementos fuera de la diagonal principal representan las predicciones incorrectas. Veamos cómo interpretar los elementos fuera de la diagonal: * **Fila 1, Columna 9 (1, 9):** Hay un 1 en esta posición, lo que indica que hay 1 instancia que pertenece a la clase 1 pero fue incorrectamente clasificada como clase 9. * **Fila 2, Columna 8 (2, 8):** Hay un 1 en esta posición, lo que indica que hay 1 instancia que pertenece a la clase 2 pero fue incorrectamente clasificada como clase 8. * **Fila 5, Columna 8 (5, 8):** Hay un 1 en esta posición, lo que indica que hay 1 instancia que pertenece a la clase 5 pero fue incorrectamente clasificada como clase 8. * **Fila 6, Columna 10 (6, 10):** Hay un 3 en esta posición, lo que indica que hay 3 instancias que pertenecen a la clase 6 pero fueron incorrectamente clasificadas como clase 10. * **Fila 8, Columna 2 (8, 2):** Hay un 2 en esta posición, lo que indica que hay 2 instancias que pertenecen a la clase 8 pero fueron incorrectamente clasificadas como clase 2. * **Fila 9, Columna 3 (9, 3):** Hay un 1 en esta posición, lo que indica que hay 1 instancia que pertenece a la clase 9 pero fue incorrectamente clasificada como clase 3. También, hay un 2 en la posición (9, 2), lo que indica que hay 2 instancias que pertenecen a la clase 9 pero fueron incorrectamente clasificadas como clase 2. Estos valores indican las instancias que fueron clasificadas incorrectamente para cada par de clases. En general, una matriz de confusión proporciona información detallada sobre el rendimiento del modelo de clasificación, permitiendo identificar los tipos y cantidades de errores cometidos por el modelo.
Aca los imports ```js from sklearn.datasets import load_digits import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np from sklearn.linear_model import LogisticRegression ```from sklearn.datasets import load\_digitsimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport numpy as npfrom sklearn.linear\_model import LogisticRegression

Si desean acceder a las imagenes sin hacer reshape: digits.images