feat: Translate file to spanish

Spanish translation for `2-Regression/4-Logistic/README.md`
pull/513/head
Angel Mendez 4 years ago
parent 30d2956a50
commit 0f6dec003c

@ -1,74 +1,75 @@
# Logistic regression to predict categories # Regresión logística para predecir categorías
![Logistic vs. linear regression infographic](./images/logistic-linear.png) ![Infografía de regresiones lineal vs logística](../images/logistic-linear.png)
> Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded) > Infografía de [Dasani Madipalli](https://twitter.com/dasani_decoded)
## [Pre-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/15/)
> ### [This lesson is available in R!](./solution/R/lesson_4-R.ipynb) ## [Examen previo a la lección](https://white-water-09ec41f0f.azurestaticapps.net/quiz/15/)
## Introduction > ### [Esta lección se encuentra disponible en R!](../solution/R/lesson_4-R.ipynb)
In this final lesson on Regression, one of the basic _classic_ ML techniques, we will take a look at Logistic Regression. You would use this technique to discover patterns to predict binary categories. Is this candy chocolate or not? Is this disease contagious or not? Will this customer choose this product or not? ## Introducción
In this lesson, you will learn: En esta lección final de Regresión, una de las técnicas básicas _clásicas_ de aprendizaje automático, echaremos un vistazo a la regresión logística. Usarás esta técnica para descubrir patrones que predigan categorías binarias. ¿Este dulce es un chocolate o no lo es? ¿Ésta enfermedad es contagiosa o no?, ¿Este cliente eligirá este producto o no?
- A new library for data visualization En esta lección, aprenderás:
- Techniques for logistic regression
✅ Deepen your understanding of working with this type of regression in this [Learn module](https://docs.microsoft.com/learn/modules/train-evaluate-classification-models?WT.mc_id=academic-15963-cxa) - Una nueva librería para visualización de datos
## Prerequisite - Técnicas para regresión logística
Having worked with the pumpkin data, we are now familiar enough with it to realize that there's one binary category that we can work with: `Color`. ✅ Profundiza tu entendimiento de trabajo con este tipo de regresión en este [módulo de aprendizaje(https://docs.microsoft.com/learn/modules/train-evaluate-classification-models?WT.mc_id=academic-15963-cxa)
## Requisitos previos
Let's build a logistic regression model to predict that, given some variables, _what color a given pumpkin is likely to be_ (orange 🎃 or white 👻). Haber trabajado con los datos de calabazas, ahora estamos suficientemente familiarizados con estos para entender que hay una categoría binaria que podemos trabajar con `Color`.
> Why are we talking about binary classification in a lesson grouping about regression? Only for linguistic convenience, as logistic regression is [really a classification method](https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression), albeit a linear-based one. Learn about other ways to classify data in the next lesson group. Construyamos un modelo de regresión logística para predecirlo, dadas algunas variables, _qué color podría tener una calabaza dada_ (naranja 🎃 o blanca 👻).
## Define the question > ¿Porqué estamos hablando acerca de clasificación binaria en un grupo de lecciones acerca de regresión? Sólo por conveniencia ligüística, como la regresión logística es [realmente un método de clasificación](https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression), aunque de de base lineal. Aprende acerca de otras formas de clasificar los datos en el siguiente grupo de lecciones.
For our purposes, we will express this as a binary: 'Orange' or 'Not Orange'. There is also a 'striped' category in our dataset but there are few instances of it, so we will not use it. It disappears once we remove null values from the dataset, anyway. ## Define la pregunta
> 🎃 Fun fact, we sometimes call white pumpkins 'ghost' pumpkins. They aren't very easy to carve, so they aren't as popular as the orange ones but they are cool looking! Para nuestros propósitos, expresaremos esto como un binario: 'Orange' o 'Not Orange'. También hay una categoría 'striped' en nuestro conjunto de datos pero hay menos instancias de éstas, por lo que no las usaremos. Ésta desaparece una vez que removemos los valores nulos de nuestro conjunto de datos, de cualquier forma.
## About logistic regression > 🎃 Dato gracioso, algunas veces llamamos 'fantasmas' a las calabazas blancas. No son muy fáciles de tallar, por lo que no son tan populares como las calabazas naranjas, ¡pero se ven geniales!
Logistic regression differs from linear regression, which you learned about previously, in a few important ways. ## Acerca de la regresión logística
### Binary classification La regresión logística difiere de la regresión lineal, lo cual aprendiste previamentem en unas pocas cosas importantes.
Logistic regression does not offer the same features as linear regression. The former offers a prediction about a binary category ("orange or not orange") whereas the latter is capable of predicting continual values, for example given the origin of a pumpkin and the time of harvest, _how much its price will rise_. ### Clasificación binaria
![Pumpkin classification Model](./images/pumpkin-classifier.png) La regresión logística no ofrece las mismas características como la regresión lineal. Las primeras ofrecen una predicción acerca de categorías binarias ("naranja o no naranja") mientras que la segunda es capaz de predecir valores continuos, por ejemplo dado el origen de una calabaza y el tiempo de cosecha, _cuánto incrementará su precio_.
> Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded)
### Other classifications
There are other types of logistic regression, including multinomial and ordinal: ![Modelo de clasificación de calabazas](../images/pumpkin-classifier.png)
> Infografía de [Dasani Madipalli](https://twitter.com/dasani_decoded)
### Otras clasificaciones
- **Multinomial**, which involves having more than one category - "Orange, White, and Striped". Existen otros tipo de regresión logística, incluyendo la multinomial y ordinal:
- **Ordinal**, which involves ordered categories, useful if we wanted to order our outcomes logically, like our pumpkins that are ordered by a finite number of sizes (mini,sm,med,lg,xl,xxl).
![Multinomial vs ordinal regression](./images/multinomial-ordinal.png) - **Multinomial**, la cual implica tener más de una categoría - "Orange, White, and Striped".
> Infographic by [Dasani Madipalli](https://twitter.com/dasani_decoded) - **Ordinal**, la cual implica categorías ordenadas, útil si quisieramos ordenar nuestras resultados logicamente, como nuestras calabazas que están ordenadas por un número finito de tamaños (mini,sm,med,lg,xl,xxl).
### It's still linear ![Regresión multinomial vs ordinal](../images/multinomial-ordinal.png)
> Infografía de [Dasani Madipalli](https://twitter.com/dasani_decoded)
Even though this type of Regression is all about 'category predictions', it still works best when there is a clear linear relationship between the dependent variable (color) and the other independent variables (the rest of the dataset, like city name and size). It's good to get an idea of whether there is any linearity dividing these variables or not. ### Sigue siendo lineal
### Variables DO NOT have to correlate Aunqeu este tipo de regresión se trata de 'predicciones de categoría', aún funciona mejor cuando hay una relación clara entre la variable dependiente (color) y las otras variables independientes (el resto del conjunto de datos, como el nombre de la ciudad y tamaño). Es bueno tener una idea de si hay alguna linealidad dividiendo estas variables o no.
Remember how linear regression worked better with more correlated variables? Logistic regression is the opposite - the variables don't have to align. That works for this data which has somewhat weak correlations. ### Las variables NO tienen correlación
### You need a lot of clean data ¿Recuerdas cómo la regresión lineal funcionó mejor con variables correlacionadas? La regresión logística es lo opuesto - las variables no se tienen que alinear. Eso funciona para estos datos los cuales tienen correlaciones algo débiles.
Logistic regression will give more accurate results if you use more data; our small dataset is not optimal for this task, so keep that in mind. ### Necesitas muchos datos limpios
✅ Think about the types of data that would lend themselves well to logistic regression La regresión logística te dará resultados más precisos si usas más datos; nuestro pequeño conjunto de datos no es óptimo para esta tarea, así que tenlo en mente.
## Exercise - tidy the data ✅ piensa en los tipos de datos que se prestarían bien para la regresión logística
First, clean the data a bit, dropping null values and selecting only some of the columns: ## Ejercicio - arregla los datos
1. Add the following code: Primero, limpia los datos un poco, remueve los valores nulos y selecciona sólo algunas de las columnas:
1. Agrega el siguiente código:
```python ```python
from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import LabelEncoder
@ -82,19 +83,19 @@ First, clean the data a bit, dropping null values and selecting only some of the
new_pumpkins = new_pumpkins.apply(LabelEncoder().fit_transform) new_pumpkins = new_pumpkins.apply(LabelEncoder().fit_transform)
``` ```
You can always take a peek at your new dataframe: Siempre puedes echar un vistazo a tu nuevo dataframe:
```python ```python
new_pumpkins.info new_pumpkins.info
``` ```
### Visualization - side-by-side grid ### Visualización - cuadrícula lado a lado
By now you have loaded up the [starter notebook](./notebook.ipynb) with pumpkin data once again and cleaned it so as to preserve a dataset containing a few variables, including `Color`. Let's visualize the dataframe in the notebook using a different library: [Seaborn](https://seaborn.pydata.org/index.html), which is built on Matplotlib which we used earlier. Por ahora has cargado el [starter notebook](../notebook.ipynb) con datos de calabazas una vez más y los has limpiado para así preservar el conjunto de datos que contiene unas pocas variables, incluyendo `Color`. Visualizaremos el dataframe en el notebook usando una librería diferente: [Seaborn](https://seaborn.pydata.org/index.html), el cual es construido en Matplotlib que ya usamos anteriormente.
Seaborn offers some neat ways to visualize your data. For example, you can compare distributions of the data for each point in a side-by-side grid. Seaborn ofrece algunas formas ingeniosas de visualizar tus datos. Por ejemplo, puedes comparar distribuciones de los datos para cada punto en una cuadrícula lado a lado.
1. Create such a grid by instantiating a `PairGrid`, using our pumpkin data `new_pumpkins`, followed by calling `map()`: 1. Crea dicha cuadrícula instanciando `PairGrid`, usando nuestros datos de calabazas `new_pumpkins`, seguido de la llamada a `map()`:
```python ```python
import seaborn as sns import seaborn as sns
@ -103,56 +104,56 @@ Seaborn offers some neat ways to visualize your data. For example, you can compa
g.map(sns.scatterplot) g.map(sns.scatterplot)
``` ```
![A grid of visualized data](images/grid.png) ![Una cuadrícula de datos visualizados](../images/grid.png)
By observing data side-by-side, you can see how the Color data relates to the other columns. Al observar los datos lado a lado, puedes ver como los datos de Color se relacionan con las otras columnas.
Given this scatterplot grid, what are some interesting explorations you can envision? Dada la cuadrícula del gráfico de dispersión, ¿cuáles son algunas exploraciones interesantes que puedes visualizar?
### Use a swarm plot ### Usa un gráfico de enjambre
Since Color is a binary category (Orange or Not), it's called 'categorical data' and needs 'a more [specialized approach](https://seaborn.pydata.org/tutorial/categorical.html?highlight=bar) to visualization'. There are other ways to visualize the relationship of this category with other variables. Dado que Color es una categoría binaria (Naranja o no), se le llaman 'datos categóricos' y necesita 'un [enfoque más especializado](https://seaborn.pydata.org/tutorial/categorical.html?highlight=bar) para visualización. Hay otras formas de visualizar las relaciones de esta categoría con otras variables.
You can visualize variables side-by-side with Seaborn plots. Puedes visualizar variables lado a lado con los gráficos Seaborn.
1. Try a 'swarm' plot to show the distribution of values: 1. Prueba un gráfico de 'enjambre' (swarm) para mostrar la distribución de valores:
```python ```python
sns.swarmplot(x="Color", y="Item Size", data=new_pumpkins) sns.swarmplot(x="Color", y="Item Size", data=new_pumpkins)
``` ```
![A swarm of visualized data](images/swarm.png) ![Un enjambre de datos visualizados](../images/swarm.png)
### Violin plot ### Gráfico de Violín
A 'violin' type plot is useful as you can easily visualize the way that data in the two categories is distributed. Violin plots don't work so well with smaller datasets as the distribution is displayed more 'smoothly'. Un gráfico tipo 'violín' es útil ya que puedes visualizar fácilmente la forma en que los datos se distribuyen en las dos categorías. Los gŕaficos de violín no funcionan muy bien con conjuntos de datos muy pequeños ya que la distribución se muestra más 'suavemente'.
1. As parameters `x=Color`, `kind="violin"` and call `catplot()`: 1. Como parámetros `x=Color`, `kind="violin"` y llamada `catplot()`:
```python ```python
sns.catplot(x="Color", y="Item Size", sns.catplot(x="Color", y="Item Size",
kind="violin", data=new_pumpkins) kind="violin", data=new_pumpkins)
``` ```
![a violin type chart](images/violin.png) ![un tipo de gráfico de violín](../images/violin.png)
Try creating this plot, and other Seaborn plots, using other variables. Prueba a crear este gráfico, y otros gráficos de Seaborn, usando otras variables.
Now that we have an idea of the relationship between the binary categories of color and the larger group of sizes, let's explore logistic regression to determine a given pumpkin's likely color. Ahora que tenemos una idea de la relación entre las categorías binarias de color y el grupo mayor de tamaños, exploremos la regresión logística para determinar el color probable de cierta calabaza.
> **🧮 Show Me The Math** > **🧮 Muéstrame las matemáticas**
> >
> Remember how linear regression often used ordinary least squares to arrive at a value? Logistic regression relies on the concept of 'maximum likelihood' using [sigmoid functions](https://wikipedia.org/wiki/Sigmoid_function). A 'Sigmoid Function' on a plot looks like an 'S' shape. It takes a value and maps it to somewhere between 0 and 1. Its curve is also called a 'logistic curve'. Its formula looks like this: > ¿Recuerdas cómo la regresión lineal suele ser usó mínimos cuadrados ordinarios para llegar al valor? La regresión logística se basa en el concepto de 'máxima probabilidad' usando [funciones sigmoides](https://wikipedia.org/wiki/Sigmoid_function). Una 'Función Sigmoide' en una gráfico tiene la forma de una 'S'. Toma una valor lo asigna entre 0 y 1. Su curva también es llamada 'curva logística'. Su fórmula luce así:
> >
> ![logistic function](images/sigmoid.png) > ![Función logística](../images/sigmoid.png)
> >
> where the sigmoid's midpoint finds itself at x's 0 point, L is the curve's maximum value, and k is the curve's steepness. If the outcome of the function is more than 0.5, the label in question will be given the class '1' of the binary choice. If not, it will be classified as '0'. > Donde el punto medio del sigmoide se encuentra en el punt 0 de las x, L es el valor máximo de la curva, k es la pendiente de la curva. Si el resultado de la función es más de 0.5, la etiqueta en cuestión se le dará la clase '1' de la elección binaria. Si no, será clasificada como '0'.
## Build your model ## Construye tu modelo
Building a model to find these binary classification is surprisingly straightforward in Scikit-learn. Construir un modelo para encontrar estas clasificaciones binarias es sorprendentemente fácil en Scikit-learn.
1. Select the variables you want to use in your classification model and split the training and test sets calling `train_test_split()`: 1. Elige las variable que quieres usar en tu modelo de clasificación y divide el modelo y los conjuntos de pruebas llamando `train_test_split()`:
```python ```python
from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split
@ -166,7 +167,7 @@ Building a model to find these binary classification is surprisingly straightfor
``` ```
1. Now you can train your model, by calling `fit()` with your training data, and print out its result: 1. Ahora puedes entrenar tu modelo, llamando `fit()` con tus datos entrenados, e imprimir su resultado:
```python ```python
from sklearn.model_selection import train_test_split from sklearn.model_selection import train_test_split
@ -182,7 +183,7 @@ Building a model to find these binary classification is surprisingly straightfor
print('Accuracy: ', accuracy_score(y_test, predictions)) print('Accuracy: ', accuracy_score(y_test, predictions))
``` ```
Take a look at your model's scoreboard. It's not too bad, considering you have only about 1000 rows of data: Echa un vistazo al marcador de tu modelo. No es tan malo, considerando tienes solo 1000 filas de datos:
```output ```output
precision recall f1-score support precision recall f1-score support
@ -202,73 +203,73 @@ Building a model to find these binary classification is surprisingly straightfor
0 0 0 1 0 1 0 0 1 0 0 0 1 0] 0 0 0 1 0 1 0 0 1 0 0 0 1 0]
``` ```
## Better comprehension via a confusion matrix ## Mejor comprensión a través e una matriz de confusión
While you can get a scoreboard report [terms](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html?highlight=classification_report#sklearn.metrics.classification_report) by printing out the items above, you might be able to understand your model more easily by using a [confusion matrix](https://scikit-learn.org/stable/modules/model_evaluation.html#confusion-matrix) to help us understand how the model is performing. Mientras puedes obtener un reporte de [términos](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.classification_report.html?highlight=classification_report#sklearn.metrics.classification_report) del marcador imprimiendo los elementos de arriba, serás capaz de entender tu modelo más fácilmente usando una [matriz de confusión](https://scikit-learn.org/stable/modules/model_evaluation.html#confusion-matrix) para ayudarnos a entender cómo se desempeña el modelo.
> 🎓 A '[confusion matrix](https://wikipedia.org/wiki/Confusion_matrix)' (or 'error matrix') is a table that expresses your model's true vs. false positives and negatives, thus gauging the accuracy of predictions. > 🎓 Una '[matriz de confusión](https://wikipedia.org/wiki/Confusion_matrix)' (o 'matriz de error') es una table que expresa los verdaderos vs los falsos positivos y negativos de tu modelo, para así medir la precisión de las predicciones.
1. To use a confusion metrics, call `confusion_matrix()`: 1. Para usar métricas de confusión, llama `confusion_matrix()`:
```python ```python
from sklearn.metrics import confusion_matrix from sklearn.metrics import confusion_matrix
confusion_matrix(y_test, predictions) confusion_matrix(y_test, predictions)
``` ```
Take a look at your model's confusion matrix: Echa un vistazo a la matriz de confusión de tu modelo:
```output ```output
array([[162, 4], array([[162, 4],
[ 33, 0]]) [ 33, 0]])
``` ```
In Scikit-learn, confusion matrices Rows (axis 0) are actual labels and columns (axis 1) are predicted labels. En Scikit-learn, las filas de las matriaces de confusión (eje 0) son etiquetas reales y las columnas (eje 1) son etiquetas previstas.
| | 0 | 1 | | | 0 | 1 |
| :---: | :---: | :---: | | :---: | :---: | :---: |
| 0 | TN | FP | | 0 | TN | FP |
| 1 | FN | TP | | 1 | FN | TP |
What's going on here? Let's say our model is asked to classify pumpkins between two binary categories, category 'orange' and category 'not-orange'. ¿Qué pasa aquí? Digamos que se le pidió a tu modelo clasificar las calabaas entre dos categorías binarias, la categoría 'orange' y la categoría 'not-orange'.
- If your model predicts a pumpkin as not orange and it belongs to category 'not-orange' in reality we call it a true negative, shown by the top left number. - Si tu modelo predice una calabaza como no naranja y esta pertenece a la categoría 'not-orange' en realidad la llamamos como un verdadero negativo, mostrado por el número superior izquierdo.
- If your model predicts a pumpkin as orange and it belongs to category 'not-orange' in reality we call it a false negative, shown by the bottom left number. - Si tu modelo precice una calabaza como naranja y esta pertenece a la categoría 'not-orange' en realidad la llamamos como un falso negativo, mostrado por el número inferior izquierdo.
- If your model predicts a pumpkin as not orange and it belongs to category 'orange' in reality we call it a false positive, shown by the top right number. - Si tu modelo predice una calabaza como no naranja y este pertenece a la categoría 'orange' en realidad la llamamos como un falso positivo, mostrado por el número superior derecho.
- If your model predicts a pumpkin as orange and it belongs to category 'orange' in reality we call it a true positive, shown by the bottom right number. - Si tu modelo predice una calabaza como naranja y esta pertenece a la categoría 'naranja' en realidad la llamamos como un verdadero positivo, mostrado por el número inferior derecho.
As you might have guessed it's preferable to have a larger number of true positives and true negatives and a lower number of false positives and false negatives, which implies that the model performs better. Como habrás adivinado, es preferible tener un número mayor de verdaderos positivos y verdaderos negativos, y un número menor de falsos positivos y falsos negativos, lo cual implica que el modelo se desempeña mejor.
How does the confusion matrix relate to precision and recall? Remember, the classification report printed above showed precision (0.83) and recall (0.98). ¿Cómo se relaciona la matriz de confusión con precision (precisión) y recall (recuerdo)? Recuerda, el reporte de clasificación impreso arriba mostró precisión (0.83) y recuerdo (0.98).
Precision = tp / (tp + fp) = 162 / (162 + 33) = 0.8307692307692308 Precision = tp / (tp + fp) = 162 / (162 + 33) = 0.8307692307692308
Recall = tp / (tp + fn) = 162 / (162 + 4) = 0.9759036144578314 Recall = tp / (tp + fn) = 162 / (162 + 4) = 0.9759036144578314
✅ Q: According to the confusion matrix, how did the model do? A: Not too bad; there are a good number of true negatives but also several false negatives. ✅ Q: De acuerdo a la matriz de confusión, ¿cómo lo hizo el modelo? A: No tan mal; existe un buen número de verdaderos positivos pero también varios falsos negativos.
Let's revisit the terms we saw earlier with the help of the confusion matrix's mapping of TP/TN and FP/FN: Repasemos los término que vimos anteriormente con la ayuda de la asignación de la matriz de confusión de TP/TN y FP/FN:
🎓 Precision: TP/(TP + FP) The fraction of relevant instances among the retrieved instances (e.g. which labels were well-labeled) 🎓 Precision: TP/(TP + FP) La fración de instancias relevantes entre las instancias recuperadas (ejemplo, qué etiquetas fueron bien etiquetadas)
🎓 Recall: TP/(TP + FN) The fraction of relevant instances that were retrieved, whether well-labeled or not 🎓 Recall: TP/(TP + FN) La fracción de instancias relevantes que fueron recuperadas, bien etiquetadas o no
🎓 f1-score: (2 * precision * recall)/(precision + recall) A weighted average of the precision and recall, with best being 1 and worst being 0 🎓 f1-score: (2 * precision * recall)/(precision + recall) Un promedio ponderado de precisión y recuerdo, siendo lo mejor 1 y lo pero 0
🎓 Support: The number of occurrences of each label retrieved 🎓 Soporte: El número de ocurrencias de cada etiqueta recuperada
🎓 Accuracy: (TP + TN)/(TP + TN + FP + FN) The percentage of labels predicted accurately for a sample. 🎓 Precisión: (TP + TN)/(TP + TN + FP + FN) El porcentaje de etiquetas previstas de forma precisa para la muestra.
🎓 Macro Avg: The calculation of the unweighted mean metrics for each label, not taking label imbalance into account. 🎓 Promedio de macros: El cálculo de métricas medias no ponderadas para cada etiqueta, no tomando en cuenta el desequilibrio de etiquetas.
🎓 Weighted Avg: The calculation of the mean metrics for each label, taking label imbalance into account by weighting them by their support (the number of true instances for each label). 🎓 Promedio ponderado: El cálculo de las métricas medias para cada etiqueta, tomando en cuenta el desequilibrio de etiquetas al ponderarlas po su soporte (el número de instancias verdaderas para cada etiqueta).
Can you think which metric you should watch if you want your model to reduce the number of false negatives? ¿Puedes pensar cuáles métrcias debes observar si quieres que tu modelo para reducir el número de falsos negativos?
## Visualize the ROC curve of this model ## Visualiza la curva ROC de este modelo
This is not a bad model; its accuracy is in the 80% range so ideally you could use it to predict the color of a pumpkin given a set of variables. Este no es un mal modelo; su precisión está en el rango de 80% ya que idealmente puedes usarlo para precedir el color de una calabaza dado un conjunto de variables.
Let's do one more visualization to see the so-called 'ROC' score: Hagamos una visualización más para ver el así llamado puntaje 'ROC':
```python ```python
from sklearn.metrics import roc_curve, roc_auc_score from sklearn.metrics import roc_curve, roc_auc_score
@ -279,31 +280,34 @@ fpr, tpr, thresholds = roc_curve(y_test, y_scores[:,1])
sns.lineplot([0, 1], [0, 1]) sns.lineplot([0, 1], [0, 1])
sns.lineplot(fpr, tpr) sns.lineplot(fpr, tpr)
``` ```
Using Seaborn again, plot the model's [Receiving Operating Characteristic](https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html?highlight=roc) or ROC. ROC curves are often used to get a view of the output of a classifier in terms of its true vs. false positives. "ROC curves typically feature true positive rate on the Y axis, and false positive rate on the X axis." Thus, the steepness of the curve and the space between the midpoint line and the curve matter: you want a curve that quickly heads up and over the line. In our case, there are false positives to start with, and then the line heads up and over properly:
![ROC](./images/ROC.png) Usando de nuevo Seaborn, grafica la [característica operativa de recepción](https://scikit-learn.org/stable/auto_examples/model_selection/plot_roc.html?highlight=roc) del modelo o ROC. Las curvas ROC curves son usadas comúnmente para obtener una vista de la salida de un clasificador en términos de sus verdaderos positivos vs falsos positivos. "Las curvas ROC presentan típicamente la tasa de verdaderos positivos en el eje Y, y la tasa falsos positivos en el eje X." Así, la inclinación de la curvay el espeacio entre la línea del punto medio y la curva importan: quieres una curva que suba rápidamente y sobre la línea. En nuestro caso, hay falsos positivos para empezar, y luego la línea sube hacía arriba y continua propiamente:
![ROC](../images/ROC.png)
Finally, use Scikit-learn's [`roc_auc_score` API](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html?highlight=roc_auc#sklearn.metrics.roc_auc_score) to compute the actual 'Area Under the Curve' (AUC): Finalmente, usa la [API `roc_auc_score`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html?highlight=roc_auc#sklearn.metrics.roc_auc_score) de Scikit-learn para calcular el 'Área bajo la curva' real (AUC):
```python ```python
auc = roc_auc_score(y_test,y_scores[:,1]) auc = roc_auc_score(y_test,y_scores[:,1])
print(auc) print(auc)
``` ```
The result is `0.6976998904709748`. Given that the AUC ranges from 0 to 1, you want a big score, since a model that is 100% correct in its predictions will have an AUC of 1; in this case, the model is _pretty good_.
In future lessons on classifications, you will learn how to iterate to improve your model's scores. But for now, congratulations! You've completed these regression lessons! El resultado es `0.6976998904709748`. Dado que la AUC varía entre 0 y 1, quieres un puntaje grande, ya que un modelo que es 100% correcto en sus predicciones tendrá un AUC de 1; en este caso el modelo es _bastante bueno_.
En futuras lecciones de clasificación, aprenderás cómo iterar para mejorar los puntajes de tus modelos. Pero por ahora, ¡felicitaciones!, ¡Haz completado estas lecciones de regresión!
--- ---
## 🚀Challenge
There's a lot more to unpack regarding logistic regression! But the best way to learn is to experiment. Find a dataset that lends itself to this type of analysis and build a model with it. What do you learn? tip: try [Kaggle](https://www.kaggle.com/search?q=logistic+regression+datasets) for interesting datasets. ## 🚀Desafío
¡Hay mucho más para desempacar respecto a la regresión logística! Pero la mejor forma de aprender es experimentar. Encuentra un conjunto de datos que se preste para este tipo de análisis y construye un modelo con él. ¿Qué aprendes? tipo: prueba [Kaggle](https://www.kaggle.com/search?q=logistic+regression+datasets) por conjuntos de datos interesantes.
## [Post-lecture quiz](https://white-water-09ec41f0f.azurestaticapps.net/quiz/16/) ## [Examen posterior a la lección](https://white-water-09ec41f0f.azurestaticapps.net/quiz/16/)
## Review & Self Study ## Revisión & autoestudio
Read the first few pages of [this paper from Stanford](https://web.stanford.edu/~jurafsky/slp3/5.pdf) on some practical uses for logistic regression. Think about tasks that are better suited for one or the other type of regression tasks that we have studied up to this point. What would work best? Lee las primeras páginas de este [artículo de Stanford](https://web.stanford.edu/~jurafsky/slp3/5.pdf) de algunos usos prácticos para la regresión logística. Piensa en las tareas que se ajustan mejor para uno u otro tipo de tareas de regresión que estudiamos hasta el momento. ¿Que funcionaría mejor?
## Assignment ## Asignación
[Retrying this regression](assignment.md) [Reintentando esta regresión](assignment.es.md)

Loading…
Cancel
Save