预期的二维数组,但得到的是标量数组

Expected 2d array but got scalar array instead

我收到这个错误

ValueError: Expected 2D array, got scalar array instead: array=6.5. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

执行这段代码时

# 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 的工作原理。您的训练数据是形状为 (n_samples, n_features) 的矩阵。这意味着,您的 SVM 在 n_features 维度的特征 space 中运行。因此,它无法预测标量输入的值,除非 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)
# Predicting a new result with Linear Regression
X_test = np.array([[6.5]])
print(lin_reg.predict(X_test))

# Predicting a new result with Polynomial Regression
print(lin_reg_2.predict(poly_reg.fit_transform(X_test)))