【问题标题】:ValueError: Expected 2D array, got scalar array insteadValueError:预期的 2D 数组,取而代之的是标量数组
【发布时间】:2019-06-15 05:18:51
【问题描述】:

在练习简单线性回归模型时,我遇到了这个错误:

ValueError: Expected 2D array, got scalar array instead:
array=60.
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.

这是我的代码(Python 3.7):

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
data = pd.read_csv("hw_25000.csv")


hgt = data.Height.values.reshape(-1,1)
wgt = data.Weight.values.reshape(-1,1)

regression = LinearRegression()
regression.fit(hgt,wgt)

print(regression.predict(60))

【问题讨论】:

    标签: python-3.x scikit-learn linear-regression


    【解决方案1】:

    ValueError 很清楚,predict 需要一个二维数组,但你传递了一个标量。

    hgt = np.random.randint(50, 70, 10).reshape(-1, 1)
    wgt = np.random.randint(90, 120, 10).reshape(-1, 1)
    from sklearn.linear_model import LinearRegression
    from sklearn.metrics import r2_score
    
    regression = LinearRegression()
    regression.fit(hgt,wgt)
    
    regression.predict([[60]])
    

    你得到

    array([[105.10013717]])
    

    【讨论】:

      【解决方案2】:

      简答:

      regression.predict([[60]])
      

      长答案: regression.predict 采用您想要预测的二维数组。数组中的每个项目都是您希望模型预测的“点”。假设我们要在点 60、52 和 31 上进行预测。那么我们会说 regression.predict([[60], [52], [31]])

      我们需要二维数组的原因是因为我们可以在比二维更高维度的空间中进行线性回归。例如,我们可以在 3d 空间中进行线性回归。假设我们要预测给定数据点 (x, y) 的“z”。然后我们需要说regression.predict([[x, y]])。

      更进一步,我们可以为一组“x”和“y”点预测“z”。例如,我们想要预测每个点的“z”值:(0, 2), (3, 7), (10, 8)。然后我们会说regression.predict([[0, 2], [3, 7], [10, 8]]),这充分证明regression.predict需要采用二维数组来预测点。

      【讨论】:

      • 这是一个惊人的反应
      猜你喜欢
      • 2021-11-15
      • 2019-09-19
      • 2019-09-11
      • 2018-12-11
      • 2020-03-19
      • 2021-12-29
      • 1970-01-01
      • 2018-12-21
      • 2018-10-04
      相关资源
      最近更新 更多