我尝试使用以下代码在Python中运行多项式回归后计算预测值:
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)
X = X_train.reshape(-1, 1)
X_predict = np.linspace(0, 10, 100)
poly = PolynomialFeatures(degree=2)
X_train_poly = poly.fit_transform(X)
model = LinearRegression()
reg_poly = model.fit(X_train_poly, y_train)
y_predict = model.predict(X_predict)
运行后,我得到以下错误:
ValueError: Expected 2D array, got 1D array instead:
array=[ 0. 0.1010101 0.2020202 0.3030303 0.4040404 0.50505051 ......
Reshape your data either using array.reshape(-1, 1)
if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
我尝试按照错误消息中所述重新调整数组的形状,因此最后一行代码是:
y_predict = model.predict(X_predict.reshape(-1,1))
但结果我犯了一个错误:
ValueError: shapes (100,1) and (3,) not aligned: 1 (dim 1) != 3 (dim 0)
有人能解释一下我做错了什么吗?你知道吗
您忘记了为预测准备数据,就像为模型准备训练数据一样。尤其是,你忘了用多项式特征来拟合你的X变换。你知道吗
由于用于预测的数据形状必须与用于训练的形状完全匹配,因此需要为X\u train\u poly(用于训练的)重新创建所做的一切。因此,您的线条应该如下所示:
相关问题 更多 >
编程相关推荐