我正在嘗試編寫一個函數,該函數使用PolynomialFeatures來訓練和測試LinearRegression。這裏是我的代碼:PolynomialFeatures LinearRegression ValueError:形狀不對齊
def get_lr2(pdeg):
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics.regression import r2_score
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
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)
test_data = np.linspace(0,10,100).reshape(100,1)
X_trainT = X_train.reshape(-1,1)
y_trainT = y_train.reshape(-1,1)
poly = PolynomialFeatures(degree=pdeg)
X_poly = poly.fit_transform(X_trainT)
X_train1, X_test1, y_train1, y_test1 = train_test_split(X_poly, y_trainT, random_state = 0)
linreg1 = LinearRegression().fit(X_train1, y_train1)
return linreg1.predict(test_data)
當我調用該函數(get_lr2(1))我得到
-------------------------------------------------------------------------
ValueError Traceback (most recent call last)
---> 84 get_lr2(1)
<ipython-input-29-a9966181155e> in get_lr2(pdeg)
23 X_train1, X_test1, y_train1, y_test1 = train_test_split(X_poly, y_trainT, random_state = 0)
24 linreg1 = LinearRegression().fit(X_train1, y_train1)
---> 25 return linreg1.predict(test_data)
ValueError: shapes (100,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0)
你能幫忙嗎?
測試和訓練數據的形狀(X,Y尺寸)似乎是不一樣的。你能檢查'test_data'和'X_train1'在你的函數中有相同的形狀嗎? – ShreyasG