Linear regression vẽ đường thẳng khớp nhất với dữ liệu của bạn. Nó là “hello world” của machine learning.
Mục tiêu bài học
- Suy ra các quy tắc cập nhật của gradient descent cho mean squared error và tự triển khai linear regression
- So sánh gradient descent và normal equation về độ phức tạp tính toán và khi nào nên dùng mỗi cách
- Xây dựng model multiple linear regression có chuẩn hóa feature và diễn giải các weight đã học
- Giải thích cách Ridge regression (L2 regularization) ngăn overfitting bằng cách phạt các weight lớn
Vấn đề
Bạn có dữ liệu về diện tích nhà và giá bán. Bạn muốn dự đoán giá của một căn nhà mới dựa trên diện tích của nó. Bạn có thể nhìn biểu đồ phân tán rồi đoán, nhưng bạn cần một công thức. Bạn cần một đường thẳng khớp với dữ liệu nhất có thể, để nhập bất kỳ diện tích nào vào và nhận được giá dự đoán.
Linear regression cho bạn đường thẳng đó. Quan trọng hơn, nó giới thiệu toàn bộ vòng lặp training trong ML: xác định model, xác định cost function, tối ưu các parameter. Mọi thuật toán ML đều theo cùng một khuôn mẫu. Hãy nắm vững nó ở trường hợp đơn giản nhất này, rồi bạn sẽ nhận ra nó ở khắp nơi.
Nó không chỉ dành cho những bài toán đơn giản. Linear regression được dùng trong các hệ thống production để dự báo nhu cầu, phân tích A/B test, xây dựng model tài chính và làm baseline cho mọi bài toán regression.
Khái niệm
Model
Linear regression giả định có một quan hệ tuyến tính giữa input () và output ():
w(weight/độ dốc): thay đổi bao nhiêu khi tăng thêm 1b(bias/tung độ gốc): giá trị của khi
Với nhiều input (feature), công thức mở rộng thành:
Hoặc viết dưới dạng vector:
Mục tiêu là tìm các giá trị và sao cho dự đoán gần với thực tế nhất trên tất cả ví dụ training.
Cost Function (Mean Squared Error)
Làm sao đo được “gần nhất”? Bạn cần một con số duy nhất cho biết các dự đoán sai đến mức nào. Lựa chọn phổ biến nhất là Mean Squared Error (MSE):
Tại sao lại bình phương? Có hai lý do. Thứ nhất, nó phạt lỗi lớn nặng hơn lỗi nhỏ (lỗi bằng 10 tệ gấp 100 lần lỗi bằng 1, chứ không phải 10 lần). Thứ hai, hàm bình phương trơn và có đạo hàm ở mọi điểm, nên việc tối ưu khá đơn giản.
Cost function tạo ra một bề mặt. Với một weight và một bias , bề mặt MSE trông như một cái bát (một paraboloid lồi). Đáy bát là nơi MSE nhỏ nhất. Training nghĩa là tìm ra đáy đó.
Gradient Descent
Gradient descent tìm đáy bát bằng cách bước dần xuống dốc.
Các gradient cho bạn biết hai điều: cần dịch chuyển mỗi parameter theo hướng nào và dịch chuyển bao nhiêu.
Với MSE và :
Quy tắc cập nhật:
Learning rate kiểm soát độ dài mỗi bước. Quá lớn: bạn bước vượt qua điểm cực tiểu rồi đi chệch ngày càng xa. Quá nhỏ: training kéo dài mãi. Các giá trị thường dùng để bắt đầu là 0.01, 0.001 hoặc 0.0001.
Normal Equation (Nghiệm dạng đóng)
Riêng với linear regression, có một công thức trực tiếp cho ra các weight tối ưu mà không cần lặp:
Công thức này lấy nghịch đảo ma trận để tìm trong một bước. Nó hoạt động rất tốt với dataset nhỏ. Với dataset lớn (hàng triệu hàng hoặc hàng nghìn feature), gradient descent được ưu tiên vì phép lấy nghịch đảo ma trận có độ phức tạp theo số lượng feature.
Multiple Linear Regression
Với nhiều feature, model trở thành:
Mọi thứ vẫn hoạt động như cũ: MSE là cost function, còn gradient descent cập nhật tất cả weight cùng lúc. Khác biệt duy nhất là bạn đang khớp một siêu phẳng thay vì một đường thẳng.
Feature scaling rất quan trọng ở đây. Nếu một feature nằm trong khoảng 0 đến 1, còn feature khác nằm trong khoảng 0 đến 1.000.000, gradient descent sẽ gặp khó vì bề mặt cost bị kéo dài. Hãy chuẩn hóa các feature (trừ đi giá trị trung bình rồi chia cho độ lệch chuẩn) trước khi training.
Polynomial Regression
Nếu mối quan hệ không tuyến tính thì sao? Bạn vẫn có thể dùng linear regression bằng cách tạo các feature đa thức:
Đây vẫn là regression “tuyến tính” vì model tuyến tính theo các weight (). Bạn chỉ đang dùng các feature phi tuyến của .
Đa thức bậc cao hơn có thể khớp những đường cong phức tạp hơn, nhưng dễ bị overfitting. Một đa thức bậc 10 sẽ đi qua mọi điểm trong dataset gồm 10 điểm, nhưng dự đoán kém trên dữ liệu mới.
Điểm R-Squared
MSE cho bạn biết dự đoán sai đến mức nào, nhưng con số đó phụ thuộc vào thang đo của . R-squared () cho một thước đo không phụ thuộc vào thang đo:
- : dự đoán hoàn hảo
- : model không tốt hơn việc luôn dự đoán giá trị trung bình
- : model còn tệ hơn việc dự đoán giá trị trung bình
Giới thiệu Regularization (Ridge Regression)
Khi có nhiều feature, model có thể bị overfitting do gán các weight lớn. Ridge regression (L2 regularization) thêm một khoản phạt:
Khoản phạt này hạn chế các weight lớn. Hyperparameter kiểm soát sự đánh đổi: càng cao thì weight càng nhỏ và mức regularization càng lớn. Một bài học sau sẽ đi sâu vào chủ đề này. Lúc này, bạn chỉ cần biết nó tồn tại và vì sao nó hữu ích.
Tự xây dựng
Bước 1: Tạo dữ liệu mẫu
import random
import math
random.seed(42)
TRUE_W = 3.0
TRUE_B = 7.0
N_SAMPLES = 100
X = [random.uniform(0, 10) for _ in range(N_SAMPLES)]
y = [TRUE_W * x + TRUE_B + random.gauss(0, 2.0) for x in X]
print(f"Generated {N_SAMPLES} samples")
print(f"True relationship: y = {TRUE_W}x + {TRUE_B} (+ noise)")
print(f"First 5 points: {[(round(X[i], 2), round(y[i], 2)) for i in range(5)]}")Bước 2: Tự triển khai linear regression bằng gradient descent
class LinearRegression:
def __init__(self, learning_rate=0.01):
self.w = 0.0
self.b = 0.0
self.lr = learning_rate
self.cost_history = []
def predict(self, X):
return [self.w * x + self.b for x in X]
def compute_cost(self, X, y):
predictions = self.predict(X)
n = len(y)
cost = sum((pred - actual) ** 2 for pred, actual in zip(predictions, y)) / n
return cost
def compute_gradients(self, X, y):
predictions = self.predict(X)
n = len(y)
dw = (2 / n) * sum((pred - actual) * x for pred, actual, x in zip(predictions, y, X))
db = (2 / n) * sum(pred - actual for pred, actual in zip(predictions, y))
return dw, db
def fit(self, X, y, epochs=1000, print_every=200):
for epoch in range(epochs):
dw, db = self.compute_gradients(X, y)
self.w -= self.lr * dw
self.b -= self.lr * db
cost = self.compute_cost(X, y)
self.cost_history.append(cost)
if epoch % print_every == 0:
print(f" Epoch {epoch:4d} | Cost: {cost:.4f} | w: {self.w:.4f} | b: {self.b:.4f}")
return self
def r_squared(self, X, y):
predictions = self.predict(X)
y_mean = sum(y) / len(y)
ss_res = sum((actual - pred) ** 2 for actual, pred in zip(y, predictions))
ss_tot = sum((actual - y_mean) ** 2 for actual in y)
return 1 - (ss_res / ss_tot)
print("=== Training Linear Regression (Gradient Descent) ===")
model = LinearRegression(learning_rate=0.005)
model.fit(X, y, epochs=1000, print_every=200)
print(f"\nLearned: y = {model.w:.4f}x + {model.b:.4f}")
print(f"True: y = {TRUE_W}x + {TRUE_B}")
print(f"R-squared: {model.r_squared(X, y):.4f}")Bước 3: Normal equation (nghiệm dạng đóng)
class LinearRegressionNormal:
def __init__(self):
self.w = 0.0
self.b = 0.0
def fit(self, X, y):
n = len(X)
x_mean = sum(X) / n
y_mean = sum(y) / n
numerator = sum((X[i] - x_mean) * (y[i] - y_mean) for i in range(n))
denominator = sum((X[i] - x_mean) ** 2 for i in range(n))
self.w = numerator / denominator
self.b = y_mean - self.w * x_mean
return self
def predict(self, X):
return [self.w * x + self.b for x in X]
def r_squared(self, X, y):
predictions = self.predict(X)
y_mean = sum(y) / len(y)
ss_res = sum((actual - pred) ** 2 for actual, pred in zip(y, predictions))
ss_tot = sum((actual - y_mean) ** 2 for actual in y)
return 1 - (ss_res / ss_tot)
print("\n=== Normal Equation (Closed-Form) ===")
model_normal = LinearRegressionNormal()
model_normal.fit(X, y)
print(f"Learned: y = {model_normal.w:.4f}x + {model_normal.b:.4f}")
print(f"R-squared: {model_normal.r_squared(X, y):.4f}")Bước 4: Multiple linear regression
class MultipleLinearRegression:
def __init__(self, n_features, learning_rate=0.01):
self.weights = [0.0] * n_features
self.bias = 0.0
self.lr = learning_rate
self.cost_history = []
def predict_single(self, x):
return sum(w * xi for w, xi in zip(self.weights, x)) + self.bias
def predict(self, X):
return [self.predict_single(x) for x in X]
def compute_cost(self, X, y):
predictions = self.predict(X)
n = len(y)
return sum((pred - actual) ** 2 for pred, actual in zip(predictions, y)) / n
def fit(self, X, y, epochs=1000, print_every=200):
n = len(y)
n_features = len(X[0])
for epoch in range(epochs):
predictions = self.predict(X)
errors = [pred - actual for pred, actual in zip(predictions, y)]
for j in range(n_features):
grad = (2 / n) * sum(errors[i] * X[i][j] for i in range(n))
self.weights[j] -= self.lr * grad
grad_b = (2 / n) * sum(errors)
self.bias -= self.lr * grad_b
cost = self.compute_cost(X, y)
self.cost_history.append(cost)
if epoch % print_every == 0:
print(f" Epoch {epoch:4d} | Cost: {cost:.4f}")
return self
def r_squared(self, X, y):
predictions = self.predict(X)
y_mean = sum(y) / len(y)
ss_res = sum((actual - pred) ** 2 for actual, pred in zip(y, predictions))
ss_tot = sum((actual - y_mean) ** 2 for actual in y)
return 1 - (ss_res / ss_tot)
random.seed(42)
N = 100
X_multi = []
y_multi = []
for _ in range(N):
size = random.uniform(500, 3000)
bedrooms = random.randint(1, 5)
age = random.uniform(0, 50)
price = 50 * size + 10000 * bedrooms - 1000 * age + 50000 + random.gauss(0, 20000)
X_multi.append([size, bedrooms, age])
y_multi.append(price)
def standardize(X):
n_features = len(X[0])
means = [sum(X[i][j] for i in range(len(X))) / len(X) for j in range(n_features)]
stds = []
for j in range(n_features):
variance = sum((X[i][j] - means[j]) ** 2 for i in range(len(X))) / len(X)
stds.append(variance ** 0.5)
X_scaled = []
for i in range(len(X)):
row = [(X[i][j] - means[j]) / stds[j] if stds[j] > 0 else 0 for j in range(n_features)]
X_scaled.append(row)
return X_scaled, means, stds
y_mean_val = sum(y_multi) / len(y_multi)
y_std_val = (sum((yi - y_mean_val) ** 2 for yi in y_multi) / len(y_multi)) ** 0.5
y_scaled = [(yi - y_mean_val) / y_std_val for yi in y_multi]
X_scaled, x_means, x_stds = standardize(X_multi)
print("\n=== Multiple Linear Regression (3 features) ===")
print("Features: house size, bedrooms, age")
multi_model = MultipleLinearRegression(n_features=3, learning_rate=0.01)
multi_model.fit(X_scaled, y_scaled, epochs=1000, print_every=200)
print(f"\nWeights (standardized): {[round(w, 4) for w in multi_model.weights]}")
print(f"Bias (standardized): {multi_model.bias:.4f}")
print(f"R-squared: {multi_model.r_squared(X_scaled, y_scaled):.4f}")Bước 5: Polynomial regression
class PolynomialRegression:
def __init__(self, degree, learning_rate=0.01):
self.degree = degree
self.weights = [0.0] * degree
self.bias = 0.0
self.lr = learning_rate
def make_features(self, X):
return [[x ** (d + 1) for d in range(self.degree)] for x in X]
def predict(self, X):
features = self.make_features(X)
return [sum(w * f for w, f in zip(self.weights, row)) + self.bias for row in features]
def fit(self, X, y, epochs=1000, print_every=200):
features = self.make_features(X)
n = len(y)
for epoch in range(epochs):
predictions = [sum(w * f for w, f in zip(self.weights, row)) + self.bias for row in features]
errors = [pred - actual for pred, actual in zip(predictions, y)]
for j in range(self.degree):
grad = (2 / n) * sum(errors[i] * features[i][j] for i in range(n))
self.weights[j] -= self.lr * grad
grad_b = (2 / n) * sum(errors)
self.bias -= self.lr * grad_b
if epoch % print_every == 0:
cost = sum(e ** 2 for e in errors) / n
print(f" Epoch {epoch:4d} | Cost: {cost:.6f}")
return self
def r_squared(self, X, y):
predictions = self.predict(X)
y_mean = sum(y) / len(y)
ss_res = sum((actual - pred) ** 2 for actual, pred in zip(y, predictions))
ss_tot = sum((actual - y_mean) ** 2 for actual in y)
return 1 - (ss_res / ss_tot)
random.seed(42)
X_poly = [x / 10.0 for x in range(0, 50)]
y_poly = [0.5 * x ** 2 - 2 * x + 3 + random.gauss(0, 1.0) for x in X_poly]
x_max = max(abs(x) for x in X_poly)
X_poly_norm = [x / x_max for x in X_poly]
y_poly_mean = sum(y_poly) / len(y_poly)
y_poly_std = (sum((yi - y_poly_mean) ** 2 for yi in y_poly) / len(y_poly)) ** 0.5
y_poly_norm = [(yi - y_poly_mean) / y_poly_std for yi in y_poly]
print("\n=== Polynomial Regression (degree 2 vs degree 5) ===")
print("True relationship: y = 0.5x^2 - 2x + 3")
print("\nDegree 2:")
poly2 = PolynomialRegression(degree=2, learning_rate=0.1)
poly2.fit(X_poly_norm, y_poly_norm, epochs=2000, print_every=500)
print(f" R-squared: {poly2.r_squared(X_poly_norm, y_poly_norm):.4f}")
print("\nDegree 5:")
poly5 = PolynomialRegression(degree=5, learning_rate=0.1)
poly5.fit(X_poly_norm, y_poly_norm, epochs=2000, print_every=500)
print(f" R-squared: {poly5.r_squared(X_poly_norm, y_poly_norm):.4f}")
print("\nDegree 2 fits the true curve well. Degree 5 fits training data slightly better")
print("but risks overfitting on new data.")Bước 6: Ridge regression (L2 regularization)
class RidgeRegression:
def __init__(self, n_features, learning_rate=0.01, alpha=1.0):
self.weights = [0.0] * n_features
self.bias = 0.0
self.lr = learning_rate
self.alpha = alpha
def predict_single(self, x):
return sum(w * xi for w, xi in zip(self.weights, x)) + self.bias
def predict(self, X):
return [self.predict_single(x) for x in X]
def fit(self, X, y, epochs=1000, print_every=200):
n = len(y)
n_features = len(X[0])
for epoch in range(epochs):
predictions = self.predict(X)
errors = [pred - actual for pred, actual in zip(predictions, y)]
mse = sum(e ** 2 for e in errors) / n
reg_term = self.alpha * sum(w ** 2 for w in self.weights)
cost = mse + reg_term
for j in range(n_features):
grad = (2 / n) * sum(errors[i] * X[i][j] for i in range(n))
grad += 2 * self.alpha * self.weights[j]
self.weights[j] -= self.lr * grad
grad_b = (2 / n) * sum(errors)
self.bias -= self.lr * grad_b
if epoch % print_every == 0:
print(f" Epoch {epoch:4d} | Cost: {cost:.4f} | L2 penalty: {reg_term:.4f}")
return self
print("\n=== Ridge Regression (L2 Regularization) ===")
print("Same data as multiple regression, with alpha=0.1")
ridge = RidgeRegression(n_features=3, learning_rate=0.01, alpha=0.1)
ridge.fit(X_scaled, y_scaled, epochs=1000, print_every=200)
print(f"\nRidge weights: {[round(w, 4) for w in ridge.weights]}")
print(f"Plain weights: {[round(w, 4) for w in multi_model.weights]}")
print("Ridge weights are smaller (shrunk toward zero) due to the L2 penalty.")Dùng thực tế
Bây giờ hãy làm điều tương tự với scikit-learn, thứ bạn sẽ thực sự dùng trong production.
from sklearn.linear_model import LinearRegression as SklearnLR
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, r2_score
import numpy as np
np.random.seed(42)
X_sk = np.random.uniform(0, 10, (100, 1))
y_sk = 3.0 * X_sk.squeeze() + 7.0 + np.random.normal(0, 2.0, 100)
X_train, X_test, y_train, y_test = train_test_split(X_sk, y_sk, test_size=0.2, random_state=42)
lr = SklearnLR()
lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)
print("=== Scikit-learn Linear Regression ===")
print(f"Coefficient (w): {lr.coef_[0]:.4f}")
print(f"Intercept (b): {lr.intercept_:.4f}")
print(f"R-squared (test): {r2_score(y_test, y_pred):.4f}")
print(f"MSE (test): {mean_squared_error(y_test, y_pred):.4f}")
poly = PolynomialFeatures(degree=2, include_bias=False)
X_poly_sk = poly.fit_transform(X_train)
X_poly_test = poly.transform(X_test)
lr_poly = SklearnLR()
lr_poly.fit(X_poly_sk, y_train)
print(f"\nPolynomial degree 2 R-squared: {r2_score(y_test, lr_poly.predict(X_poly_test)):.4f}")
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
ridge = Ridge(alpha=1.0)
ridge.fit(X_train_scaled, y_train)
print(f"Ridge R-squared: {r2_score(y_test, ridge.predict(X_test_scaled)):.4f}")
print(f"Ridge coefficient: {ridge.coef_[0]:.4f}")Bản bạn tự triển khai và scikit-learn cho cùng kết quả. Điểm khác biệt là scikit-learn xử lý các trường hợp đặc biệt, độ ổn định số học và tối ưu hiệu năng. Hãy dùng thư viện trong production. Hãy dùng bản tự triển khai để hiểu điều gì đang diễn ra.
Đưa vào sản phẩm
Bài học này tạo ra:
outputs/skill-regression.md- một skill giúp chọn cách regression phù hợp với bài toán
Bài tập
- Triển khai batch gradient descent, stochastic gradient descent (SGD) và mini-batch gradient descent. So sánh tốc độ hội tụ trên cùng một dataset. Cách nào hội tụ nhanh nhất? Cách nào có đường cong cost mượt nhất?
- Tạo dữ liệu từ một hàm bậc ba (). Khớp các đa thức bậc 1, 3 và 10. So sánh trên tập training và trên tập test. Overfitting bắt đầu rõ rệt ở bậc nào?
- Triển khai Lasso regression (L1 regularization: ). Training trên dữ liệu nhà ở có nhiều feature. So sánh những weight nào về 0 với Ridge. Vì sao L1 tạo ra nghiệm thưa, còn L2 thì không?
Thuật ngữ chính
| Thuật ngữ | Người ta hay nói | Nghĩa thật sự |
|---|---|---|
| Linear regression | “Vẽ một đường thẳng xuyên qua dữ liệu” | Tìm weight và bias sao cho tổng bình phương chênh lệch giữa và các giá trị thực tế là nhỏ nhất |
| Cost function | “Model tệ đến mức nào” | Một hàm biến các parameter của model thành một con số duy nhất đo lỗi dự đoán, rồi quá trình tối ưu tìm cách giảm con số đó |
| Mean squared error | “Trung bình các lỗi đã bình phương” | , phạt lỗi lớn nặng hơn nhiều |
| Gradient descent | “Đi bộ xuống dốc” | Điều chỉnh các parameter qua nhiều bước theo hướng làm giảm cost function, dựa trên các đạo hàm riêng |
| Learning rate | “Độ dài mỗi bước” | Một hệ số kiểm soát mức thay đổi của parameter sau mỗi bước gradient descent |
| Normal equation | “Giải trực tiếp” | Nghiệm dạng đóng cho ra các weight tối ưu mà không cần lặp |
| R-squared | “Model khớp tốt đến đâu” | Phần phương sai của được model giải thích, có giá trị từ âm vô cùng đến 1.0 |
| Feature scaling | “Đưa các feature về mức tương đương” | Biến đổi các feature về khoảng giá trị tương tự nhau (ví dụ: trung bình bằng 0, phương sai bằng 1) để gradient descent hội tụ nhanh hơn |
| Regularization | “Phạt độ phức tạp” | Thêm một thành phần vào cost function để thu nhỏ các weight, ngăn overfitting |
| Ridge regression | “L2 regularization” | Linear regression có thêm khoản phạt vào MSE |
| Polynomial regression | “Khớp đường cong bằng toán tuyến tính” | Linear regression trên các feature đa thức (), vẫn tuyến tính theo các weight |
| Overfitting | “Học thuộc dữ liệu training” | Dùng một model phức tạp đến mức nó khớp cả nhiễu trong dữ liệu training và dự đoán kém trên dữ liệu mới |
Đọc thêm
- Nhập môn Statistical Learning (ISLR) -- PDF miễn phí, chương 3 và 6 trình bày linear regression và regularization qua các ví dụ thực tế bằng R
- Các nền tảng của Statistical Learning (ESL) -- PDF miễn phí, tài liệu đi kèm ISLR thiên về toán hơn và trình bày sâu hơn về ridge và lasso
- Ghi chú bài giảng Stanford CS229 về Linear Regression -- ghi chú của Andrew Ng, suy ra normal equation và gradient descent từ các nguyên lý cơ bản
- Tài liệu scikit-learn về LinearRegression -- tài liệu tham khảo thực tế về LinearRegression, Ridge, Lasso và ElasticNet, kèm ví dụ code