Linear Regression
Mục tiêu bài học
Sau bài học này, học viên sẽ:
- Hiểu bản chất cua Linear Regression
- Nắm vững công thức OLS (Ordinary Least Squares)
- Tính toán thủ công Linear Regression
- Implement với Scikit-learn
1. Giới thiệu Linear Regression
1.1 Ý tưởng
Linear Regression tìm đường thẳng tốt nhất để mô tả mối quan hệ giữa biến độc lập (X) va biến phụ thuộc (y).
Công thức:
Trong do:
- : Gia tri dự đoán
- : Intercept (hệ số chặn)
- : Slope (hệ số góc)
- : Bien doc lap

Hinh: Linear Regression fit đường thẳng qua các điểm du lieu
1.2 Multiple Linear Regression
Với nhiều biến:
Hoac dạng ma trận:
2. Ordinary Least Squares (OLS)
2.1 Mục tiêu
Tim sao cho tổng bình phương sai số la nhỏ nhất:
2.2 Công thức OLS
Slope:
Intercept:
2.3 Dang ma tran
3. Ví dụ tính toán thủ công
3.1 Dữ liệu
| x (Diện tích m2) | y (Gia triệu VND) |
|---|---|
| 50 | 500 |
| 60 | 600 |
| 70 | 650 |
| 80 | 700 |
| 100 | 850 |
3.2 Bước 1: Tính Mean
3.3 Bước 2: Tính các thành phần
| 50 | 500 | -22 | -160 | 3520 | 484 |
| 60 | 600 | -12 | -60 | 720 | 144 |
| 70 | 650 | -2 | -10 | 20 | 4 |
| 80 | 700 | 8 | 40 | 320 | 64 |
| 100 | 850 | 28 | 190 | 5320 | 784 |
| Tổng | 9900 | 1480 |
3.4 Bước 3: Tính hệ số
Slope:
Intercept:
3.5 Bước 4: Phương trình hồi quy
Diễn giải: Mỗi mét vuông tăng thêm, giá tăng 6.69 triệu VND.
3.6 Bước 5: Du doan
Với nhà 90m2:
4. Đánh giá Model
4.1 Mean Squared Error (MSE)
4.2 Root Mean Squared Error (RMSE)
4.3 R-squared (R2)
| Gia tri R2 | Ý nghĩa |
|---|---|
| R2 = 1 | Model fit hoàn hảo |
| R2 = 0 | Model khong giải thích gì |
| R2 < 0 | Model tệ hơn mean |
5. Thực hành với Scikit-learn
5.1 Code hoàn chỉnh
Python
1import numpy as np2import matplotlib.pyplot as plt3from sklearn.linear_model import LinearRegression4from sklearn.model_selection import train_test_split5from sklearn.metrics import mean_squared_error, r2_score67# Dữ liệu8X = np.array([50, 60, 70, 80, 100]).reshape(-1, 1)9y = np.array([500, 600, 650, 700, 850])1011# Train model12model = LinearRegression()13model.fit(X, y)1415# Xem hệ số16print(f"Intercept (beta_0): {model.intercept_:.2f}")17print(f"Slope (beta_1): {model.coef_[0]:.2f}")1819# Du doan20y_pred = model.predict(X)21print(f"Predictions: {y_pred}")2223# Đánh giá24mse = mean_squared_error(y, y_pred)25rmse = np.sqrt(mse)26r2 = r2_score(y, y_pred)2728print(f"MSE: {mse:.2f}")29print(f"RMSE: {rmse:.2f}")30print(f"R2: {r2:.4f}")3132# Visualize33plt.figure(figsize=(10, 6))34plt.scatter(X, y, color='blue', label='Actual')35plt.plot(X, y_pred, color='red', label='Predicted')36plt.xlabel('Diện tích (m2)')37plt.ylabel('Gia (triệu VND)')38plt.title('Linear Regression - House Price Prediction')39plt.legend()40plt.grid(True)41plt.show()5.2 Multiple Linear Regression
Python
1from sklearn.datasets import fetch_california_housing2from sklearn.model_selection import train_test_split3from sklearn.linear_model import LinearRegression4from sklearn.metrics import mean_squared_error, r2_score5from sklearn.preprocessing import StandardScaler67# Load data8housing = fetch_california_housing()9X, y = housing.data, housing.target1011# Split12X_train, X_test, y_train, y_test = train_test_split(13 X, y, test_size=0.2, random_state=4214)1516# Scale (quan trong cho multiple regression)17scaler = StandardScaler()18X_train_scaled = scaler.fit_transform(X_train)19X_test_scaled = scaler.transform(X_test)2021# Train22model = LinearRegression()23model.fit(X_train_scaled, y_train)2425# Predict26y_pred = model.predict(X_test_scaled)2728# Evaluate29print(f"R2 Score: {r2_score(y_test, y_pred):.4f}")30print(f"RMSE: {np.sqrt(mean_squared_error(y_test, y_pred)):.4f}")3132# Feature importance33for name, coef in zip(housing.feature_names, model.coef_):34 print(f"{name}: {coef:.4f}")6. Giả định của Linear Regression
6.1 Cac gia dinh
| Gia dinh | Mô tả | Kiểm tra |
|---|---|---|
| Linearity | Quan hệ tuyến tính giữa X va y | Scatter plot |
| Indepenđếnce | Các observation độc lập | Durbin-Watson test |
| Homoscedasticity | Phuong sai sai số khong doi | Residual plot |
| Normality | Sai số phân phối chuẩn | Q-Q plot |
| No multicollinearity | Các features không tương quan cao | VIF |
6.2 Kiểm tra Residuals
Python
1import matplotlib.pyplot as plt2import scipy.stats as stats34# Tính residuals5residuals = y_test - y_pred67# Residual plot8plt.figure(figsize=(12, 4))910plt.subplot(1, 2, 1)11plt.scatter(y_pred, residuals)12plt.axhline(y=0, color='r', linestyle='--')13plt.xlabel('Predicted')14plt.ylabel('Residuals')15plt.title('Residual Plot')1617# Q-Q plot18plt.subplot(1, 2, 2)19stats.probplot(residuals, dist="norm", plot=plt)20plt.title('Q-Q Plot')2122plt.tight_layout()23plt.show()7. Ưu và nhược điểm
| Uu điểm | Nhuoc điểm |
|---|---|
| Đơn giản, dễ hiểu | Chỉ mô tả quan hệ tuyến tính |
| Nhanh, ít tính toán | Nhạy với outliers |
| De giai thich hệ số | Không tốt với dữ liệu phi tuyến |
| Không cần tham số | Giả định nghiêm ngặt |
Bài tập tự luyện
- Bai tap 1: Tính thu cong Linear Regression voi data: X=[1,2,3,4,5], y=[2,4,5,4,5]
- Bai tap 2: Load Boston Housing dataset, train Linear Regression, danh gia R2
- Bai tap 3: Kiểm tra cac gia dinh cua Linear Regression voi residual plots
