Linear Regression
Mean Squared Error
Compute MSE = (1/n)Σ(y_trueᵢ−y_predᵢ)² over paired actual and predicted
lists. A single loop accumulates squared differences; divide by n. Library:
sklearn.metrics.mean_squared_error(y_true, y_pred). RESULT: MSE (rounded).
By hand
With scikit-learn
mean_squared_error(y_true, y_pred) computes MSE directly. No model
object needed — pass any paired lists of actuals and predictions.
y_true = [2, 4, 4, 4, 6]
y_pred = [2.4, 3.2, 4.0, 4.8, 6.4]
n = len(y_true)
sq_err = 0.0
for i in range(n):
diff = y_true[i] - y_pred[i]
sq_err = sq_err + diff * diff
mse = sq_err / n
print('RESULT:', round(mse, 4))
from sklearn.metrics import mean_squared_error
from dalib.display import set_display
set_display()
y_true = [2, 4, 4, 4, 6]
y_pred = [2.4, 3.2, 4.0, 4.8, 6.4]
mse = float(mean_squared_error(y_true, y_pred))
print('y_true:', y_true)
print('y_pred:', y_pred)
print('RESULT:', round(mse, 4))
y_true: [2, 4, 4, 4, 6]
y_pred: [2.4, 3.2, 4.0, 4.8, 6.4]
RESULT: 0.32
Honesty
This lesson shows the computation of MSE exactly, on a tiny pinned sample. The value is correct and reproducible, but on so few points it measures error on these specific in-sample points and overstates how the model would perform out of sample. Read it as the mechanism of how squared error is averaged, not as evidence the model generalizes; a real estimate of error needs held-out data and an adequate sample size.
Implementation notes
- MSE = SSE/n: divides the total squared error by sample count.
Cross-reference:
residuals-and-sse(python-stats ch08) computes SSE=1.6 for this same data; MSE = SSE/5 = 0.32. - Squaring gives large errors disproportionate weight (a 2× error contributes 4× the penalty of a 1× error).
- MSE units are squared (e.g. if y is in kg, MSE is in kg²). RMSE = √MSE restores original units at the cost of being less differentiable at 0.
- y_pred here are the fitted values from
normal-equation-1d(this chapter), making the connection between fitting and evaluation explicit.