An Introduction to Sceptical Data Science Part II — Making Predictions with Linear Regression

This post focuses on making predictions, ascertaining the correctness of these predictions, and trying to partly improve them. This used to be a Practical notebook for the Data Mining course I taught at Tilburg University. Most of the content assumes no prior knowledge of the field whatsoever (the previous post can be found here, and the associated lecture is embedded below), and is tailored at conducting critical analyses. Assignments are included.

NOTE: this post’s previous version included the ‘Boston housing dataset’ from Kaggle. This dataset (among including many inflammatory features) casually assumes people prefer living in segregated neighborhoods. In tandem with it being deprecated from various ML libraries (e.g. sklearn), I have removed its use from this post as well.

🧭 Preparing for Prediction

From what you have seen up until now, you can probably make a pretty good prediction if someone survived the Titanic. Say that we offer you this table of people as instances and some of their features:

\[\begin{array}{lrlrl} \hline & \mathtt{gender} & \mathtt{age} & \mathtt{pclass} & \mathtt{fare} \\ \hline 1 & \text{m} & 51 & \text{higher} & 80 \\ 2 & \text{f} & 40 & \text{middle} & 60 \\ 3 & \text{m} & 25 & \text{lower} & 10 \\ \hline \end{array}\]

How would you rank the survivability of these three persons? Now for a bit more complicated one:

\[\begin{array}{lrlrl} \hline & \mathtt{gender} & \mathtt{age} & \mathtt{pclass} & \mathtt{fare} \\ \hline 1 & \text{m} & 27 & \text{higher} & ? \\ 2 & \text{f} & 21 & \text{middle} & ? \\ 3 & \text{f} & 35 & \text{lower} & ? \\ \hline \end{array}\]

What would you predict is (ballpark) the fair that these three person bought their tickets for?

⛏️ Data Mining

This is exactly the kind of process we want to automate using Data Mining techniques. Up until now, we’ve used the Titanic data, which is pretty simple, can be well understood in historical context by humans, and therefore you can at least say something about the likelihood of survival. The fares, on the other hand, require a bit more of a complex view on the data. You can sort of guess what ballpark the fares would be in based on the pclass, but the nuances are harder to guesstimate. These two tasks involve prediction: survived — a discrete feature (classification), where we have a limited set of options to choose from, and fare — a continuous feature (regression), where we’d like to be as close to the actual number as possible.

KDD workflow

Commonly understood steps of a Data Mining (/KDD) workflow.

Data Mining is in general the combination of several techniques:

  1. Managing your data.
  2. A thorough understanding of its contents and potential.
  3. The ability to manually select and alter the data to create useful insights and visualizations.
  4. Understanding and applying predictive models that use the full complexity of the data to create even better insights.
  5. Making sure these models are correctly evaluated and being able to judge their usefulness.
  6. Communicating these results.

This series will mostly focus on 2-5. The posts will try to train you in 3-5. However, 2 will require your own effort but is the most important step to the success of actually applying 3-5.

🔮 Making Predictions

penguins

For this post, we are first going to take a model-driven approach rather than a data-driven one; we’ll try to fit a Linear Regression model (see figure 👇 for a quick visual refresher) that hopefully predicts with low error, and see what kind of information we can get from it. As our data, we’ll be looking at the Palmer Penguins dataset from Gorman, Williams & Fraser; measurements of three penguin species (Adélie, Chinstrap and Gentoo) on three islands in the Palmer Archipelago, Antarctica. It’s a popular ‘toy’ dataset for regression, given that it only has 344 instances.

ℹ️ Task     💽 Data (raw)     🐙 Git

Linear regression with residuals

Linear Regression and residuals (error). For 2-d (1 feature, 1 target), the fit of the line is determined by $Y = \beta_0 + \beta_1 \cdot X$ where $\beta_0$ is the intercept (or bias coefficient) and $\beta_1$ the coefficient for the first feature (determining the slope of the line).

If you’re still unsure how prediction and error assessment for this type of model works, try the following given bias and coefficients:

   -1.0408 * bill_length_mm +
 -100.2515 * bill_depth_mm +
   37.2790 * flipper_length_mm +
  563.6088 * sex +
-1804.3772

You are provided with the following test data (sex is 1 for male and 0 for female penguins):

\[\begin{array}{rrrr} \hline \text{bill\_length\_mm} & \text{bill\_depth\_mm} & \text{flipper\_length\_mm} & \text{sex} \\ \hline 39.5 & 16.7 & 178 & 0 \\ \hline \end{array}\]

🚩 Task 1

Given the true body mass (so the actual weight of the penguin) $Y$, use the predicted body mass $\hat{Y}$ to calculate the Root Mean Squared Error (RMSE) for the body mass in the equation below 👇. You do this by (for each of the feature vectors) subtracting the actual ($y_i$) from the predicted ($\hat{y_i}$) value, and squaring them. Here, $i$ is the index of any instance $y$ in $Y$ (and thus $X$). After, you take the sum over all these values (should be $i=1$ value, because 1 instance), divide it by the amount of predictions ($n=1$), and take the root.

\[Y = \langle 3250 \rangle\] \[\text{RMSE} = \sqrt{ \frac{ \sum^n_{i=1}(\hat{y}_i - y_i)^2}{n}}\]

So, that was a tedious exercise you probably don’t want to do again. Luckily, we can automate the fitting of the regression line, making predictions, and calculating RMSE with scikit-learn.


📈 Linear Regression with Scikit-Learn

In the following piece of code we are going to load the data, select the columns we’ll use (with our target last), turn sex into a number, and drop the few penguins with missing measurements. For an explanation of what’s going on, see the footnotes.1

import pandas as pd

# working locally: './penguins.csv'
df = pd.read_csv('https://raw.githubusercontent.com/mwaskom/seaborn-data/master/penguins.csv')

columns = ['bill_length_mm', 'bill_depth_mm', 'flipper_length_mm',
           'sex', 'body_mass_g']
df = df[columns].copy()  # keep only these columns, in this order
df['sex'] = df['sex'].map({'MALE': 1, 'FEMALE': 0})
df = df.dropna()  # drop penguins with missing values

df

To set up for predicting anything, we first have to split our data into features and a target. Hence, we want to put body_mass_g into its own variable2 $Y$ — and everything else into $X$. For the label, we can just simply select the column from the dataframe and put it in y, like so:

y = df["body_mass_g"]

Now comes a bit more complicated syntax for selecting everything but body_mass_g from the dataframe. For this we can use the loc() method.3 As such:

X = df.loc[:, df.columns != "body_mass_g"]

Now, we want to create a train and test set. We can do this pretty easily with the following piece of code:

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = \
    train_test_split(X, y, test_size=0.2, random_state=42)

Here, train_test_split() returns multiple objects, so that’s why there’s more variable names before the = sign. The splitting does multiple things under the hood:

For regression, we first initialize the model (this is where you’d want to set the parameters). After, we can call the fit() method on our training set (X_train), and labels (y_train) (scikit-learn has very comprehensible documentation. Look up the parameters for the model and its methods!).

from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(X_train, y_train)

The classifier is now fitted, or trained. We can first try to interpret the coefficients. This can be done by calling the coef_ attribute (see the Attributes section in the documentation), and then zipping (concatenating)4 it with the column names, like below:

list(zip(df.columns[:-1], lr.coef_))

Now that the model is trained, we can use it to perform prediction on our (unseen) test set (X_test), and then evaluate how far the predicted values are from the actual true values (y_test). We do this by providing one of the sklearn metrics (root_mean_squared_error()) with these two variables.

from sklearn.metrics import root_mean_squared_error
import numpy as np

y_pred = lr.predict(X_test)
rmse_model = root_mean_squared_error(y_test, y_pred)
rmse_model

Interpret all the output we have generated up until now. Then finally, solve:

🚩 Task 2


🔬 Further Analysis

With our model-driven results we have some empirical indication of how well we can predict the body mass of a penguin given the features (and data) we were provided with. Note that even if very successful, this shouldn’t be presented as a general model of predicting penguin weight! The final scores we are looking at are constrained by:

Anyway, let’s get into some analysis. If we want a nicer visualization of the coefficients, we can simply dump them in a dataframe and get a bar plot going. Like so:

cdf = pd.DataFrame([list(lr.coef_)], columns=df.columns[:-1])
plt = cdf.plot(figsize=(15,5), kind='bar', legend=True)
plt.xaxis.set_visible(False)

We can control the size to see the bars a bit better using figsize, where the first part of figsize=( , ) is the width, and the second the height. Because there are no values on the x-axis of the plot, we can just turn that off. For this we have to store the plot in a variable first (plt), after which we can manipulate the visibility (last line). Mostly you will see how much (visual) impact the penguin’s sex has in the model that we fitted (males are heavier). bill_depth_mm also seems to have quite an impact, but a negative one. Does that make intuitive sense if you’re not into penguins?

📏 Baseline

Up until now we’ve only looked at the test scores; we don’t actually know if our model actually learned something (i.e., if it’s not making some silly predictions, like that all penguins are heckin’ chonkers). An easy way to get a baseline score for a regression model is to take a mean baseline. For this, we can simply take:

df["body_mass_g"].mean()

We’ll have to make this prediction as many times as we have test items though, so we can take the length (len) of y_test, and fill a list up with as many times the mean. This looks like:

bl = [df["body_mass_g"].mean()] * len(y_test)
bl

Now we have 67 entries with the exact same baseline prediction, great. We can compare it with the true y_test and see how far we are off:

rmse_bl = np.sqrt(mean_squared_error(y_test, bl))
rmse_bl

🚩 Task 3

🧐 Post-hoc Feature Analysis

The regression coefficients have given us some indication of feature importance. We know which ones affect the body mass positively, and which do negatively — and to what intensity. But how much does that correspond to what we would expect from a general correlation between that specific feature, and our target? Let’s find out:

from scipy.stats import pearsonr
df.plot(x='bill_length_mm', y='body_mass_g', kind='scatter')
pearsonr(df['bill_length_mm'], df['body_mass_g'])

Previously, you could have observed bill_length_mm to have barely any effect (even a slightly negative one). According to our model, it hardly matters compared to flipper_length_mm. Let’s inspect that one as well:

df.plot(x='flipper_length_mm', y='body_mass_g', kind='scatter')
pearsonr(df['flipper_length_mm'], df['body_mass_g'])

🚩 Task 4

🗺️ More Plots

As we’re looking at plots anyways, let’s try to see if we can get a bit more insight into the penguin data. For example, penguins with shallow bills tend to have long flippers, and to be heavy:

df.plot(x='bill_depth_mm', y='flipper_length_mm', c='body_mass_g',
        colormap='Oranges', kind='scatter')

Males are heavier than females:

df.boxplot(column='body_mass_g', by='sex')

⚖️ Why Normalize?

As we arrive at boxplots, hopefully you’ll see some oddities and issues with the following plot (Note that rot is used to rotate the labels on the x-axis by 90 degrees to fit the names.):

df.boxplot(figsize=(20,5), rot=90)

Most of the plots are barely visible, because the ranges of the feature values differ tremendously. There’s quite a simple fix for that, which is normalizing by z-score.

df_norm = (df - df.mean()) / (df.max() - df.min())
df_norm.boxplot(figsize=(20,5), rot=90)

In addition to fixing our boxplot, standardizing or normalizing also potentially improves algorithms (as the space they need to fit a line in is greatly reduced). Let’s see how it affects ours, start with:

X = df_norm.loc[:, df_norm.columns != "body_mass_g"]

🚩 Task 5

🏁 You’ve reached the end of the second post! Solutions are below.

✅ Solutions

🏁 Task 1

🏁 Task 2

🏁 Task 3

🏁 Task 4

🏁 Task 5

  1. To boil it down, columns is a list; an ordered collection of strings (our column names between quotes). Selecting df[columns] keeps only those columns, in that order, so that our target body_mass_g ends up last (we’ll rely on that later). We leave out species and island for now, as they are text that a Linear Regression model can’t use directly. The map() method replaces the values of sex with numbers (1 for male, 0 for female), and dropna() drops the 11 penguins that miss at least one of these values. That leaves 333 penguins. ↩︎

  2. Please be aware of the mixed use of the word variable between the Python variable (a name reference to a particular object, like an integer, list, or dataframe) and that used in data mining (where it is explicitly a feature vector). ↩︎

  3. This ‘locates’ (thus subsets) columns that are according to a certain condition. Our specific condition is that we want all but body_mass_g. We could manually type out all the column names, but df.columns != "body_mass_g" gives us all the indices that are not the body mass. If you try the command by itself you’ll see that it gives a list of True and False when something meets the condition (is not body_mass_g). The loc function has two parts for subsetting: by rows (first part between [ , ]) and by columns (second part). Given that we want all the rows, we type :, and provide the indices in the second part. ↩︎

  4. No need to really understand what’s going on here. Basically, the coefficient values are ordered according to our features, so here we just link the column names (minus our target) with those values. Regardless, just remember it as a way to look at the coefficients. ↩︎