Learning path: Predict a Number: Regression from Scratch to Regularisation · Step 4 of 6
Regression Metrics: MAE, RMSE, R-squared and the Baseline to Beat
Score a regression model honestly: MAE, MSE and RMSE from four darts, then the insurance model on 268 test people, a DummyRegressor baseline to beat, R-squared and adjusted R-squared, and a residual plot.
What you will learn
- Compute MAE, MSE and RMSE and explain why RMSE is bigger than MAE
- Score a model against a DummyRegressor baseline
- Explain R-squared as 1 minus model MSE over mean-guess MSE, including negative values
- Compute adjusted R-squared and read a residual plot
Before you start
- Linear Regression and the Cost Function
- Linear Regression in scikit-learn
How good is a dart player? None of the darts hits the exact centre, so you measure how far each one landed from the bullseye. Four throws: 1 cm, 2 cm, 3 cm and 6 cm off. A good player has small misses on average.
A model that predicts a number is the same. Each miss is the residual, actual minus predicted. In this lesson you'll turn many misses into one honest score, compare it with a baseline, and look at the misses themselves.
Four misses, three scores
import numpy as np
misses = np.array([1, 2, 3, 6]) # cm from the bullseye
print("MAE :", np.mean(np.abs(misses)))
print("MSE :", np.mean(misses ** 2))
print("RMSE:", round(np.sqrt(np.mean(misses ** 2)), 2))
MAE : 3.0
MSE : 12.5
RMSE: 3.54
- MAE, mean absolute error: the average miss. (1 + 2 + 3 + 6) / 4 = 3 cm.
- MSE, mean squared error: square each miss, then average. (1 + 4 + 9 + 36) / 4 = 12.5. The unit is cm2, which is hard to picture. (MSE is the cost function from Linear Regression and the Cost Function.)
- RMSE, root mean squared error: the square root of the MSE. 3.54 cm, back in normal units.
Why is RMSE bigger than MAE? Squaring makes the 6 cm dart count the most. Big misses pull RMSE up.
Score the insurance model
This is the same model as in Linear Regression in scikit-learn: insurance.csv, an 80/20 split with random_state=42, and a pipeline (median imputer for numbers, most-frequent imputer and one-hot encoder for text) with LinearRegression at the end. It predicts all 268 test people:
import pandas as pd
from sklearn.model_selection import train_test_split
df = pd.read_csv("insurance.csv")
X = df.drop(columns="charges")
y = df["charges"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)
(1070, 6) (268, 6)
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
from sklearn.linear_model import LinearRegression
num_cols = X.select_dtypes(include="number").columns
cat_cols = X.select_dtypes(exclude="number").columns
preprocess = ColumnTransformer([
("num", SimpleImputer(strategy="median"), num_cols),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(drop="first",
handle_unknown="ignore")),
]), cat_cols),
])
model = Pipeline([("preprocess", preprocess),
("reg", LinearRegression())])
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(len(y_pred))
268
First, three of them, with the miss for each:
check = pd.DataFrame({"actual": y_test, "predicted": y_pred})
check = check.round().astype(int)
check["miss"] = check["actual"] - check["predicted"]
print(check.loc[[764, 887, 890]])
actual predicted miss
764 9095 8970 125
887 5272 7069 -1797
890 29331 36858 -7527
Only $125 off for the first person, but more than $7,000 off for the smoker. Three people aren't enough. We need one number for all 268.
from sklearn.metrics import (
mean_absolute_error, mean_squared_error,
r2_score)
mae = mean_absolute_error(y_test, y_pred)
mse = mean_squared_error(y_test, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y_test, y_pred)
print("MAE :", round(mae))
print("MSE :", round(mse))
print("RMSE:", round(rmse))
print("R2 :", round(r2, 3))
MAE : 4181
MSE : 33596916
RMSE: 5796
R2 : 0.784
On average a guess is about $4,181 off. RMSE is higher, $5,796, because a few people are missed by a lot. The MSE is in dollars squared, a huge number nobody can picture, so we rarely report it.
The number to beat: DummyRegressor
Is $5,796 good? A score only means something next to something to compare it with. The simplest possible model, DummyRegressor(strategy="mean"), ignores every column and always predicts the average bill from the training rows:
from sklearn.dummy import DummyRegressor
dummy = DummyRegressor(strategy="mean")
dummy.fit(X_train, y_train)
d_pred = dummy.predict(X_test)
d_rmse = np.sqrt(mean_squared_error(y_test, d_pred))
d_r2 = r2_score(y_test, d_pred)
print("always predicts:", round(d_pred[0]))
print("RMSE:", round(d_rmse))
print("R2 :", round(d_r2, 3))
always predicts: 13346
RMSE: 12466
R2 : -0.001
The dummy always says $13,346 and misses by about $12,466. Our model misses by $5,796, less than half. Every model you build should beat this baseline.
R-squared: better than the mean?
R-squared compares your model with the mean-guessing dummy:
R2 = 1 - (model MSE) / (MSE of always guessing the mean)
base_mse = mean_squared_error(y_test, d_pred)
print(round(base_mse))
print(round(1 - mse / base_mse, 3))
155391444
0.784
33.6 million over 155.4 million, taken away from 1, gives 0.784: the same number r2_score printed. The dummy scores about 0 because it is the mean guess. Now a silly model that always guesses $30,000:
# always guess $30,000
bad_pred = np.full(len(y_test), 30000)
print(round(r2_score(y_test, bad_pred), 2))
-1.87
So R-squared is not stuck between -1 and 1. Its maximum is 1, and it can go as low as a bad model takes it.
Adjusted R-squared: extra columns must earn their place
Plain R-squared never goes down when you add a column, even a useless one. Adjusted R-squared takes a small penalty for every column. scikit-learn has no function for it, so it's a few lines:
n = len(y_test) # test rows
names = model[:-1].get_feature_names_out()
p = len(names) # columns used
adj_r2 = 1 - (1 - r2) * (n - 1) / (n - p - 1)
print(n, p, round(adj_r2, 3))
268 8 0.777
268 test rows, 8 columns after encoding, and an adjusted R-squared of 0.777, a little below the plain 0.784.
The residual plot
One number is useful, but look at every miss too. Plot the residual (actual minus predicted) against the prediction, one dot per test person:
import matplotlib.pyplot as plt
residuals = y_test - y_pred
plt.figure(figsize=(7, 2.8), layout="tight")
plt.scatter(y_pred, residuals, s=14)
plt.axhline(0, color="red")
plt.xlabel("predicted charges")
plt.ylabel("residual")
plt.show()

Good misses look like random noise around the red zero line. Here you can see stripes and bands, especially on the right. That tells you a straight line is missing something in this data. You'll bend the line in Polynomial Regression, Overfitting and Underfitting.
Common mistakes
- Reporting MSE to people. It's in squared units. Report MAE and RMSE, which are in dollars.
- Showing a score with no baseline. Always put the DummyRegressor next to it.
- Thinking R-squared can't be negative. Below 0 means worse than guessing the mean, with no lower limit.
- Trusting R-squared alone when adding columns. It never goes down; adjusted R-squared does.
- Skipping the residual plot. Patterns in the misses show what the model can't see.
Quick recap
| Metric | Meaning | Insurance model | Dummy |
|---|---|---|---|
| MAE | Average miss, in dollars | 4,181 | |
| RMSE | Like MAE, big misses hurt more | 5,796 | 12,466 |
| R2 | How much better than the mean guess | 0.784 | -0.001 |
| Adjusted R2 | R2 with a penalty per column | 0.777 | |
| Residual plot | Look for stripes, not just noise | Bands on the right |
Try it yourself
Compute MAE, RMSE and R-squared for the age-only model (LinearRegression on X_train[["age"]]). Does it beat the DummyRegressor? By how much?
The notebook and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Next →Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Linear Regression and the Cost Function: Draw a Line, Score It
Draw a straight line through six kids' ages and weights, measure every miss, and turn the misses into one score, the mean squared error. Then let np.polyfit find the line with the lowest score.
Gradient Descent Explained: Feel the Slope, Step Downhill
Instead of handing over the best line, let the computer walk to it: measure the slope of the cost, step downhill with a learning rate, repeat. Shown step by step on six kids' ages and weights.
Linear Regression in scikit-learn: Fit, Predict and Read the Price Tags
Predict a yearly medical bill with scikit-learn's LinearRegression: first from age alone, then from every column inside a pipeline. Each coefficient reads like a price tag, and smoker_yes is by far the biggest.
Polynomial Regression, Overfitting and Underfitting: Bend the Line, Watch the Test Score
Give a linear model extra columns with PolynomialFeatures and it can bend. Then watch train and test scores split apart: degrees 1, 2 and 16 on Canada's income per person, and degrees 1 to 5 on the insurance model.