0Pricing
Machine Learning Academy · Lekcja

Funkcje kosztu i metoda najmniejszych kwadratów

Oblicz średni błąd kwadratowy, zwizualizuj powierzchnię kosztu i poznaj przyczynę, dla której minimalizacja błędu prowadzi do parametrów najlepszego dopasowania.

Funkcje kosztu i metoda najmniejszych kwadratów to bezpłatna lekcja Machine Learning Academy na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Machine Learning Academy, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Machine Learning Academy zawiera 4 lekcji w sumie.

Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.

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 MAE

The 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.0

R-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.

Często zadawane pytania

Czy lekcja „Funkcje kosztu i metoda najmniejszych kwadratów” jest bezpłatna?

Tak — pełny tekst „Funkcje kosztu i metoda najmniejszych kwadratów” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Machine Learning Academy, przejdź na CoddyKit PRO. Kurs Machine Learning Academy zawiera 4 lekcji w sumie.

Co nauczysz się w „Funkcje kosztu i metoda najmniejszych kwadratów”?

Oblicz średni błąd kwadratowy, zwizualizuj powierzchnię kosztu i poznaj przyczynę, dla której minimalizacja błędu prowadzi do parametrów najlepszego dopasowania. Ćwiczysz Machine Learning Academy z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.

Czy potrzebuję doświadczenia, aby zacząć Machine Learning Academy?

Nie wymagamy żadnego doświadczenia. Machine Learning Academy w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.

Ile czasu zajmuje lekcja „Funkcje kosztu i metoda najmniejszych kwadratów”?

Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.

Czy mogę pisać i uruchamiać kod w tej lekcji Machine Learning Academy?

Tak. Każda lekcja Machine Learning Academy zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.

Wszystkie lekcje w tym kursie

  1. Równanie prostej: nachylenie, wyraz wolny i predykcje
  2. Funkcje kosztu i metoda najmniejszych kwadratów
  3. Trenowanie regresji liniowej za pomocą scikit-learn
  4. Wieloraka regresja liniowa i ważność cech
← Powrót do Machine Learning Academy