在练习简单线性回归模型时出现此错误,我认为我的数据集有问题。
这是错误正文:
ValueError: Expected 2D array, got 1D array instead:
array=[ 7. 8.4 10.1 6.5 6.9 7.9 5.8 7.4 9.3 10.3 7.3 8.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.
这是我的代码:
import pandas as pd
import matplotlib as pt
#import data set
dataset = pd.read_csv('Sample-data-sets-for-linear-regression1.csv')
x = dataset.iloc[:, 1].values
y = dataset.iloc[:, 2].values
#Spliting the dataset into Training set and Test Set
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size= 0.2, random_state=0)
#linnear Regression
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(x_train,y_train)
y_pred = regressor.predict(x_test)
谢谢
原文由 danyialKhan 发布,翻译遵循 CC BY-SA 4.0 许可协议
您需要为
fit
和predict
方法提供二维数组。你的x_train
和x_test
目前只有一维。控制台建议的内容应该有效:这使用 numpy 的
reshape
来转换你的数组。例如,x = [1, 2, 3]
将被转换为矩阵x' = [[1], [2], [3]]
(-1给出矩阵的x维度,从数组的长度和剩余维度推断,1是y维度- 给我们一个 anx 1 矩阵,其中 n 是输入长度)。关于
reshape
的问题在过去已经得到回答,例如应该回答什么reshape(-1,1)
完全意味着: -1 在 numpy reshape 中意味着什么? (下面的其他一些答案也很好地解释了这一点)