基于Python的多元线性回归分析
生活随笔
收集整理的這篇文章主要介紹了
基于Python的多元线性回归分析
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、多元線性回歸分析(Multiple regression)
1.與簡單線性回歸相比較,具有多個自變量x
2.多元回歸模型
其中是誤差值,與簡單線性回歸分析中的要求特點相一致。其余的系數和截距為參數。
3.多元回歸方程
4.估計多元回歸方程(點估計)
5.估計方法
使方差和最小,即
從而得到一個唯一的超平面。
二、自變量里沒有類別數據的實例
2.1數據:
100,4,9.3 50,3,4.8 100,4,8.9 100,2,6.5 50,2,4.2 80,2,6.2 75,3,7.4 65,4,6 90,3,7.6 90,2,6.12.2代碼
from numpy import genfromtxt #將導入的數據轉換為numparry(即SK包中可以進行運算的矩陣類型的數據) from sklearn import linear_model#SK包里的數據集和線性模型 import numpy as np dataPath = r"Delivery.csv"#r后面的內容默認為一個完整的字符串,忽略里面的\ deliveryData = genfromtxt(dataPath,delimiter=',')print("data")#將已經輸入的數據打印出來查看 print(deliveryData)x= deliveryData[:,:-1]#提取所有的行和除倒數第一列之外的所有的列 y = deliveryData[:,-1]#提取所有行和最后一列的數據print(x)#打印x的數據 print(y)#打印y的數據lr = linear_model.LinearRegression()#定義一個模型變量名lr,調用sklearn包中線性模型線性回歸分析方法 lr.fit(x, y)#利用上述模型對lr中的x,y數據進行建模print(lr)print("coefficients:") print(lr.coef_)#獲取到的截面的參數值print("intercept:") print(lr.intercept_)#獲取到的截距的參數值xPredict = np.array([102,5]).reshape(1,-1) yPredict = lr.predict(xPredict)#對所給出的x的預測值進行預測 print("predict:") print(yPredict)#打印預測的結果運行結果:
data [[100. 4. 9.3][ 50. 3. 4.8][100. 4. 8.9][100. 2. 6.5][ 50. 2. 4.2][ 80. 2. 6.2][ 75. 3. 7.4][ 65. 4. 6. ][ 90. 3. 7.6][ 90. 2. 6.1]] [[100. 4.][ 50. 3.][100. 4.][100. 2.][ 50. 2.][ 80. 2.][ 75. 3.][ 65. 4.][ 90. 3.][ 90. 2.]] [9.3 4.8 8.9 6.5 4.2 6.2 7.4 6. 7.6 6.1] LinearRegression() coefficients: [0.0611346 0.92342537] intercept: -0.8687014667817126 predict: [9.98415444]Process finished with exit code 0三、自變量中含有類別型的數據
3.1數據
100,4,0,1,0,9.3 50,3,1,0,0,4.8 100,4,0,1,0,8.9 100,2,0,0,1,6.5 50,2,0,0,1,4.2 80,2,0,1,0,6.2 75,3,0,1,0,7.4 65,4,1,0,0,6 90,3,1,0,0,7.6 90,2,0,0,1,6.13.2代碼
from numpy import genfromtxt #將導入的數據轉換為numparry(即SK包中可以進行運算的矩陣類型的數據) import numpy as np from sklearn import linear_model #SK包里的數據集和線性模型datapath=r"Delivery_Dummy.csv" #r后面的內容默認為一個完整的字符串,忽略里面的\ deliveryData = genfromtxt(datapath,delimiter=",")x = deliveryData[1:,:-1]#提取所有的行和除倒數第一列之外的所有的列 y = deliveryData[1:,-1]#提取所有行和最后一列的數據 print(x) print(y)mlr = linear_model.LinearRegression()#定義一個模型變量名lr,調用sklearn包中線性模型線性回歸分析方法mlr.fit(x, y)#利用上述模型對lr中的x,y數據進行建模print(mlr) print("coef:") print(mlr.coef_)#獲取到的截面的參數值 print("intercept") print(mlr.intercept_)#獲取到的截距的參數值xPredict = np.array([90,2,0,0,1]).reshape(1,-1) yPredict = mlr.predict(xPredict)#對所給出的x的預測值進行預測print("predict:") print(yPredict)#打印預測的結果運行結果:
[[ 50. 3. 1. 0. 0.][100. 4. 0. 1. 0.][100. 2. 0. 0. 1.][ 50. 2. 0. 0. 1.][ 80. 2. 0. 1. 0.][ 75. 3. 0. 1. 0.][ 65. 4. 1. 0. 0.][ 90. 3. 1. 0. 0.][ 90. 2. 0. 0. 1.]] [4.8 8.9 6.5 4.2 6.2 7.4 6. 7.6 6.1] LinearRegression() coef: [ 0.05446701 0.62208122 -0.10896785 0.5572758 -0.44830795] intercept 0.44678510998308685 predict: [6.14467005]Process finished with exit code 0總結
以上是生活随笔為你收集整理的基于Python的多元线性回归分析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 某音X-Argus,X-Gorgon,X
- 下一篇: 开发者应知的 如何“推销自己”?