文章目錄
- 前言
- 一、重要概念
-
- 1.模型
- 2.回歸分析
- 3.簡單線性回歸
- 4.拟合
- 5.多元線性回歸
- 6.損失函數
- 7.參數求解
- 二、一進制線性回歸模型代碼實作
-
- 1.簡單線性回歸程式
- 三、回歸模型評估
-
- 1.MSE
- 2.RMSE
- 3.MAE
- 4.R方
- 四、多元線性回歸模型代碼實作
- 五、作業
前言
本節知識點:學習線性回歸模型,實作連續變量類型的預測。
1、掌握線性回歸的原理;
2、能夠實用線性回歸進行預測;
3、能夠對線性回歸模型進行預測;
一、重要概念
1.模型
2.回歸分析
3.簡單線性回歸
4.拟合
5.多元線性回歸
6.損失函數
用來衡量誤差,檢驗預測值與真實值之間的差異,也叫目标函數或代價函數;
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIyVGduV2YfNWawNCM38FdsYkRGZkRG9lcvx2bjxiNx8VZ6l2cs0TP350dBpWT3tGVOBDOsJGcohVYsR2MMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnL0MDN2MDOyMTM5ETMxAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
7.參數求解
二、一進制線性回歸模型代碼實作
1.簡單線性回歸程式
以鸢尾花資料集中花瓣長度和寬度為例,通過程式實作線性回歸模型;
import numpy as np
#線性回歸需要的類;
from sklearn.linear_model import LinearRegression
#用來切分訓練集和測試集
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
#設定輸出的精度,預設為8.
np.set_printoptions(precision=2)
iris=load_iris()
#擷取花瓣長度作為x,花瓣寬度作為y
X,y=iris.data[:,2].reshape(-1,1),iris.data[:,3]
lr=LinearRegression()
#将資料集分為訓練集和測試集
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=0)#test_size:表示測試集大小;random_state表示随機種子用來産生相同的随機數序列。
lr.fit(X_train,y_train)
print("權重:",lr.coef_)
print("截距:",lr.intercept_)
#從訓練集中學習到了模型的參數(w與b),确定方程,就可以進行預測;
y_hat=lr.predict(X_test)
print("實際值:",y_test[:5])
print("預測值:",y_hat[:5])
輸出:
權重: [0.42]
截距: -0.37058412021766785
實際值: [2.4 1. 0.2 1.8 0.2]
預測值: [1.77 1.31 0.22 2.27 0.26]
可視化
import matplotlib.pyplot as plt
plt.rcParams["font.family"]="SimHei"
plt.rcParams["axes.unicode_minus"]=False
plt.rcParams["font.size"]=15
plt.figure(figsize=(10,6))
plt.scatter(X_train,y_train,c="orange",label="訓練集")
plt.scatter(X_test,y_test,c="g",label="測試集")
plt.plot(X,lr.predict(X),"r-")
plt.legend()
plt.xlabel("花瓣長度")
plt.ylabel("花瓣寬度")
輸出:Text(0, 0.5, '花瓣寬度')
可視化效果:
plt.figure(figsize=(15,6))
plt.plot(y_test,label="真實值",color="r",marker="o")
plt.plot(y_hat,label="預測值",ls="--",color="g",marker="o")
plt.xlabel("測試集資料序号")
plt.ylabel("資料值")
plt.legend()
三、回歸模型評估
1.MSE
平均平方誤差,為所有樣本資料誤差(真實值與預測值之差)的平方和,然後取均值。
2.RMSE
在平均平方誤差的基礎上,取其平方根。
兩者公式如下:
3.MAE
平均絕對值誤差,為所有樣本資料誤差的絕對值和。
公式如下:
4.R方
R方為決定系數,用來表示模型拟合的分值,值越高表示模型拟合的越好。在訓練集中,r方的取值範圍為【0,1】,在測試集中這樣的未知資料中,其取值範圍為【-無窮大,1】。
公式如下:
對比幾個模型評估方法看一下值
from sklearn.metrics import mean_squared_error,mean_absolute_error,r2_score
print("均方誤差(MSE):",mean_squared_error(y_test,y_hat))
print("根均方誤差(RMSE):",np.sqrt(mean_squared_error(y_test,y_hat)))
print("平均絕對值誤差(MAE):",mean_absolute_error(y_test,y_hat))
print("訓練集R^2:",r2_score(y_train,lr.predict(X_train)))
print("測試集R^2:",r2_score(y_test,y_hat))
#score求解的其實就是r^2的值,但r2_score與score方法傳遞的參數的内容是不同的。
print("訓練集R^2:",lr.score(X_train,y_train))
print("訓練集R^2:",lr.score(X_test,y_test))
輸出:
均方誤差(MSE): 0.0521286207919386
根均方誤差(RMSE): 0.2283169305854005
平均絕對值誤差(MAE): 0.1673599103556632
訓練集R^2: 0.9358824215964661
測試集R^2: 0.8931453922584154
訓練集R^2: 0.9358824215964661
訓練集R^2: 0.8931453922584154
四、多元線性回歸模型代碼實作
上面是再用一進制線性回歸來計算模型,在實際場景中多因素影響才是常見的,我們以波士頓房價為例進行學習:
首先導入資料和各種計算的庫,對資料集有個大概的預覽:
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_boston
import pandas as pd
boston=load_boston()
X,y=boston.data,boston.target
df=pd.DataFrame(np.concatenate([X,y.reshape(-1,1)],axis=1),columns=boston.feature_names.tolist()+["MEDV"])
df.head()
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.25,random_state=0)
lr=LinearRegression()
lr.fit(X_train, y_train)
print("模型權重:",lr.coef_)
print("截距:",lr.intercept_)
y_hat=lr.predict(X_test)
print("訓練集R^2:",lr.score(X_train,y_train))
print("測試集R^2:",lr.score(X_test,y_test))
輸出:
模型權重: [-1.18e-01 4.40e-02 -5.77e-03 2.39e+00 -1.56e+01 3.77e+00 -7.04e-03 -1.43e+00 2.40e-01 -1.13e-02 -9.86e-01 8.44e-03 -4.99e-01]
截距: 36.933255457118676
訓練集R^2: 0.7697699488741149
測試集R^2: 0.6354638433202129
五、作業
1、使用投放廣告(X)與收入(y)的資料集,進行線性回歸
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
import numpy as np
import pandas as pd
df=pd.read_csv("./Advertising.csv",index_col=0) #index_col=0表示自動指定某列為索引
x=df.iloc[:,0:-1]
y=df.iloc[:,-1]
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2,random_state=0)
lr=LinearRegression()
lr.fit(x_train,y_train)
lr.predict(x_test)
#使用R方對模型效果進行評估
print("訓練集R^2:",lr.score(x_train,y_train))
print("測試集R^2:",lr.score(x_test,y_test))
lr.predict(x_test)
輸出:
訓練集R^2: 0.9067114990146383
測試集R^2: 0.8601145185017869
array([10.05739563, 7.4522807 , 7.0197076 , 24.08029725, 12.01786259,
6.53793858, 12.78286918, 15.10974587, 10.76974013, 16.34357951,
22.88297477, 9.12924467, 10.46455672, 15.48743552, 11.58555633,
12.17296914, 18.76551502, 10.78318566, 15.90515992, 17.30651279,
24.06692057, 9.59834224, 15.13512211, 12.38591525, 5.71360885,
15.24749314, 12.29402334, 20.9421167 , 13.40991558, 9.04348832,
12.89239415, 21.40272028, 18.13802209, 21.17320803, 6.56974433,
6.14114206, 7.89018394, 13.01541434, 14.68953791, 6.18835143])
2、我們使用線性回歸類,當模型調用fit方法拟合資料後,如果不調用模型的predict方法,我們該怎麼對未知的資料進行預測呢?
#我們可以通過擷取權重值,與我們的測試資料 按照線性回歸的公式 y=wx+b進行y值得預測
#lr.coef_ 權重清單W
#intercept_ 截距項b
lr.coef_.dot(x_test.T)+lr.intercept_
輸出:可以看到,結果是一樣的。
array([10.05739563, 7.4522807 , 7.0197076 , 24.08029725, 12.01786259,
6.53793858, 12.78286918, 15.10974587, 10.76974013, 16.34357951,
22.88297477, 9.12924467, 10.46455672, 15.48743552, 11.58555633,
12.17296914, 18.76551502, 10.78318566, 15.90515992, 17.30651279,
24.06692057, 9.59834224, 15.13512211, 12.38591525, 5.71360885,
15.24749314, 12.29402334, 20.9421167 , 13.40991558, 9.04348832,
12.89239415, 21.40272028, 18.13802209, 21.17320803, 6.56974433,
6.14114206, 7.89018394, 13.01541434, 14.68953791, 6.18835143])