使用线性回归模型预测单个值时出错

Error while predicting a single value using a linear regression model

我是初学者,正在制作线性回归模型,当我根据测试集进行预测时,效果很好。但是当我试图预测某个特定值的东西时。它给出了一个错误。我正在看的教程,他们没有任何错误。

dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values

# Fitting Linear Regression to the dataset
from sklearn.linear_model import LinearRegression
lin_reg = LinearRegression()
lin_reg.fit(X, y)

# Visualising the Linear Regression results
plt.scatter(X, y, color = 'red')
plt.plot(X, lin_reg.predict(X), color = 'blue')
plt.title('Truth or Bluff (Linear Regression)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

# Predicting a new result with Linear Regression
lin_reg.predict(6.5)

ValueError:应为二维数组,取而代之的是标量数组: 数组=6.5。 如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1)。

根据 Scikit-learn documentation,输入数组的形状应为 (n_samples, n_features)。因此,如果您想要一个具有单个值的示例,您应该期望输入的形状为 (1,1).

这可以通过以下方式完成:

import numpy as np
test_X = np.array(6.5).reshape(-1, 1)
lin_reg.predict(test_X)

您可以通过以下方式检查形状:

test_X.shape

这是因为输入可以有很多样本(即你想一次预测多个数据点),or/and每个样本可以有很多特征。

注:Numpy is a Python library to support large arrays and matrices. When scikit-learn is installed, Numpy should be installed as well.