Multivariate/Multiple Linear Regression in Scikit Learn?

谁都会走 提交于 2019-12-04 07:55:30

问题


I have a dataset (dataTrain.csv & dataTest.csv) in .csv file with this format:

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)

How to do that in scikit-learn?


回答1:


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]



回答2:


That's correct you need to use .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)

you can get them with:

Coefficients = model.coef_
intercept = model.intercept_



来源:https://stackoverflow.com/questions/42055615/multivariate-multiple-linear-regression-in-scikit-learn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!