我遇到了以下错误:
“ValueError: 预期二维数组,但得到的是一维数组:array=[ 45000. 50000. 60000. 80000. 110000. 150000. 200000. 300000. 500000. 1000000.]。如果您的数据只有一个特征,请使用array.reshape(-1, 1)重塑数据;如果数据包含单一样本,请使用array.reshape(1, -1)重塑数据。”
在执行以下代码时:
# SVR# 导入库import numpy as npimport matplotlib.pyplot as pltimport pandas as pd# 导入数据集dataset = pd.read_csv('Position_S.csv')X = dataset.iloc[:, 1:2].valuesy = dataset.iloc[:, 2].values # 特征缩放from sklearn.preprocessing import StandardScalersc_X = StandardScaler()sc_y = StandardScaler()X = sc_X.fit_transform(X)y = sc_y.fit_transform(y)# 将SVR拟合到数据集上from sklearn.svm import SVRregressor = SVR(kernel = 'rbf')regressor.fit(X, y)# 可视化SVR结果plt.scatter(X, y, color = 'red')plt.plot(X, regressor.predict(X), color = 'blue')plt.title('真实或虚构 (SVR)')plt.xlabel('职位等级')plt.ylabel('薪资')plt.show()# 可视化SVR结果(用于更高分辨率和更平滑的曲线)X_grid = np.arange(min(X), max(X), 0.01)X_grid = X_grid.reshape((len(X_grid), 1))plt.scatter(X, y, color = 'red')plt.plot(X_grid, regressor.predict(X_grid), color = 'blue')plt.title('真实或虚构 (SVR)')plt.xlabel('职位等级')plt.ylabel('薪资')plt.show()
回答:
看起来,预期的维度是错误的。你可以尝试以下方法:
regressor = SVR(kernel='rbf')regressor.fit(X.reshape(-1, 1), y)