python - “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,所有其他变量都是回归量。
谢谢,
解决方案
似乎当你这样做时:
X = sc_X.fit_transform(X)
X 包含多个变量。8 具体
接下来你做:
regressor.predict(sc_X.transform(np.array([[6.5]])))
现在,您尝试转换一个新样本,该样本只有一个变量,但sc
模型是在具有多个变量的数据上训练的。
推荐阅读
- android - 尝试复制我的 Android Studio 项目并使其运行
- python - list = [] 与 list.clear() 之间的区别
- html - 如何使用单引号使 vscode 自动完成 HTML 标签的属性?
- java - TabLayout 中的 AsyncTask
- html - 如何在 CSS 中找到关注孩子的兄弟姐妹
- python - 带有附加字典的熊猫从宽到长
- python - 如何创建一个用户只能在 django 网站上点赞一次的点赞按钮?
- php - 我们可以根据不同的语言使用多种字体使用干预库创建覆盖文本吗?
- javascript - 正则表达式使用 javascript 检查数字长度并允许长度在 6 到 8 之间
- java - 如何从我输入到 FireStore 的数据中向地图添加自定义标记