python - 预期的二维数组,但得到了标量数组
问题描述
我收到此错误
ValueError:预期的 2D 数组,得到了标量数组:array=6.5。如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 重塑您的数据,如果它包含单个样本,则使用 array.reshape(1, -1) 。
在执行此代码时
# SVR
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.svm import SVR
# Load dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values
y = dataset.iloc[:, 2].values
# Fitting the SVR to the data set
regressor = SVR(kernel = 'rbf', gamma = 'auto')
regressor.fit(X, y)
# Predicting a new result
y_pred = regressor.predict(6.5)
解决方案
您需要了解 SVM 的工作原理。您的训练数据是 shape 矩阵(n_samples, n_features)
。这意味着,您的 SVM 在n_features
维度的特征空间中运行。因此,它无法预测标量输入的值,除非n_features
是 1。您只能预测维度向量的值n_features
。因此,如果您的数据集有 5 列,您可以预测任意 5 列的行向量的值。请参见下面的示例。
import numpy as np
from sklearn.svm import SVR
# Data: 200 instances of 5 features each
X = randint(1, 100, size=(200, 5))
y = randint(0, 2, size=200)
reg = SVR()
reg.fit(X, y)
y_test = np.array([[0, 1, 2, 3, 4]]) # Input to .predict must be 2-dimensional
reg.predict(y_test)
推荐阅读
- java - 尝试加载新数据时 Firebase LimitToLast 崩溃
- android - 并行使用 MediaRecorder.AudioSource.CAMCORDER
- javascript - $.contains() 方法的 jQuery 用法
- ajax - 用茉莉花测试猎犬的远程选项
- c# - 如何在mvc中删除列表的特定元素?
- spring - Spring ClasPathXmlApplicationContext registerShutDownHook 与使用 try-with-resources
- json - Symfony FOSRest 返回 html 而不是 json
- java - 在 Android 上使用 Conscrypt 进行 ECC 密钥包装
- soap - 从同一标签多次获取值
- azure - 是否可以在 Azure 中创建没有后端地址池的应用程序网关?