Python 线性回归模型预测函数不起作用

Python 线性回归模型预测函数不起作用,python,scikit-learn,linear-regression,data-science,valueerror,Python,Scikit Learn,Linear Regression,Data Science,Valueerror,我有这个密码。它基本上一直有效,直到我尝试使用predict(x-value)得到y-value答案 代码如下 import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression df = pd.read_csv('l

我有这个密码。它基本上一直有效,直到我尝试使用
predict(x-value)
得到
y-value
答案

代码如下

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

df = pd.read_csv('linear_data.csv')
x = df.iloc[:,:-1].values
y = df.iloc[:,1:].values
x_train, x_test, y_train, y_test= train_test_split(x,y,test_size=1/3,random_state=0)
reg = LinearRegression()
reg.fit(x_train, y_train)

y_predict = reg.predict(x_test)

y_predict_res = reg.predict(11) --> #This is the error! 11 is the number of years to predict the salary
print(y_predict_res)

我得到的错误是:

ValueError:应为2D数组,但改为标量数组:数组=11。 使用数组重塑数据。如果数据具有 单个特征或阵列。如果包含单个样本,则重塑(1,-1)


错误消息对我没有多大帮助,因为我不明白为什么需要对其进行整形。

请注意,它所期望的参数X是类似数组或稀疏矩阵,形状(n\u样本,n\u特征),这意味着它不能是单个数字。数字/值必须是数组的一部分。

尝试使用
reg.predict([[11]])
为什么这样做@这能回答你的问题吗?看到我的答案了吗there@OferSadan是的。成功了。