我正在使用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.
你能帮我吗?
答案 0 :(得分: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])
就是这样。
答案 1 :(得分:0)
Sklearn希望您
自变量(X)具有多个特征(多列),因此是2维数组。
因变量(y)具有单个值,例如类标签(在分类的情况下)或数值(在回归的情况下)
在您的情况下,自变量(X)仅具有一个功能,因此您已经遇到了问题。可以按照其他答案中的建议解决