【问题标题】:Getting an error: Reshape your data either using array出现错误:使用数组重塑数据
【发布时间】:2020-04-07 04:01:38
【问题描述】:

我正在使用 SKlearn 学习线性回归,但我不断收到此错误:

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
%matplotlib inline

mydf = pd.read_csv("Salary_Data.csv")

X = np.array(mydf["YearsExperience"])
Y = np.array(mydf["Salary"])

xtrain, xtest, ytrain, ytest = train_test_split(X, Y, test_size=0.2)

lr = LinearRegression()
lr.fit(xtrain,ytrain)  ##HERE AN ERROR ARISES

错误是:

ValueError: Expected 2D array, got 1D array instead:
array=[ 4.   2.2  2.9  8.2 10.5  3.   4.9  1.5  5.1  4.  10.3  4.1  3.2  2.
  9.6  6.   7.9  7.1  3.2  8.7  6.8  9.5  3.9  1.1].
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 pandas scikit-learn linear-regression


【解决方案1】:

Sklearn 期待您的

  • 自变量(X)具有多个特征(多列)因此是一个二维数组。

  • 因变量(y)具有单个值,例如类标签(在分类的情况下)或数值(在回归的情况下)

在您的情况下,自变量(X)只有一个特征,因此您遇到了问题。可以按照其他答案中的建议解决

【讨论】:

    【解决方案2】:

    我建议你Reshape your data either using array.reshape(-1, 1)

    lr.fit(xtrain,ytrain.reshape(-1, 1))
    

    Scikit-Learn 需要这样的输入:

    array([[0],
           [1],
           [2],
           [3]])
    

    不是这样的:

    array([0, 1, 2, 3])
    

    就是这样。

    【讨论】:

    • 哦,成功了。你能告诉我是什么问题吗?我从未见过这样的重塑解决方案。我的数据出了什么问题?
    • 非常有帮助。谢谢尼古拉斯。
    猜你喜欢
    • 2022-01-14
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-02-05
    • 1970-01-01
    • 2012-09-19
    • 1970-01-01
    相关资源
    最近更新 更多