我怎样才能重塑我的数组以适应 (4,100)

How can I reshape my array to fit (4,100)

这是我的代码,但是当我 运行 它时,我没有得到正确的形状。我需要它 return 一个形状为 (4,100) 的 numpy 数组。

为了了解我在做什么,我在指定度数的训练数据上拟合多项式 LinearRegression 模型,然后通过转置 100 行单列生成多项式值的预测输出到单行 100 列数组。

np.random.seed(0)
C = 15
n = 60
x = np.linspace(0, 20, n)  # x is drawn from a fixed range
y = x ** 3 / 20 - x ** 2 - x + C * np.random.randn(n)

x = x.reshape(-1, 1) # convert x and y from simple array to a 1-column matrix for input to sklearn regression 
y = y.reshape(-1, 1)

# Create the training and testing sets and their targets
X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)


def model():
    
    degs = (1, 3, 7, 11)
    #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.
    def poly_y(i):
        poly = PolynomialFeatures(degree = i)
        x_poly = poly.fit_transform(X_train.reshape(-1,1))
        linreg = LinearRegression().fit(x_poly, y_train)
        #x_orig = np.linspace(0, 20, 100)
        y_pred = linreg.predict(poly.fit_transform(np.linspace(0, 20, 100).reshape(-1,1)))
        y_pred = y_pred.T
        return(y_pred.reshape(-1,1))
    
    ans = poly_y(1)
    for i in degs:
        temp = poly_y(i)        
        ans = np.vstack([ans, temp])
    
    return ans

model()   

输出图像:

结合对您问题的评论,并作简要说明:

您目前正在做

ans = poly_y(1)
for i in degs:
    temp = poly_y(i)        
    ans = np.vstack([ans, temp])

您将 ans 设置为 1 度的结果,然后遍历 所有 度并将它们叠加到 ans。但是,所有度数都包含 1,因此您获得度数 1 两次,并最终得到一个 500 x 1 数组。因此,您可以删除第一行。然后,你有这个循环,你可以在其中重复堆叠到 ans,这可以使用列表理解(例如,使用 [poly_y(deg) for deg in degs])一次性完成。堆叠导致 400 x 1 阵列,这不是您想要的。你可以重塑它,或者你可以使用 hstack。后者returns一个100×4的数组;要获得 4 x 100 数组,只需转置它即可。

所以最终的解决方案是将上面四行替换为

ans = np.hstack([poly_y(deg) for deg in degs]).T

(如果你想变得更花哨,请将这些行和 return ans 行替换为

return np.hstack([poly_y(deg) for deg in degs]).T

)