1. 程式人生 > >Scikit-learn 學習心得(線性迴歸)

Scikit-learn 學習心得(線性迴歸)

一開始學習線性迴歸的時候,是在MATLAB裡寫的,現在學習用python來做。

Scikit-learn 的線性迴歸怎麼用呢?

開始參考的是這個:https://blog.csdn.net/u010900574/article/details/52666291

官方參考為:http://scikit-learn.org/stable/modules/linear_model.html

 

其實很簡單,主要有如下幾步:

1,各種import

import matplotlib.pyplot as plt
import numpy as np
from sklearn.linear_model import LinearRegression

2,構造樣本

#這裡嘗試做一個直線10 + 2x的迴歸

NUM = 10
x = np.linspace(1,10,NUM)
y = 10 + 2*x + np.random.randn(NUM)
x_train = np.array([[tmp] for tmp in x]) #sklearn線性迴歸函式的入參要整成這種,不能用前兩行的x,(這個在一開始把我整的暈乎乎的,還不太熟悉python的資料型別)
y_train = np.array([[tmp] for tmp in y])

3,訓練

model_linear = LinearRegression()  #設定線性迴歸模組
model_linear.fit(x_train, y_train) #訓練資料,得出引數

4,得到特徵引數:

print(model_linear.coef_)        #coef_ 用於存放係數
print(model_linear.intercept_)   #intercept_ 用於存放截距 (偏置項)

其他引數請查閱相關資料,例如:https://www.cnblogs.com/magle/p/5881170.html

5,模型應用:

y_predict = model_linear.predict(x_train)

6,繪圖

label = ['sample', 'predict']
plt.plot(x_train, y_train, 'o')
plt.plot(x_train, y_predict)
plt.legend(label)
plt.show()

完成。