我已经为形状(4,100)创建了一个空白的numpy数组,并且我试图在for循环中为其分配/添加值,但是我一直在获取原始数组。我试过使用串联和附加,但这似乎也不起作用。我期望具有所有预测值的形状为(4,100)的输出数组。
下面是我要执行的操作的代码
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
desired_width = 3000
pd.set_option('display.width',desired_width)
pd.set_option('display.max_columns',300)
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
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
degrees = [1, 3, 6, 9]
test_x = np.linspace(0,10,100).reshape(-1,1)
X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)
res = np.zeros((4,100), int)
for pos, degree in enumerate(degrees):
poly = PolynomialFeatures(degree=degree)
X_trans = poly.fit_transform(X_train.reshape(-1,1))
lm = LinearRegression().fit(X_trans, y_train)
print('goodness of fit is {}'.format(lm.score(poly.fit_transform(X_test.reshape(-1,1)),y_test)))
test_x_poly = poly.fit_transform(test_x)
y_predict = lm.predict(test_x_poly)
print(y_predict.shape)
print(y_predict.reshape(1,100).shape)
res[pos,:] = y_predict.reshape(1,100)
我在代码中发现了错误。我必须用float而不是整数来初始化数组。