![Logistic vs. linear regression infographic](https://github.com/microsoft/ML-For-Beginners/blob/main/2-Regression/4-Logistic/images/linear-vs-logistic.png)
![Logistic vs. linear regression infographic](../../images/linear-vs-logistic.png)
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?
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?
In this lesson, you will learn:
- 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-77952-leestott)
✅ Deepen your understanding of working with this type of regression in this [Learn module](https://learn.microsoft.com/training/modules/introduction-classification-models/?WT.mc_id=academic-77952-leestott)
#### **Prerequisite**
## Prerequisite
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`.
@ -70,7 +70,17 @@ Logistic regression differs from linear regression, which you learned about prev
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*.
![Infographic by Dasani Madipalli](../../images/pumpkin-classifier.png){width="600"}
![Infographic by Dasani Madipalli](../../images/pumpkin-classifier.png)
### Other classifications
There are other types of logistic regression, including multinomial and ordinal:
- **Multinomial**, which involves having more than one category - "Orange, White, and Striped".
- **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-vs-ordinal.png)
#### **Variables DO NOT have to correlate**
@ -82,9 +92,11 @@ Logistic regression will give more accurate results if you use more data; our sm
✅ Think about the types of data that would lend themselves well to logistic regression
## 1. Tidy the data
## Exercise - tidy the data
First, clean the data a bit, dropping null values and selecting only some of the columns:
Now, the fun begins! Let's start by importing the data, cleaning the data a bit, dropping rows containing missing values and selecting only some of the columns:
Sometimes, we may want some little more information on our data. We can have a look at the `data`, `its structure` and the `data type` of its features by using the [*glimpse()*](https://pillar.r-lib.org/reference/glimpse.html) function as below:
You can always take a peek at your new dataframe, by using the [*glimpse()*](https://pillar.r-lib.org/reference/glimpse.html) function as below:
```{r glimpse}
pumpkins_select %>%
glimpse()
```
Wow! Seems that all our columns are all of type *character*, further alluding that they are all categorical.
Let's confirm that we will actually be doing a binary classification problem:
```{r distinct color}
# Subset distinct observations in outcome column
pumpkins_select %>%
distinct(color)
```
### Visualization - categorical plot
By now you have loaded up the 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 ggplot library.
The ggplot library offers some neat ways to visualize your data. For example, you can compare distributions of the data for each Variety and Color in a categorical plot.
1. Create such a plot by using the geombar function, using our pumpkin data, and specifying a color mapping for each pumpkin category (orange or white):
```{r}
# Specify colors for each value of the hue variable
palette <- c(ORANGE = "orange", WHITE = "wheat")
# Create the bar plot
ggplot(pumpkins_select, aes(y = variety, fill = color)) +
geom_bar(position = "dodge") +
scale_fill_manual(values = palette) +
labs(y = "Variety", fill = "Color") +
theme_minimal()
```
🥳🥳 That went down well!
By observing the data, you can see how the Color data relates to Variety.
## 2. Explore the data
✅ Given this categorical plot, what are some interesting explorations you can envision?
The goal of data exploration is to try to understand the `relationships` between its attributes; in particular, any apparent correlation between the *features* and the *label* your model will try to predict. One way of doing this is by using data visualization.
### Data pre-processing: feature encoding
Given our the data types of our columns, we can `encode` them and be on our way to making some visualizations. This simply involves `translating` a column with `categorical values` for example our columns of type *char*, into one or more `numeric columns` that take the place of the original. - Something we did in our [last lesson](https://github.com/microsoft/ML-For-Beginners/blob/main/2-Regression/3-Linear/solution/lesson_3.html).
Our pumpkins dataset contains string values for all its columns. Working with categorical data is intuitive for humans but not for machines. Machine learning algorithms work well with numbers. That's why encoding is a very important step in the data pre-processing phase, since it enables us to turn categorical data into numerical data, without losing any information. Good encoding leads to building a good model.
For feature encoding there are two main types of encoders:
@ -164,26 +192,14 @@ baked_pumpkins %>%
slice_head(n = 5)
```
Now, let's make a categorical plot showing the distribution of the predictors with respect to the outcome color!
✅ What are the advantages of using an ordinal encoder for the Item Size column?
```{r cat plot pumpkins-colors-variety}
# Specify colors for each value of the hue variable
palette <- c(ORANGE = "orange", WHITE = "wheat")
### Analyse relationships between variables
# Create the bar plot
ggplot(pumpkins_select, aes(y = variety, fill = color)) +
geom_bar(position = "dodge") +
scale_fill_manual(values = palette) +
labs(y = "Variety", fill = "Color") +
theme_minimal()
```
Amazing🤩! For some of the features, there's a noticeable difference in the distribution for each color label. For instance, it seems the white pumpkins can be found in smaller packages and in some particular varieties of pumpkins. The *item_size* category also seems to make a difference in the color distribution. These features may help predict the color of a pumpkin.
### **Analysing relationships between features and label**
```{r}
Now that we have pre-processed our data, we can analyse the relationships between the features and the label to grasp an idea of how well the model will be able to predict the label given the features. The best way to perform this kind of analysis is plotting the data.
We'll be using again the ggplot geom_boxplot_ function, to visualize the relationships between Item Size, Variety and Color in a categorical plot. To better plot the data we'll be using the encoded Item Size column and the unencoded Variety column.
```{r boxplot}
# Define the color palette
palette <- c(ORANGE = "orange", WHITE = "wheat")
@ -206,14 +222,11 @@ ggplot(pumpkins_select_plot, aes(x = `item_size`, y = color, fill = color)) +
Let's now focus on a specific relationship: Item Size and Color!
#### **Use a swarm plot**
#### Use a swarm plot
Color is a binary category (Orange or Not), it's called `categorical data`. There are other various ways of [visualizing categorical data](https://seaborn.pydata.org/tutorial/categorical.html?highlight=bar).
Since Color is a binary category (White or Not), it needs 'a [specialized approach](https://github.com/rstudio/cheatsheets/blob/main/data-visualization.pdf) to visualization'.
Try a `swarm plot` to show the distribution of color with respect to the item_size.
@ -228,13 +241,12 @@ baked_pumpkins %>%
scale_color_brewer(palette = "Dark2", direction = -1) +
theme(legend.position = "none")
```
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.
## 3. Build your model
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.
Let's begin by splitting the data into `training` and `test` sets. The training set is used to train a classifier so that it finds a statistical relationship between the features and the label value.
## Build your model
It is best practice to hold out some of your data for **testing** in order to get a better estimate of how your models will perform on new data by comparing the predicted labels with the already known labels in the test set. [rsample](https://rsample.tidymodels.org/), a package in Tidymodels, provides infrastructure for efficient data splitting and resampling:
Select the variables you want to use in your classification model and split the data into training and test sets. [rsample](https://rsample.tidymodels.org/), a package in Tidymodels, provides infrastructure for efficient data splitting and resampling:
```{r split_data}
# Split data into 80% for training and 20% for testing
Now that we have a recipe and a model specification, we need to find a way of bundling them together into an object that will first preprocess the data (prep+bake behind the scenes), fit the model on the preprocessed data and also allow for potential post-processing activities.
@ -283,7 +294,6 @@ log_reg_wf <- workflow() %>%
# Print out the workflow
log_reg_wf
```
After a workflow has been *specified*, a model can be `trained` using the [`fit()`](https://tidymodels.github.io/parsnip/reference/fit.html) function. The workflow will estimate a recipe and preprocess the data before training, so we won't have to manually do that using prep and bake.
@ -296,8 +306,6 @@ wf_fit <- log_reg_wf %>%
# Print the trained workflow
wf_fit
```
The model print out shows the coefficients learned during training.
Very nice! This provides some more insights into how logistic regression works.
### Better comprehension via a confusion matrix
Comparing each prediction with its corresponding "ground truth" actual value isn't a very efficient way to determine how well the model is predicting. Fortunately, Tidymodels has a few more tricks up its sleeve: [`yardstick`](https://yardstick.tidymodels.org/) - a package used to measure the effectiveness of models using performance metrics.
One performance metric associated with classification problems is the [`confusion matrix`](https://wikipedia.org/wiki/Confusion_matrix). A confusion matrix describes how well a classification model performs. A confusion matrix tabulates how many examples in each class were correctly classified by a model. In our case, it will show you how many orange pumpkins were classified as orange and how many white pumpkins were classified as white; the confusion matrix also shows you how many were classified into the **wrong** categories.
eval_metrics(data = results, truth = color, estimate = .pred_class)
```
#### **Visualize the ROC curve of this model**
For a start, this is not a bad model; its precision, recall, F measure and accuracy are in the 90% range so ideally you could use it to predict the color of a pumpkin given a set of variables. It also seems that our model was not really able to identify the white pumpkins 🧐. Could you guess why? One reason could be because of the high prevalence of ORANGE pumpkins in our training set making our model more inclined to predict the majority class.
## Visualize the ROC curve of this model
Let's do one more visualization to see the so-called [`ROC score`](https://en.wikipedia.org/wiki/Receiver_operating_characteristic):
Let's do one more visualization to see the so-called [`ROC curve`](https://en.wikipedia.org/wiki/Receiver_operating_characteristic):
```{r roc_curve}
# Make a roc_curve
results %>%
roc_curve(color, .pred_ORANGE) %>%
autoplot()
```
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`/Sensitivity on the Y axis, and `False Positive Rate`/1-Specificity 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.
@ -395,15 +401,17 @@ Finally, let's use `yardstick::roc_auc()` to calculate the actual Area Under the
# Calculate area under curve
results %>%
roc_auc(color, .pred_ORANGE)
```
The result is around `0.947`. 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*.
The result is around `0.975`. 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 improve your model's scores (such as dealing with imbalanced data in this case).
But for now, congratulations 🎉🎉🎉! You've completed these regression lessons!
## 🚀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.
## Review & Self Study
You R awesome!
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?
![Artwork by \@allison_horst](../../images/r_learners_sm.jpeg)