我的代码linreg.predict()没有给出正确答案是什么问题?

时间:2019-09-06 17:47:45

标签: python scikit-learn regression reshape numpy-broadcasting

所以我给的问题是

在训练数据X_train上为1、3、6和9度写一个适合多项式LinearRegression模型的函数(在sklearn.preprocessing中使用PolynomialFeatures创建多项式特征,然后拟合一个线性回归模型)对于每个模型,在x = 0到10的区间内找到100个预测值(例如np.linspace(0,10,100)),并将其存储在numpy数组中。该数组的第一行应对应于在度1,第二行度3,第三行度6和第四行度9上训练的模型的输出。

所以我自己尝试了该问题,但失败了,并看到了其他人的GitHub代码,与我非常相似,但是有效。

那么我的代码和其他人的代码有什么区别?

在我提问之前,这里有一些基本代码

np.random.seed(0)
n = 15
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10


X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)

这是我的方法

pred=np.linspace(0,10,100).reshape(100,1)
k=np.zeros((4,100))

for count,i in enumerate([1,3,6,9]):   
    poly = PolynomialFeatures(degree=i)
    X_poly = poly.fit_transform(X_train.reshape(-1,1))
    linreg = LinearRegression()
    linreg.fit(X_poly,y_train.reshape(-1,1))
    pred = poly.fit_transform(pred.reshape(-1,1))
    t=linreg.predict(pred)
    #print(t)                      #used for debugging
    print("###   ****   ####")     #used for debugging
    k[count,:]=t.reshape(1,-1)    


print(k)

这是有效的代码

result = np.zeros((4, 100))
for i, degree in enumerate([1, 3, 6, 9]):
    poly = PolynomialFeatures(degree=degree)
    X_poly = poly.fit_transform(X_train.reshape(11,1))
    linreg = LinearRegression().fit(X_poly, y_train)
    y=linreg.predict(poly.fit_transform(np.linspace(0,10,100).reshape(100,1)))
    result[i, :] = y
print(result)

我的方法出现错误

     13     print("###   ****   ####")  
---> 14     k[count,:]=t.reshape(1,-1)
     15 
     16 

ValueError: could not broadcast input array from shape (200) into shape (100)

其他代码工作正常

1 个答案:

答案 0 :(得分:1)

区别在于linreg.predict的参数。您正在用pred的结果覆盖poly.fit_transform变量,这在循环的第一次迭代中将其形状从(100,1)更改为(200,2)。在第二次迭代中,t不再适合k,从而导致您面临错误。