Python Scikit Learn 中的多元/多元线性回归?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42055615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multivariate/Multiple Linear Regression in Scikit Learn?
提问by Drizzer Silverberg
I have a dataset (dataTrain.csv & dataTest.csv) in .csv file with this format:
我在 .csv 文件中有一个数据集(dataTrain.csv & dataTest.csv),格式如下:
Temperature(K),Pressure(ATM),CompressibilityFactor(Z)
273.1,24.675,0.806677258
313.1,24.675,0.888394713
...,...,...
And able to build a regression model and prediction with this code:
并且能够使用以下代码构建回归模型和预测:
import pandas as pd
from sklearn import linear_model
dataTrain = pd.read_csv("dataTrain.csv")
dataTest = pd.read_csv("dataTest.csv")
# print df.head()
x_train = dataTrain['Temperature(K)'].reshape(-1,1)
y_train = dataTrain['CompressibilityFactor(Z)']
x_test = dataTest['Temperature(K)'].reshape(-1,1)
y_test = dataTest['CompressibilityFactor(Z)']
ols = linear_model.LinearRegression()
model = ols.fit(x_train, y_train)
print model.predict(x_test)[0:5]
However, what I want to do is multivariate regression. So, the model will be CompressibilityFactor(Z) = intercept + coef*Temperature(K) + coef*Pressure(ATM)
但是,我想做的是多元回归。所以,模型将是CompressibilityFactor(Z) = intercept + coef*Temperature(K) + coef*Pressure(ATM)
How to do that in scikit-learn?
如何在 scikit-learn 中做到这一点?
回答by piRSquared
If your code above works for univariate, try this
如果您上面的代码适用于单变量,请尝试此操作
import pandas as pd
from sklearn import linear_model
dataTrain = pd.read_csv("dataTrain.csv")
dataTest = pd.read_csv("dataTest.csv")
# print df.head()
x_train = dataTrain[['Temperature(K)', 'Pressure(ATM)']].to_numpy().reshape(-1,2)
y_train = dataTrain['CompressibilityFactor(Z)']
x_test = dataTest[['Temperature(K)', 'Pressure(ATM)']].to_numpy().reshape(-1,2)
y_test = dataTest['CompressibilityFactor(Z)']
ols = linear_model.LinearRegression()
model = ols.fit(x_train, y_train)
print model.predict(x_test)[0:5]
回答by Fabrizio Peruzzo
That's correct you need to use .values.reshape(-1,2)
这是正确的,你需要使用 .values.reshape(-1,2)
In addition if you want to know the coefficients and the intercept of the expression:
此外,如果您想知道表达式的系数和截距:
CompressibilityFactor(Z) = intercept + coefTemperature(K) + coefPressure(ATM)
CompressibilityFactor(Z) = 截距 + coef温度(K) + coef压力(ATM)
you can get them with:
您可以通过以下方式获取它们:
Coefficients = model.coef_
intercept = model.intercept_
系数 = model.coef_
截距 = model.intercept_