首页 文章

使用sklearn和线性回归时出错:形状(1,16)和(1,1)未对齐:16(dim 1)!= 1(dim 0)

提问于
浏览
6

我看到了机器学习的故事,我偶然发现了youtube siraj和他的Udacity视频,想要尝试拿起一些东西 .

他的视频参考:https://www.youtube.com/watch?v=vOppzHpvTiQ&index=1&list=PL2-dafEMk2A7YdKv4XfKpfbTH5z6rEEj3

在他的视频中,他有一个导入和读取的txt文件,但是当我尝试重新创建txt文件时,它无法正确读取 . 相反,我尝试使用相同的数据创建一个pandas数据帧并对其执行线性回归/预测,但后来我得到了以下错误 .

找到具有不一致样本数的输入变量:[1,16]以及关于传递1d数组的内容,我需要重新整形它们 .

然后,当我试图在这篇文章后重塑它们:Sklearn : ValueError: Found input variables with inconsistent numbers of samples: [1, 6]

我收到这个错误....

shapes (1,16) and (1,1) not aligned: 16 (dim 1) != 1 (dim 0)

这是我在下面的代码 . 我知道这可能是一个语法错误,我只是不熟悉这个scklearn,并希望得到一些帮助 .

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import linear_model

#DF = pd.read_fwf('BrainBodyWeight.txt')
DF = pd.DataFrame()
DF['Brain'] = [3.385, .480, 1.350, 465.00,36.330, 27.660, 14.830, 1.040, 4.190, 0.425, 0.101, 0.920, 1.000, 0.005, 0.060, 3.500 ]

DF['Body'] = [44.500, 15.5, 8.1, 423, 119.5, 115, 98.2, 5.5,58, 6.40, 4, 5.7,6.6, .140,1, 10.8]

try:
    x = DF['Brain']
    y = DF['Body']

    x = x.tolist()
    y = y.tolist()

    x = np.asarray(x)
    y = np.asarray(y)


    body_reg = linear_model.LinearRegression()
    body_reg.fit(x.reshape(-1,1),y.reshape(-1,1))
    plt.scatter(x,y)
    plt.plot(x,body_reg.predict(x))
    plt.show()
except Exception as e:
    print(e)

任何人都可以解释为什么sklearn不喜欢我的输入????

1 回答

  • 3

    documentation LinearRegression.fit()需要一个 [n_samples,n_features] 形状的x数组 . 这就是为什么你在调用fit之前重塑你的 x 数组的原因 . 因为如果你没有一个具有(16,)形状的数组,它不符合所需的 [n_samples,n_features] 形状,那么就没有给出 n_features .

    x = DF['Brain']
    x = x.tolist()
    x = np.asarray(x)
    
    # 16 samples, None feature
    x.shape
    (16,)
    
    # 16 samples, 1 feature
    x.reshape(-1,1).shape
    (16,1)
    

    同样的要求适用于LinearRegression.predict函数(以及一致性),您只需在调用预测函数时进行相同的整形 .

    plt.plot(x,body_reg.predict(x.reshape(-1,1)))
    

    或者,您也可以在调用任何函数之前重新整形 x 数组 .

    对于功能参考,只需调用 DF['Brain'].values 即可轻松获取内部numpy值数组 . 您不需要将其强制转换为list - > numpy数组 . 所以你可以使用它而不是所有的转换:

    x = DF['Brain'].values.reshape(1,-1)
    y = DF['Body'].values.reshape(1,-1)
    
    body_reg = linear_model.LinearRegression()
    body_reg.fit(x, y)
    

相关问题