【发布时间】:2020-04-05 19:13:42
【问题描述】:
我有这个代码。它基本上一直有效,直到我尝试使用 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 数组,得到的是标量数组:array=11。 如果您的数据有 单个特征或 array.reshape(1, -1) 如果它包含单个样本。
错误消息对我没有多大帮助,因为我不明白为什么需要对其进行重塑。
【问题讨论】:
-
尝试使用
reg.predict([[11]]) -
为什么会这样? @OferSadan
-
这能回答你的问题吗? Error in Python script "Expected 2D array, got 1D array instead:"? 在那里看我的回答
-
@OferSadan 确实如此。它奏效了。
标签: python scikit-learn linear-regression data-science valueerror