線性迴歸是機器學習中最基礎、最常用的算法之一,主要用於預測連續數值(如房價、温度、銷售額等)。它通過建立一個線性關係模型,來擬合輸入特徵與目標變量之間的關係
一、基本概念
1. 線性迴歸的定義
線性迴歸是一種監督學習算法,用於預測一個連續的目標變量(輸出)。
模型形式為:
其中:
是目標變量(預測值)
是輸入特徵
是模型參數(權重)
是誤差項
二、線性迴歸的類型
1. 簡單線性迴歸
- 只有一個輸入特徵(自變量)
- 模型:
2. 多元線性迴歸
- 有多個輸入特徵
- 模型:
三、線性迴歸的原理
1. 損失函數(Cost Function)
- 常用損失函數是均方誤差(MSE):
其中
是樣本數量,
是真實值,
是預測值。
2. 優化方法
- 常用方法是梯度下降(Gradient Descent),通過不斷調整參數,使損失函數最小化。
四、線性迴歸的實現
1. 使用 Python 實現(手動)
pythonimport numpy as np
# 定義模型
class LinearRegression:
def __init__(self, lr=0.01, n_iters=1000):
self.lr = lr
self.n_iters = n_iters
self.weights = None
self.bias = None
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(self.n_iters):
y_pred = np.dot(X, self.weights) + self.bias
dw = (2 / n_samples) * np.dot(X.T, (y_pred - y))
db = (2 / n_samples) * np.sum(y_pred - y)
self.weights -= self.lr * dw
self.bias -= self.lr * db
def predict(self, X):
return np.dot(X, self.weights) + self.bias
2. 使用 Scikit-learn 實現
pythonfrom sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
# 假設 X 是特徵矩陣,y 是目標變量
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
五、線性迴歸的優缺點
優點:
- 簡單、易於理解和實現
- 計算速度快
- 可解釋性強
缺點:
- 假設特徵和目標之間是線性關係,無法處理非線性問題
- 對異常值敏感
- 容易過擬合(可通過正則化解決)
六、應用場景
- 房價預測
- 銷售預測
- 股票價格預測
- 學生成績預測
七、評估指標
- 均方誤差(MSE)
- 均方根誤差(RMSE)
- 平均絕對誤差(MAE)
- R² 分數(決定係數)
pythonfrom sklearn.metrics import mean_squared_error, r2_score
mse = mean_squared_error(y_test, predictions)
r2 = r2_score(y_test, predictions)
print("MSE:", mse)
print("R²:", r2)
八、擴展:正則化線性迴歸
- 嶺迴歸(Ridge Regression):L2 正則化
- Lasso 迴歸(Lasso Regression):L1 正則化
- 彈性網絡(Elastic Net):L1 + L2 正則化
這些方法通過在損失函數中加入正則化項,防止模型過擬合