0Pricing
Machine Learning Academy · 강의

비용 함수와 최소제곱법

평균 제곱 오차를 계산하고 비용 표면을 시각화하며, 오차를 최소화하면 최적 적합 매개변수를 얻는 이유를 이해합니다.

비용 함수와 최소제곱법은(는) CoddyKit의 무료 Machine Learning Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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 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.

자주 묻는 질문

“비용 함수와 최소제곱법” 강의는 무료인가요?

네 — “비용 함수와 최소제곱법” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Machine Learning Academy 강의 전체를 잠금 해제할 수 있습니다. Machine Learning Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“비용 함수와 최소제곱법”에서 뭘 배우나요?

평균 제곱 오차를 계산하고 비용 표면을 시각화하며, 오차를 최소화하면 최적 적합 매개변수를 얻는 이유를 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 Machine Learning Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Machine Learning Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Machine Learning Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“비용 함수와 최소제곱법” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Machine Learning Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Machine Learning Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 직선의 방정식: 기울기, 절편, 예측
  2. 비용 함수와 최소제곱법
  3. scikit-learn으로 LinearRegression 훈련
  4. 다중 선형 회귀와 특성 중요도
← Machine Learning Academy(으)로 돌아가기