首页 > 解决方案 > 预期的二维数组,但得到了标量数组

问题描述

我收到此错误

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)

标签: pythonmachine-learninganacondaspyderdata-science

解决方案


您需要了解 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)

推荐阅读