在练习简单线性回归模型时,我得到了这个错误,

Here is my data set:

Here is independent variable X:

Here is dependent variable Y:

Here is X_train

Here Is 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两种二维数组的方法.您的x_trainy_trainx_test当前仅为1D.控制台建议的操作应该有效:

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

这使用了numpy的reshape.关于reshape的问题在过go 已经得到了回答,例如,这个例子应该回答reshape(-1,1)的意思:What does -1 mean in numpy reshape?

Python-3.x相关问答推荐

使用魔方无法从图像中识别单个字符

将f-字符串放置在f-字符串内

使用数据库将文件从Sharepoint下载到文件系统

Pandas -我们如何在一行中应用多个要求

与 pandas 0.22 相比,pandas 2.0.3 中的 df.replace() 会抛出 ValueError 错误

继承自 Counter 与 dict 的类实例的 Deepcopy

requests.exceptions.InvalidSchema:未找到连接适配器.我试图遍历一个列表

Django在POST到外部URL时如何进行CSRF保护? 更新

Pandas教程:如何更新行内数值的位置

Pandas 在每组两个条件之间获得时间增量

DynamoDB - boto3 - batch_write_item:提供的关键元素与架构不匹配

如何使用 django rest 框架在 self forienkey 中删除多达 n 种类型的数据?

Python:如何从句子/段落中提取地址(非正则表达式方法)?

段落中句子的索引

spaCy 中的匹配模式返回空结果

sys.stdin.readline() 读取时没有提示,返回 'nothing in between'

Selenium (Python) - 使用 Chrome 网络驱动程序等待下载过程完成

无法在 Windows 8 中使用 Python 3.3 找到 vcvarsall.bat

在没有时间的python中创建日期

将 Python 字节转换为无符号 8 位整数