Python 应为2D数组,改为1D数组错误

Python 应为2D数组,改为1D数组错误,python,machine-learning,data-science,Python,Machine Learning,Data Science,我得到的错误如下 ValueError:应为2D数组,而应为1D数组:数组=[45000]。 50000. 60000. 80000. 110000. 150000. 200000. 300000. 500000.1000000.].使用数组重塑数据。如果数据具有单个特征,则重塑(-1,1)或数组。如果数据具有单个特征,则重塑(1,-1) 包含一个样本。” 执行以下代码时: # SVR # Importing the libraries import numpy as np i

我得到的错误如下

ValueError:应为2D数组,而应为1D数组:数组=[45000]。 50000. 60000. 80000. 110000. 150000. 200000. 300000. 500000.1000000.].使用数组重塑数据。如果数据具有单个特征,则重塑(-1,1)或数组。如果数据具有单个特征,则重塑(1,-1) 包含一个样本。”

执行以下代码时:

# SVR

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Position_S.csv')
X = dataset.iloc[:, 1:2].values
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 SVR to the dataset
from sklearn.svm import SVR
regressor = SVR(kernel = 'rbf')
regressor.fit(X, y)

# Visualising the SVR results
plt.scatter(X, y, color = 'red')
plt.plot(X, regressor.predict(X), color = 'blue')
plt.title('Truth or Bluff (SVR)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

# Visualising the SVR results (for higher resolution and smoother curve)
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('Truth or Bluff (SVR)')
plt.xlabel('Position level')
plt.ylabel('Salary')
plt.show()

看起来,预期的维度是错误的。你能试试吗

regressor = SVR(kernel='rbf')
regressor.fit(X.reshape(-1, 1), y)

问题是,如果键入y.ndim,您将看到维度为1,如果键入X.ndim,您将看到维度为2

因此,要解决这个问题,必须将y.ndim的结果从1更改为2

为此,只需使用numpy类下的重塑函数

data=pd.read_csv("Position_Salaries.csv")
X=data.iloc[:,1:2].values
y=data.iloc[:,2].values
y=np.reshape(y,(10,1))
它应该能够解决由于尺寸而引起的问题。 在上面的代码之后进行常规的特性缩放,它肯定会工作

如果它对你有效,一定要投票


谢谢。

sklearn
需要2D输入。只需使用
fit(X[:,None],y)
thax ZislsNotZiscould你可以告诉我这个X.resporate(-1,1)。实际上是做什么的。它也解决了这个问题。我实际上通过改成y=dataset.iloc[:,2:3]解决了这个问题。尽管我只给出了3列值。根据错误消息,你输入的数据格式是
[45000,50000,60000,…]
。但是模型希望输入的格式像
[[45000]、[50000]、[60000]、…]
——一个列表。因此,重塑(-1,1)只需更改一种格式。请注意,
restrape()
现在已被弃用。改用
df.values.reformate()