代价函数与最小二乘法
您将计算均方误差,可视化代价曲面,并理解为什么最小化误差能够得到最佳拟合参数
代价函数与最小二乘法 是 CoddyKit 上的免费 Machine Learning Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Machine Learning Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Machine Learning Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
What Makes a Line 'Best'?
Given a scatter plot of data points, infinitely many lines could pass through or near the data. The question is: which line is the best? We need a formal mathematical definition of 'best' that we can optimise algorithmically.
The answer is a cost function (also called a loss function or objective function) — a single number that measures how wrong the model's predictions are across all training examples. The best line is the one that minimises the cost function. This turns model training into a mathematical optimisation problem.
Mean Squared Error: The Standard Cost Function
The most common cost function for regression is Mean Squared Error (MSE). For each training example, you compute the residual (actual minus predicted), square it, then average across all examples:
MSE = (1/n) × Σ(yᵢ - ŷᵢ)²
Squaring has two important effects: it makes all errors positive (so positive and negative errors do not cancel out), and it penalises large errors more than small errors (a residual of 10 contributes 100, not 10, to the cost). This means MSE pushes the model to avoid large mistakes.
import numpy as np
y_actual = np.array([250000, 300000, 350000, 200000, 400000])
y_pred = np.array([240000, 320000, 330000, 210000, 380000])
# Compute MSE manually
residuals = y_actual - y_pred
squared_residuals = residuals ** 2
mse = squared_residuals.mean()
print('Residuals:', residuals)
print('Squared residuals:', squared_residuals)
print(f'MSE: {mse:,.0f}')
print(f'RMSE (interpretable): ${np.sqrt(mse):,.0f}')Why Square the Errors?
You might wonder: why not just average the absolute values of residuals (MAE) instead of squaring them? Both are valid cost functions, but MSE has mathematical advantages:
- MSE is differentiable everywhere, which is essential for gradient-based optimisation.
- The squared errors make the MSE surface a smooth bowl with a unique global minimum, unlike some cost functions with multiple local minima.
- MSE has a closed-form algebraic solution, meaning we can compute the optimal parameters directly without iterative search.
Mean Absolute Error (MAE) is more robust to outliers and often preferred in practice, but MSE is the starting point for understanding least-squares regression.
import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error
y_actual = np.array([1.0, 2.0, 3.0, 4.0, 100.0]) # note the outlier
y_pred = np.array([1.1, 2.0, 3.1, 4.0, 4.0]) # miss the outlier
mse = mean_squared_error(y_actual, y_pred)
mae = mean_absolute_error(y_actual, y_pred)
print(f'MSE: {mse:.2f} -> heavily penalises the outlier (100 vs 4)')
print(f'MAE: {mae:.2f} -> less sensitive to the outlier')
# MSE amplifies the big miss much more than MAEThe Cost Surface: Visualising the Optimisation
Imagine a 2D space where one axis is the slope m and the other is the intercept b. For each combination of (m, b), we can compute the MSE on the training data. The result is a cost surface — a bowl-shaped 3D surface where the bottom of the bowl is the optimal (m, b) that minimises MSE.
For linear regression with MSE, this surface is a perfect convex paraboloid — it has exactly one minimum, which guarantees that optimisation will always find the globally best parameters. This is a key theoretical advantage over more complex models with non-convex loss surfaces.
import numpy as np
import matplotlib.pyplot as plt
# Simple 1-feature dataset
np.random.seed(42)
x = np.array([1, 2, 3, 4, 5], dtype=float)
y = np.array([2.1, 4.0, 5.9, 8.1, 10.0])
# Compute MSE for a grid of (slope, intercept) values
slopes = np.linspace(0, 4, 50)
intercepts = np.linspace(-3, 3, 50)
MSE = np.zeros((50, 50))
for i, m in enumerate(slopes):
for j, b in enumerate(intercepts):
y_pred = m * x + b
MSE[j, i] = ((y - y_pred) ** 2).mean()
# Minimum MSE occurs at the true parameters (~m=2, b=0)
print('Minimum MSE:', MSE.min().round(3))
print('At grid position:', np.unravel_index(MSE.argmin(), MSE.shape))The Ordinary Least Squares Solution
Ordinary Least Squares (OLS) is the closed-form mathematical solution that finds the slope and intercept minimising MSE in a single calculation — no iteration required. For simple linear regression (one feature), the formulas are:
m = Σ(xᵢ - x̄)(yᵢ - ȳ) / Σ(xᵢ - x̄)²
b = ȳ - m × x̄
These formulas involve only means, sums, and products of the training data. Scikit-learn's LinearRegression uses the generalised matrix form of this solution, which handles any number of features.
import numpy as np
x = np.array([1, 2, 3, 4, 5], dtype=float)
y = np.array([2.1, 4.0, 5.9, 8.1, 10.0])
# OLS closed-form solution
x_mean, y_mean = x.mean(), y.mean()
numerator = ((x - x_mean) * (y - y_mean)).sum()
denominator = ((x - x_mean) ** 2).sum()
m = numerator / denominator
b = y_mean - m * x_mean
print(f'Optimal slope (m): {m:.4f}') # ~2.0
print(f'Optimal intercept (b): {b:.4f}') # ~0.0
print(f'MSE at optimal params: {((y - (m*x+b))**2).mean():.4f}')The Normal Equation for Multiple Features
When you have multiple features, OLS generalises to the Normal Equation using matrix algebra:
w = (XᵀX)⁻¹ Xᵀy
Here, X is the feature matrix (with a column of ones for the bias), y is the target vector, and w is the vector of optimal weights. This is exactly what scikit-learn computes internally when you call LinearRegression().fit().
The Normal Equation is fast for small datasets (up to ~10,000 features) but slow for very large ones, because computing the matrix inverse is an O(n³) operation. For huge datasets, gradient descent is preferred.
import numpy as np
# Multiple features: X has columns [1, sqft, bedrooms]
X_raw = np.array([[1000, 3], [1500, 4], [800, 2], [2000, 5]], dtype=float)
X = np.column_stack([np.ones(4), X_raw]) # add bias column
y = np.array([200000, 300000, 160000, 380000], dtype=float)
# Normal Equation: w = (X^T X)^{-1} X^T y
w = np.linalg.inv(X.T @ X) @ X.T @ y
print(f'Bias (intercept): {w[0]:,.0f}')
print(f'Sqft coefficient: {w[1]:.2f}')
print(f'Bedrooms coef: {w[2]:,.0f}')
# Verify: prediction for a 1200 sqft, 3 bed house
pred = w[0] + w[1]*1200 + w[2]*3
print(f'Prediction: ${pred:,.0f}')Gradient Descent: An Alternative Optimiser
For very large datasets or models with millions of parameters (like neural networks), the Normal Equation is too slow. Gradient Descent is an iterative alternative: start at a random point on the cost surface, compute the gradient (slope of the cost surface), and take a small step in the downhill direction. Repeat until you reach the bottom.
The learning rate controls step size. Too large and you overshoot the minimum; too small and convergence is painfully slow. Gradient descent is the foundation of deep learning training and the algorithm you will use implicitly whenever you train a neural network.
import numpy as np
# Gradient descent for linear regression
x = np.array([1, 2, 3, 4, 5], dtype=float)
y = np.array([2.1, 4.0, 5.9, 8.1, 10.0])
m, b = 0.0, 0.0 # start at zero
lr = 0.02 # learning rate
for epoch in range(500):
y_pred = m * x + b
residuals = y_pred - y
# Gradients of MSE w.r.t. m and b
grad_m = (2/len(x)) * (residuals * x).sum()
grad_b = (2/len(x)) * residuals.sum()
m -= lr * grad_m
b -= lr * grad_b
print(f'Learned slope: {m:.4f}') # ~2.0
print(f'Learned intercept: {b:.4f}') # ~0.0R-Squared: Goodness of Fit
R² (R-squared), also called the coefficient of determination, measures how much of the variance in y is explained by the model. It ranges from 0 to 1 (or can be negative for a very bad model):
- R² = 1.0 — perfect predictions; the line explains all variability.
- R² = 0.0 — the model does no better than always predicting the mean of y.
- R² = 0.8 — the model explains 80% of the variance in y.
R² is the primary metric for evaluating regression models because, unlike MSE, it is scale-independent and always interpreted as a proportion.
import numpy as np
from sklearn.metrics import r2_score
y_actual = np.array([200, 250, 300, 350, 400], dtype=float)
y_pred_good = np.array([195, 255, 305, 345, 402], dtype=float) # tight fit
y_pred_bad = np.array([300, 300, 300, 300, 300], dtype=float) # always predict mean
print(f'Good model R2: {r2_score(y_actual, y_pred_good):.3f}') # close to 1.0
print(f'Baseline R2: {r2_score(y_actual, y_pred_bad):.3f}') # close to 0.0
# Manual calculation
ss_res = ((y_actual - y_pred_good)**2).sum()
ss_tot = ((y_actual - y_actual.mean())**2).sum()
print(f'Manual R2: {1 - ss_res/ss_tot:.3f}')Evaluating Cost with scikit-learn
Scikit-learn provides all standard regression metrics in sklearn.metrics. You import them as functions that take two arrays — actual values and predicted values — and return a scalar score.
Always compute metrics on the test set, not the training set. The training MSE tells you how well the model fits the data it was trained on, which is always lower than the test MSE. The test MSE is the honest estimate of generalisation performance.
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import numpy as np
np.random.seed(42)
X = np.random.randn(200, 1)
y = 3 * X.ravel() + 2 + np.random.randn(200) * 0.5
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = LinearRegression().fit(X_train, y_train)
y_pred = model.predict(X_test)
print(f'Test MSE: {mean_squared_error(y_test, y_pred):.4f}')
print(f'Test RMSE: {mean_squared_error(y_test, y_pred, squared=False):.4f}')
print(f'Test MAE: {mean_absolute_error(y_test, y_pred):.4f}')
print(f'Test R2: {r2_score(y_test, y_pred):.4f}')When MSE Is Not the Right Loss
MSE is the default for regression but is not always the best choice:
- If your target has outliers, MSE amplifies their effect dramatically. Use Huber loss or MAE for robustness.
- If you care more about relative errors than absolute ones (e.g., predicting sales for both $100 and $1,000,000 products), use MSLE (Mean Squared Log Error).
- For time-series forecasting, domain-specific metrics like MAPE (Mean Absolute Percentage Error) are often more interpretable.
The loss function is a design decision that encodes what kinds of errors matter most for your specific problem.
Quick Check
Test your understanding of Machine Learning with Python concepts from this lesson.
Lesson Recap
In this lesson you learned: MSE measures total prediction error by averaging squared residuals across all training examples, the OLS solution finds the exact optimal slope and intercept in one calculation using the Normal Equation, and R-squared measures what proportion of variance the model explains and is scale-independent. Next up we use scikit-learn's LinearRegression to train a real model, inspect its coefficients, and evaluate it on a held-out test set.
用 AI 导师学习 Python — 免费
在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。
- 课程
- 30
- 课程
- 120
常见问题解答
「代价函数与最小二乘法」课时是免费的吗?
是的 — 「代价函数与最小二乘法」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Machine Learning Academy 课程的其余内容,请升级到 CoddyKit PRO。 Machine Learning Academy 课程共包含 4 节课。
「代价函数与最小二乘法」这节课中我会学到什么?
您将计算均方误差,可视化代价曲面,并理解为什么最小化误差能够得到最佳拟合参数 你通过在浏览器中直接运行的动手代码来练习 Machine Learning Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Machine Learning Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Machine Learning Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。
「代价函数与最小二乘法」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Machine Learning Academy 课中编写并运行代码吗?
能。每节 Machine Learning Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。