首页 > 解决方案 > “ValueError:预期的 2D 数组,得到 1D 数组”的问题

问题描述

我需要运行 SVR(支持向量回归)。我有一个 CSV 数据框。使用一个目标变量和多个回归器运行 OLS 回归没有问题。但是我对这部分代码有疑问。

所以,这是我的代码:


import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR

sc_X = StandardScaler()
sc_y = StandardScaler()
X = sc_X.fit_transform(X)
y = sc_y.fit_transform(y)

y_pred = sc_y.inverse_transform ((regressor.predict (sc_X.transform(np.array([[6.5]])))))
plt.scatter(X, y, color = 'magenta')
plt.plot(X, regressor.predict(X))
plt.title('SVR')
plt.xlabel('X')
plt.ylabel('VF')
plt.show()

X_grid = np.arange(min(X), max(X), 0.1)
X_grid = X_grid.reshape((len(X_grid), 1))
plt.scatter(X, y)
plt.plot(X_grid, regressor.predict(X_grid))
plt.title('SVR')
plt.xlabel('X')
plt.ylabel('VF')
plt.show()

我有以下错误消息:“ValueError: Expected 2D array, got 1D array instead reshape your data or using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if它包含一个样本。”

这是我第一次遇到这个问题。我在其他主题中看到的并不稀缺,但实际上我不明白在哪里重塑我的代码中的数据。当我尝试这样做时,它说 DataFrame 没有重塑功能。

这是我的数据集的图片。目标是 VF,所有其他变量都是回归量。我的数据集

谢谢,

标签: pythonarraysnumpyscikit-learnregression

解决方案


似乎当你这样做时:

 X = sc_X.fit_transform(X)

X 包含多个变量。8 具体

接下来你做:

 regressor.predict(sc_X.transform(np.array([[6.5]])))

现在,您尝试转换一个新样本,该样本只有一个变量,但sc模型是在具有多个变量的数据上训练的。


推荐阅读