【问题标题】:ValueError: shapes (100,1) and (2,1) not aligned: 1 (dim 1) != 2 (dim 0)ValueError:形状(100,1)和(2,1)未对齐:1(dim 1)!= 2(dim 0)
【发布时间】:2021-04-25 06:40:42
【问题描述】:

我使用以下代码解决机器学习问题,结果出现错误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()

【问题讨论】:

    标签: python numpy scikit-learn


    【解决方案1】:

    PolynomialFeatures 返回(11, 2) 您的代码需要(11, 1) 才能运行LinearRegression 拟合函数。另外,我更改了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)
    

    【讨论】:

      猜你喜欢
      • 2019-03-21
      • 2020-01-29
      • 2019-11-23
      • 2017-02-11
      • 1970-01-01
      • 2019-05-28
      • 2021-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多