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



我有这个代码。它基本上一直有效,直到我尝试使用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)

我得到的错误是:

值错误:预期的 2D 数组,而是获得标量数组:array=11。 如果使用 array.reshape(-1, 1( 重塑数据,前提是您的数据具有 单个特征或 array.reshape(1, -1( 如果它包含单个样本。

错误消息对我没有多大帮助,因为我不明白为什么我需要重塑它。

请注意,它期望的参数 X 是array_like或稀疏矩阵、形状(n_samples、n_features(,这意味着它不能是单个数字。数字/值必须是数组的一部分。