【问题标题】:Expected 2D array, got 1D array instead error预期的二维数组,得到一维数组而不是错误
【发布时间】:2019-03-28 10:44:08
【问题描述】:

我得到的错误是

"ValueError: 预期二维数组,得到一维数组:array=[ 45000. 50000. 60000. 80000. 110000. 150000. 200000. 300000. 500000. 1000000.]。如果您的数据具有单个特征,则使用 array.reshape(-1, 1) 或 array.reshape(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()

【问题讨论】:

  • sklearn 需要二维输入。只需使用fit(X[:,None], y)
  • thax ZislsNotZis

标签: python machine-learning data-science


【解决方案1】:

看来,预期的尺寸是错误的。你可以试试:

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

【讨论】:

  • 你能告诉我这个 x.reshape(-1,1).actually 是做什么的。它也解决了这个问题。我实际上是通过更改为 y = dataset.iloc[:, 2 :3].values 尽管我只给出了 3 列。
  • 根据错误信息,您输入的数据格式为[45000, 50000, 60000, ...]。但该模型期望输入格式为[[45000], [50000], [60000], ...] - 列表列表。所以 reshape(-1, 1) 只是改变一个格式。
  • 请注意,reshape() 现在已弃用。请改用df.values.reshape()
【解决方案2】:

问题是,如果你输入 y.ndim,你会看到维度为 1,如果你输入 X.ndim,你会看到维度为 2。

所以要解决这个问题,你必须将 y.ndim 的结果从 1 更改为 2。

为此,只需使用 numpy 类下的 reshape 函数。

data=pd.read_csv("Position_Salaries.csv")
X=data.iloc[:,1:2].values
y=data.iloc[:,2].values
y=np.reshape(y,(10,1))

应该可以解决由于维度引起的问题。 在上面的代码之后进行常规的特征缩放,它肯定会起作用。

如果对你有用,请投票。

谢谢。

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 2022-01-22
    • 2023-03-07
    • 2019-08-17
    • 2018-01-15
    • 1970-01-01
    • 2018-06-06
    • 2020-06-01
    • 2021-03-01
    相关资源
    最近更新 更多