Sub topic 2
Measuring Regression Error and Building a Safe Pipeline
Assume you know basic Python, NumPy arrays, pandas DataFrames, and the equation of a line. This chapter uses scikit-learn’s estimator API: fit learns from data, predict produces values, and score returns a model-specific score.
Measuring error
Regression predicts a numeric value. A residual is the actual value minus the predicted value.
| Metric | Meaning | Lower or higher is better |
|---|---|---|
| MSE | Mean squared residual | Lower |
| RMSE | Square root of MSE, in target units | Lower |
| MAE | Mean absolute residual | Lower |
| R-squared | Fraction of target variation explained | Higher |
MSE penalizes large errors strongly because it squares them. RMSE is easier to interpret because it uses the same units as the target. MAE gives the typical absolute error and is less affected by outliers. R-squared can be negative when a model performs worse than predicting the target mean.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(200, 1))
y = 3 * X[:, 0] + 2 + rng.normal(0, 1, size=200)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model = LinearRegression().fit(X_train, y_train)
predictions = model.predict(X_test)
mse = mean_squared_error(y_test, predictions)
print("MSE:", mse)
print("RMSE:", np.sqrt(mse))
print("MAE:", mean_absolute_error(y_test, predictions))
print("R2:", r2_score(y_test, predictions))
print("coef_:", model.coef_)
print("intercept_:", model.intercept_)Reading coefficients
For one feature, the model is:
prediction = coef_ * feature + intercept_
coef_ is the expected target change for a one-unit feature increase. intercept_ is the predicted target when every feature equals zero. That value may not have a useful real-world meaning if zero is outside the observed data.
Checking residuals and assumptions
A useful residual plot compares residuals with predictions. Random scatter around zero supports a linear relationship. Curves suggest nonlinearity, a widening spread suggests unequal variance, and extreme points may be outliers.
Scaling and pipelines
StandardScaler subtracts each feature’s training mean and divides by its training standard deviation. Scaling is especially useful for regularized models. A Pipeline chains preprocessing and prediction. During cross-validation, it fits the scaler separately inside each training fold, preventing test information from leaking into training.
Exercise
Which metric is in the target’s original units, and what residual pattern suggests unequal variance?
Show answer
RMSE is in the target’s original units. A funnel-shaped residual pattern suggests unequal variance.