ValueError:预期的二维数组,而是得到一维数组: [英] ValueError: Expected 2D array, got 1D array instead:

查看:26
本文介绍了ValueError:预期的二维数组,而是得到一维数组:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在练习简单线性回归模型时,我遇到了这个错误,我认为我的数据集有问题.

While practicing Simple Linear Regression Model I got this error, I think there is something wrong with my data set.

这是我的数据集:

这里是自变量 X:

这里是因变量 Y:

这里是 X_train

这里是 Y_train

这是错误正文:

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)

谢谢

推荐答案

您需要同时提供 fitpredict 方法 2D 数组.你的 x_trainy_trainx_test 目前只有一维.控制台建议的内容应该有效:

You need to give both the fit and predict methods 2D arrays. Your x_train, y_train and x_test are currently only 1D. What is suggested by the console should work:

x_train= x_train.reshape(-1, 1)
y_train= y_train.reshape(-1, 1)
x_test = x_test.reshape(-1, 1)

这使用 numpy 的 reshape.关于 reshape 的问题过去已经回答过,例如这应该回答 reshape(-1,1) 的意思:numpy reshape 中的 -1 是什么意思?

This uses numpy's reshape. Questions about reshape have been answered in the past, this for example should answer what reshape(-1,1) means: What does -1 mean in numpy reshape?

这篇关于ValueError:预期的二维数组,而是得到一维数组:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆