使用Sklearn进行多元多元线性回归 [英] Multivariate multiple linear regression using Sklearn
问题描述
我想使用sklearn
和多维输入和输出样本(例如矢量)来训练线性模型Y = M_1*X_1 + M_2*X_2
.我尝试了以下代码:
I want to train a linear model Y = M_1*X_1 + M_2*X_2
using sklearn
with multidimensional input and output samples (e.g. vectors). I tried the following code:
from sklearn import linear_model
from pandas import DataFrame
x1 = [[1,2],[2,3],[3,4]]
x2 = [[1,1],[3,2],[3,5]]
y = [[1,0],[1,2],[2,3]]
model = {
'vec1': x1,
'vec2': x2,
'compound_vec': y}
df = DataFrame(model, columns=['vec1','vec2','compound_vec'])
x = df[['vec1','vec2']].astype(object)
y = df['compound_vec'].astype(object)
regr = linear_model.LinearRegression()
regr.fit(x,y)
但是出现以下错误:
regr.fit(x,y)
...
array = array.astype(np.float64)
ValueError: setting an array element with a sequence.
有人知道代码有什么问题吗?如果这是训练Y = M_1*X_1 + M_2*X_2
的正确方法?
Does anyone know what is wrong with the code? and if this is a right way to train Y = M_1*X_1 + M_2*X_2
?
推荐答案
只需将您的x1
,x2
和y
列表弄平,就可以了.一种方法是使用数组,如下所示:
Just flatten your x1
, x2
and y
lists and you are good to go. One way to do that is using arrays as follows:
import numpy as np
x1 =np.array(x1).flatten()
x2 =np.array(x2).flatten()
y =np.array(y).flatten()
第二种方法是将ravel
用作:
x1 =np.array(x1).ravel()
x2 =np.array(x2).ravel()
y =np.array(y).ravel()
不使用NumPy的第三种方法是使用列表理解为:
Third way without using NumPy is by using list comprehension as:
x1 =[j for i in x1 for j in i]
x2 =[j for i in x2 for j in i]
y =[j for i in y for j in i]
也许还有更多方法,但是您发现了问题所在.有关更多方法,您可以在此处中查看
There might be more ways but you got what the problem was. For more ways, you can have a look here
输出
LinearRegression(copy_X=True, fit_intercept=True, n_jobs=1, normalize=False)
这篇关于使用Sklearn进行多元多元线性回归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!