【问题标题】:Expected 2D array, got 1D array instead, Reshape Data预期二维数组,得到一维数组,重塑数据
【发布时间】:2018-06-06 12:04:28
【问题描述】:

我真的被这个问题困住了。在使用 LabelEncoder 后,我尝试使用 OneHotEncoder 将我的数据编码为矩阵,但出现此错误:Expected 2D array, got 1D array instead.

在错误消息(包括在下面)的末尾,它说“重塑我的数据”,我以为我做到了,但它仍然无法正常工作。如果我理解 Reshaping,那是否只是当您想将某些数据重塑为不同的矩阵大小时?例如,如果我想将 3 x 2 矩阵更改为 4 x 6?

我的代码在这两行上失败了:

X = X.reshape(-1, 1) # I added this after I saw the error
X[:, 0] = onehotencoder1.fit_transform(X[:, 0]).toarray()

这是我目前的代码:

# Data Preprocessing

# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Import Dataset
dataset = pd.read_csv('Data2.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 5].values
df_X = pd.DataFrame(X)
df_y = pd.DataFrame(y)

# Replace Missing Values
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
imputer = imputer.fit(X[:, 3:5 ])
X[:, 3:5] = imputer.transform(X[:, 3:5])


# Encoding Categorical Data "Name"
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x = LabelEncoder()
X[:, 0] = labelencoder_x.fit_transform(X[:, 0])

# Transform into a Matrix

onehotencoder1 = OneHotEncoder(categorical_features = [0])
X = X.reshape(-1, 1)
X[:, 0] = onehotencoder1.fit_transform(X[:, 0]).toarray()


# Encoding Categorical Data "University"
from sklearn.preprocessing import LabelEncoder
labelencoder_x1 = LabelEncoder()
X[:, 1] = labelencoder_x1.fit_transform(X[:, 1])

这是完整的错误信息:

 File "/Users/jim/anaconda3/lib/python3.6/site-packages/sklearn/preprocessing/data.py", line 1809, in _transform_selected
    X = check_array(X, accept_sparse='csc', copy=copy, dtype=FLOAT_DTYPES)

  File "/Users/jim/anaconda3/lib/python3.6/site-packages/sklearn/utils/validation.py", line 441, in check_array
    "if it contains a single sample.".format(array))

ValueError: Expected 2D array, got 1D array instead:
array=[  2.00000000e+00   7.00000000e+00   3.20000000e+00   2.70000000e+01
   2.30000000e+03   1.00000000e+00   6.00000000e+00   3.90000000e+00
   2.80000000e+01   2.90000000e+03   3.00000000e+00   4.00000000e+00
   4.00000000e+00   3.00000000e+01   2.76700000e+03   2.00000000e+00
   8.00000000e+00   3.20000000e+00   2.70000000e+01   2.30000000e+03
   3.00000000e+00   0.00000000e+00   4.00000000e+00   3.00000000e+01
   2.48522222e+03   5.00000000e+00   9.00000000e+00   3.50000000e+00
   2.50000000e+01   2.50000000e+03   5.00000000e+00   1.00000000e+00
   3.50000000e+00   2.50000000e+01   2.50000000e+03   0.00000000e+00
   2.00000000e+00   3.00000000e+00   2.90000000e+01   2.40000000e+03
   4.00000000e+00   3.00000000e+00   3.70000000e+00   2.77777778e+01
   2.30000000e+03   0.00000000e+00   5.00000000e+00   3.00000000e+00
   2.90000000e+01   2.40000000e+03].
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.

任何帮助都会很棒。

【问题讨论】:

  • 您的数组是 1D 它必须是 2D ...。无论您遇到错误,只需添加 numpy.asmatrix(data) 其中 data 是您传递的数据...或者您可以 reshape 。 .. 在最新版本的 sklearn 中已弃用传递一维数组
  • 嗨 @JayShah 在我添加的代码中:X = X.reshape(-1, 1)。这是重塑数据的正确方法吗?
  • yes X = X.reshape(-1, 1) 是重塑数据的正确方法,但在错误中,但这仅在您的 X 是 numpy 数组 而不是 list... 如果它是一个列表而不是让您的数组列表... 从错误消息中我可以清楚地看到array = [ ] 是一维的,因为它有一个左括号和一个括号,并且在整形后请删除X[:, 1]在变换中,只需放 X

标签: python python-3.x numpy machine-learning sklearn-pandas


【解决方案1】:

试着把你的代码改成这个

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Import Dataset
dataset = pd.read_csv('Data2.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 5].values
df_X = pd.DataFrame(X)
df_y = pd.DataFrame(y)

# Replace Missing Values
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
imputer = imputer.fit(X[:, 3:5 ])
X[:, 3:5] = imputer.transform(X[:, 3:5])


# Encoding Categorical Data "Name"
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x = LabelEncoder()
X[:, 0] = labelencoder_x.fit_transform(X[:, 0])

# Transform into a Matrix

onehotencoder1 = OneHotEncoder(categorical_features = [0])
res_0 = onehotencoder1.fit_transform(X[:, 0].reshape(-1, 1))  # <=== Change
X[:, 0] = res_0.ravel()

# Encoding Categorical Data "University"
from sklearn.preprocessing import LabelEncoder
labelencoder_x1 = LabelEncoder()
X[:, 1] = labelencoder_x1.fit_transform(X[:, 1])

如果您在labelencoder_x1.fit_transform(X[:, 1]) 遇到错误,请输入labelencoder_x1.fit_transform(X[:, 1].reshape(-1, 1))

【讨论】:

  • 感谢您的解决方案!我正在逐行运行它,但它在这一行失败:“X[:, 0] = res_0.ravel()”,说“ravel not found”。
  • 试试 np.ravel(res_0)
【解决方案2】:

好的,我终于让代码工作了。请看下面的解决方案:

# Data Preprocessing

# Import Libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Import Dataset
dataset = pd.read_csv('Data2.csv')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 5].values
df_X = pd.DataFrame(X)
df_y = pd.DataFrame(y)

# Replace Missing Values
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0)
imputer = imputer.fit(X[:, 3:5 ])
X[:, 3:5] = imputer.transform(X[:, 3:5])


# Encoding Categorical Data "Name"
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x = LabelEncoder()
X[:, 0] = labelencoder_x.fit_transform(X[:, 0])


# Encoding Categorical Data "University"
from sklearn.preprocessing import LabelEncoder
labelencoder_x1 = LabelEncoder()
X[:, 1] = labelencoder_x1.fit_transform(X[:, 1])


# Transform Name into a Matrix
onehotencoder1 = OneHotEncoder(categorical_features = [0])
X = onehotencoder1.fit_transform(X).toarray()

# Transform University into a Matrix
onehotencoder2 = OneHotEncoder(categorical_features = [6])
X = onehotencoder2.fit_transform(X).toarray()

【讨论】:

    【解决方案3】:

    当我尝试做同样的事情时,我遇到了同样的错误。我正在转换单列数据。在这里,我如何覆盖这个问题

    encoding_X = OneHotEncoder(categories = [np.unique(X[:,0]).tolist()])
    encoding_X.fit(np.unique(X[:,0]).reshape(-1,1).tolist())
    encoding_X.transform(X[:,0].reshape(-1,1).tolist()).toarray()
    

    【讨论】:

      猜你喜欢
      • 2019-08-17
      • 2021-03-01
      • 2019-10-07
      • 2019-03-28
      • 2021-04-16
      • 1970-01-01
      • 2014-04-21
      • 2021-02-23
      • 1970-01-01
      相关资源
      最近更新 更多