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.

Commonly understood steps of a Data Mining (/KDD) workflow.
Data Mining is in general the combination of several techniques:
- Managing your data.
- A thorough understanding of its contents and potential.
- The ability to manually select and alter the data to create useful insights and visualizations.
- Understanding and applying predictive models that use the full complexity of the data to create even better insights.
- Making sure these models are correctly evaluated and being able to judge their usefulness.
- 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
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.
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):
🚩 Task 1
- Use the given coefficients and bias to predict $\hat{y}$: the body mass in grams (by hand) for the feature vectors in the table above ($X_{\text{test}}$). See below for instructions.
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:
- It makes sure the training set (
X_train) is split into 80% of the total data, and the test set (X_test) is 20% (test_size=0.2). - It stratifies the data, so that the distribution of the target is the same in the training set as it is in the set. As such, there’s a proportionally equal amount of penguins in both sets (i.e., if the total data had 10, test now has 2, and train 8).
- It randomly shuffles the data, so that the model can’t infer anything out of the order in which the dataset was composed. As a result, if we want to be able to reproduce our exact results, we need to provide a seed to this (
random_state=42) so that the ‘random’ order is the same if we were to repeat the experiment.
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
- Fit Linear Regression on the Palmer Penguins dataset, interpret the coefficients. What would these mean?
- How do we assess if the model has a) actually learned something, and b) will generalize well?
🔬 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:
- Our data (amount and sample) — e have three species from three islands, measured over a few breeding seasons, and arguably a very small sample. One could question how well that translates to other colonies, other penguin species, other years, etc. Can we predict penguins at the end of a harsh winter? What about their chicks?
- Our model (algorithm and parameters) — we chose the simplest implementation of regression; Linear Regression. We did not tune the algorithm to perform better, nor have we thought about choosing other models that might be better suited for the type of data we are dealing with.
- Our evaluation (scheme and scores) — while RMSE gives a fair indication of how well a particular model approximates the actual pattern underlying the data, we do need to realize how much data we are using for training and testing. We might also have to look at some other evaluation metrics to get a better indication (like MAE). Moreover, if we will tune any of our parameters, we need to consider doing that on a different data split altogether. The latter we’re not going into for this particular post.
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
- Interpret the baseline score and compare it to our previous RMSE score. How would you say the model is performing?
- Looking at the error, and
body_mass_g, determine if the model is useful in practice.
🧐 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
- Interpreting the plots (and more importantly the correlations), do these correspond to the regression coefficients?
- What is the reason behind this?
🗺️ 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
- From here on out you are on your own. Use the new normalized X (repeat all steps we did before from there on out) to get a
rmse_normand compare it to the baseline andrmse_model. How much did we improve?
🏁 You’ve reached the end of the second post! Solutions are below.
✅ Solutions
🏁 Task 1
- The predicted value should be around $3116$ grams. This makes the RMSE around $134$.
🏁 Task 2
- Positive means it increases the body mass by some factor (in grams per unit of that feature), negative coefficients mean it decreases the body mass by this factor. Note that they are on different scales though!
- a) we would need some ‘stupid’ baseline that we can use to predict without learning anything (like the mean of all the values that we saw in our training dataset). b) we have a test set, so we know the performance on unseen data. Actual generalizability isn’t easy to comment on with small datasets. The more instances we have (especially across seasons and colonies; food availability changes from year to year), the more confident we can be that it still holds.
🏁 Task 3
- Baseline error should be around $794$, whilst our model error is around $316$. From this, we can at least conclude that is quite a bit better than baseline — the model is at least learning some pattern in the data. We have to further interpret the error to make an actual quality estimate, however. See below.
- Let’s see what this
body_mass_gactually represents. The documentation gives the following info: ‘‘body mass (grams)’’. This means that per penguin we are generally about 316 grams (plus or minus) off. Looking atdf["body_mass_g"].mean(), it can be observed that the average penguin weighs about 4207 grams with a standard deviation (df["body_mass_g"].std()) of about 805 grams. I’m not a penguin biologist, but an error of about a third of a kilogram is fine for telling a small penguin from a big one, and probably too coarse for tracking how much weight a penguin gains or loses over a season. You can further inspecty_predandy_test(using e.g.np.mean, or just outputting the values) to see how far the model is off in some specific cases (spoiler: on average it is only about 9 grams too low, so it does not systematically over- or undershoot).
🏁 Task 4
- No, they don’t.
bill_length_mmcorrelates quite strongly withbody_mass_g($r \approx 0.59$), yet the model gives it almost no weight;flipper_length_mm($r \approx 0.87$) already covers that information.bill_depth_mmis even stranger: overall it correlates negatively with body mass ($r \approx -0.47$), but within each species the correlation is positive (between $0.58$ and $0.72$). The Gentoo penguins are heavy and have shallow bills, and we leftspeciesout of our model. - Linear Regression models multiple dimensions simultaneously when adding all features. As such, some features might be weighted lower (e.g. if their values have a smaller range, or if another feature already explains the same thing). You can try the boxplot again after normalizing to get a ‘better’ representation.
🏁 Task 5
- RMSE for the normalized model should be exactly the same. Note that this applies to standard features; when later we go into interaction features, the importance will become more evident.
To boil it down,
columnsis a list; an ordered collection of strings (our column names between quotes). Selectingdf[columns]keeps only those columns, in that order, so that our targetbody_mass_gends up last (we’ll rely on that later). We leave outspeciesandislandfor now, as they are text that a Linear Regression model can’t use directly. Themap()method replaces the values ofsexwith numbers (1 for male, 0 for female), anddropna()drops the 11 penguins that miss at least one of these values. That leaves 333 penguins. ↩︎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). ↩︎
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, butdf.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 notbody_mass_g). Thelocfunction 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. ↩︎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. ↩︎