有一个错误,它抛出了一个预期的2D数组,而是抛出了1D数组。错误详细描述如下,在输出之后也找到完整的代码,
输出:
Traceback (most recent call last):
File "<ipython-input-16-d2ec9bb14152>", line 5, in <module>
y = sc_y.fit_transform(y).reshape(1,-1)
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\base.py", line 553, in fit_transform
return self.fit(X, **fit_params).transform(X)
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py", line 639, in fit
return self.partial_fit(X, y)
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\preprocessing\data.py", line 663, in partial_fit
force_all_finite='allow-nan')
File "C:\ProgramData\Anaconda3\lib\site-packages\sklearn\utils\validation.py", line 521, in check_array
"if it contains a single sample.".format(array))
ValueError: Expected 2D array, got 1D array instead:
array=[ 45000. 50000. 60000. 80000. 110000. 150000. 200000. 300000.
500000. 1000000.].
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*```
The complete code is as follows:
**Code:**
```# SVR Template
# Data Preprocessing
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Position_Salaries.csv')
X = dataset.iloc[:, 1:2].values # 1:2 is to consider X as a matrix
y = dataset.iloc[:, 2].values
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
sc_y = StandardScaler()
X = sc_X.fit_transform(X)
y = sc_y.fit_transform(y)
# Fitting the SVR Model to the dataset
from sklearn.svm import SVR
regressor = SVR(kernel = 'rbf')
regressor.fit(X,y)
# Predicting a new result
y_pred = regressor.predict([[6.5]])
# Visualising the SVR Results
plt.scatter(X,y, color = 'red')
plt.plot(X, regressor.predict(X), color = 'blue')
plt.title('Truth or Bluff (SVR Model)')
plt.xlabel(' Position Level ')
plt.ylabel('Salary')
plt.show() ```
[1]: https://i.stack.imgur.com/ksQs2.png
最佳答案
这与以下内容有关:stackoverflow question from a year ago
错误消息确切说明了您需要执行的操作:y = sc_y.fit_transform(y.reshape(-1, 1))
但是,我认为您无需对ys进行标准缩放即可获得SVR的良好性能(尽管x是)ref of statexchange。
关于python - 预期为2D阵列,而是获得了1D阵列。如何解决呢?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59508553/