原創轉載請注明出處:https://www.cnblogs.com/agilestyle/p/12690755.html
准備數據
import matplotlib.pyplot as plt from sklearn.datasets import make_regression from sklearn.linear_model import LinearRegression from sklearn.linear_model import SGDRegressor from sklearn.metrics import mean_squared_error X, y = make_regression(n_samples=500, n_features=1, noise=20, random_state=0) # (500, 1) X.shape # (500,) y.shape plt.scatter(X, y)
建模訓練
lr = LinearRegression() y = y.reshape(-1, 1) # LinearRegression(copy_X=True, fit_intercept=True, n_jobs=None, normalize=False) lr.fit(X, y)
評價模型
# 查看模型的截距 array([-1.53821792]) lr.intercept_ # 查看模型的斜率 array([[45.2879203]]) lr.coef_ # 0.8458565184565707 lr.score(X, y) lr_mse = mean_squared_error(y, lr.predict(X)) # 均方誤差 372.3837648686677 lr_mse plt.scatter(X, y) plt.plot(X, lr.predict(X), 'r')
使用隨機梯度下降求解參數
sgd = SGDRegressor(eta0=0.01, max_iter=100) # eta0: 初始學習率,max_iter: 最大迭代次數 sgd.fit(X, y.ravel()) sgd.score(X, y)
Note:
梯度下降的兩個重要因素
- 學習率決定了下降的步伐的大小,學習率過小,每次只移動一小步,需要移動很多次才能達到最小值或局部最小值;學習率過大,則每次移動一大步,很容易錯過最優解。
- 偏導數決定了下降的方向。每次都選擇下降最快的方向。一個函數在某一點的導數描述了這個函數在這一點附近的變化率。
Linear Regression 算法優缺點
優點
- 建模速度快,不需要很復雜的計算,在數據量大的情況下依然運行速度很快
- 可解釋性
缺點
- 不能很好的處理非線性數據
Reference
scikit-learn Cookbook Second Edition
https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html
https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDRegressor.html
https://docs.scipy.org/doc/numpy/reference/generated/numpy.ravel.html
https://developers.google.com/machine-learning/crash-course/reducing-loss/gradient-descent
https://developers.google.com/machine-learning/crash-course/reducing-loss/learning-rate