現在用導數的方式模擬線性迴歸中的梯度下降法
首先再來回顧一下梯度下降法的基礎
- 梯度下降法不是一個機器學習算法, 而是一個搜索算法
- 梯度下降法用在監督學習中
- 梯度下降法的過程: 對比模型輸出值和樣本值的差異不斷調整本省權重, 直到最後模型輸出值和樣本標籤差別達到理想誤差範圍內
- 梯度下降法的超參是梯度, 梯度過大會導致跳過最優或局部最優解, 梯度過小會過於消耗計算資源
現在寫一個sklearn中的正規方程的線性迴歸模型 沒有實現fit方法
import numpy as np
from .metrics import r2_score
class LinearRegression:
def __init__(self):
"""初始化Linear Regression模型"""
self.coef_ = None
self.intercept_ = None
self._theta = None
def predict(self, X_predict):
"""給定待預測數據集X_predict,返回表示X_predict的結果向量"""
assert self.intercept_ is not None and self.coef_ is not None, \
"must fit before predict!"
assert X_predict.shape[1] == len(self.coef_), \
"the feature number of X_predict must be equal to X_train"
X_b = np.hstack([np.ones((len(X_predict), 1)), X_predict])
return X_b.dot(self._theta)
def score(self, X_test, y_test):
"""根據測試數據集 X_test 和 y_test 確定當前模型的準確度"""
y_predict = self.predict(X_test)
return r2_score(y_test, y_predict)
def __repr__(self):
return "LinearRegression()"
因爲這裏是用線性迴歸做測試, 線性迴歸的正規方程解如下
此公式網上搜的, 推導過程可以看下這位老兄的博客 https://blog.csdn.net/chenlin41204050/article/details/78220280 (未經允許直接引用了哈)
實現正規方程解的fit如下:
def fit_normal(self, X_train, y_train):
"""根據訓練數據集X_train, y_train訓練Linear Regression模型"""
assert X_train.shape[0] == y_train.shape[0], \
"the size of X_train must be equal to the size of y_train"
X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)
self.intercept_ = self._theta[0]
self.coef_ = self._theta[1:]
return self
要用梯度下降法, 就得找到損失函數, 然後計算梯度
下面是多元線性迴歸的瞬時函數
線性迴歸的lose
接着實現上圖面試的梯度下降法的fit_gd如下
def fit_gd(self, X_train, y_train, eta=0.01, n_iters=1e4):
"""根據訓練數據集X_train, y_train, 使用梯度下降法訓練Linear Regression模型"""
assert X_train.shape[0] == y_train.shape[0], \
"the size of X_train must be equal to the size of y_train"
def J(theta, X_b, y):
try:
return np.sum((y - X_b.dot(theta)) ** 2) / len(y)
except:
return float('inf')
def dJ(theta, X_b, y):
return X_b.T.dot(X_b.dot(theta) - y) * 2. / len(y)
def gradient_descent(X_b, y, initial_theta, eta, n_iters=1e4, epsilon=1e-8):
theta = initial_theta
cur_iter = 0
while cur_iter < n_iters:
gradient = dJ(theta, X_b, y)
last_theta = theta
theta = theta - eta * gradient
if (abs(J(theta, X_b, y) - J(last_theta, X_b, y)) < epsilon):
break
cur_iter += 1
return theta
X_b = np.hstack([np.ones((len(X_train), 1)), X_train])
initial_theta = np.zeros(X_b.shape[1])
self._theta = gradient_descent(X_b, y_train, initial_theta, eta, n_iters)
self.intercept_ = self._theta[0]
self.coef_ = self._theta[1:]
return self
上面的方法都封裝在一個LinearRegression.py中
現在開始測試
準備一些隨機數據, 維度爲5000, 樣本數量1000
m = 1000
n = 5000
big_X = np.random.normal(size=(m,n))
true_theta = np.random.uniform(0.0, 100.0, size=n+1)
big_y = big_X.dot(true_theta[1:]) + true_theta[0] + np.random.normal(0, 10.0, size=m)
print(big_X.shape, big_y.shape)
%run LinearRegression.py
輸出:
(1000, 5000) (1000,)
使用正規方程解訓練線性迴歸
big_reg1 = LinearRegression()
%time big_reg1.fit_normal(X_train, y_train)
big_reg1.score(X_test, y_test)
輸出:
CPU times: user 26.8 s, sys: 921 ms, total: 27.7 s
Wall time: 11.1 s
LinearRegression()
使用梯度下降法訓練
big_reg2 = LinearRegression()
%time big_reg2.fit_gd(big_X, big_y)
輸出:
CPU times: user 7.44 s, sys: 97.2 ms, total: 7.54 s
Wall time: 4.15 s
LinearRegression()
結論
- 梯度下降法在無法求出直接最優解的情況下 , 可以搜索到相對較優的解
- 梯度下降法在數據量較大的情況下, 可以避免類似於正規方程解因爲數據規模變大帶來的長時間運算(也是相對性的)