python - 出现错误 : Reshape your data either using array

标签 python pandas scikit-learn linear-regression

我正在使用 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.

你能帮我吗?

最佳答案

我建议您使用 array.reshape(-1, 1) reshape 数据

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

Scikit-Learn 需要这样的输入:

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

像这样:

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

事情就是这样。

关于python - 出现错误 : Reshape your data either using array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59326998/

相关文章:

Python 将包含列表元组的字符串解压为变量

python - 将数据转换为 Pandas 中缺失的数据

python - 通过拆分索引名称将 1D pandas DataFrame 重新排列为 2d

python - 如何为 Kmeans 散点图并打印异常值

flask - python : Erratic joblib behaviour on Flask

python - 如何解析 Apple 的 IAP 收据格式错误的 JSON?

在列表中查找最大值及其索引的 Pythonic 方法?

python - 不支持的格式字符 'm'

python - 将 1 分钟间隔内的最后一个值分配给 pandas DataFrame 的行

scikit-learn - 无法从 sckits.learn 导入 GMM 函数