繁体   English   中英

ValueError:形状(100,1)和(2,1)未对齐:1(dim 1)!= 2(dim 0)

[英]ValueError: shapes (100,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0)

我将以下代码用于机器学习问题,结果出现错误ValueError: shapes (100,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0)

我发现了一些类似的主题,但实际上,我找不到主要问题是什么以及如何解决这个问题。 我将输入转换为具有单列的 NumPy 数组。

import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
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
X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)

def regressor():
   
    X_test_new=np.linspace(0,10,100).reshape(100,1)
    prediction=np.array([])
     
    for i in [1,3,6,9]:    
        poly = PolynomialFeatures(degree=i)
        X_train_poly = poly.fit_transform(X_train.reshape(11,1))
        linreg = LinearRegression().fit(X_train_poly, y_train.reshape(11,1))
        prediction = np.concatenate((prediction,linreg.predict(X_test_new)),axis=0)
     
    return prediction
regressor()

PolynomialFeatures返回(11, 2)您的代码需要(11, 1)来运行LinearRegression fit function。 另外,我更改了linreg.predict(...)响应形状以获得用于concatenate操作的单列。

    for i in [1,3,6,9]:    
        poly = PolynomialFeatures(degree=i)
        X_train_poly = poly.fit_transform(X_train.reshape(11,1))[:,1].reshape(-1,1)
        linreg = LinearRegression().fit(X_train_poly, y_train.reshape(11,1))
        prediction = np.concatenate((prediction,linreg.predict(X_test_new)[:,0]),axis=0)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM