【问题标题】:OneHotEncoder on multiple columns belonging to same categories属于同一类别的多个列上的 OneHotEncoder
【发布时间】:2019-03-25 03:08:50
【问题描述】:

我有多个由分类变量组成的列,这些变量的形式为 0-4 之间的整数值。但是,所有列都属于同一类别。我尝试使用 scikit learn 中的 OneHotEncoder,但它不会处理列中缺失的类别,当我在我的神经网络模型上测试看不见的数据时,这会导致问题。下面的代码显示了我需要编码的数据类型

>>> df = pd.DataFrame(np.random.randint(low=0, high=4, size=(5, 5)),
                       columns=['color1', 'color2', 'color3', 'color4', 'color5'])
>>> df

   color1  color2  color3  color4  color5
0       0       1       2       3       1
1       3       1       0       1       1
2       0       1       0       3       0
3       0       2       0       1       2
4       0       2       0       3       2

>>> df_onehotencoder = OneHotEncoder(sparse=False)
>>> df2 = df_onehotencoder.fit_transform(df)

>>> df2

array([[1., 0., 1., 0., 0., 1., 0., 1., 0., 1., 0.],
       [0., 1., 1., 0., 1., 0., 1., 0., 0., 1., 0.],
       [1., 0., 1., 0., 1., 0., 0., 1., 1., 0., 0.],
       [1., 0., 0., 1., 1., 0., 1., 0., 0., 0., 1.],
       [1., 0., 0., 1., 1., 0., 0., 1., 0., 0., 1.]])

这仅针对该列中存在的类别而不是缺少的类别为每列生成和数组。我需要为每列具有相同数量的编码列,即缺失的类别将全为零。此外,解码此 OneHotEncoded 数组的最佳选择是什么,以便我可以轻松地将预测输出解码为实际整数值。

【问题讨论】:

  • 所以color1 为 0 与color3 为 0 的颜色相同吗?或者实际上有 20 种颜色?
  • yes 0 表示 color1 和 color3 相同。例如,如果 0 = 红色,则 color1 为 0 为红色,color3 也为红色。

标签: python scikit-learn categorical-data one-hot-encoding categorization


【解决方案1】:

sklearn==0.20开始,OneHotEncoder 具有categories 参数,您可以在其中提供包含给定列的所有可能值的列表列表。

import pandas as pd
df = pd.DataFrame([[0, 1, 2, 3, 1],
 [3, 1, 0, 1, 1],
 [0, 1, 0, 3, 0],
 [0, 2, 0, 1, 2],
 [0, 2, 0, 3, 2]], columns=['color1', 'color2', 'color3', 'color4', 'color5'])

from sklearn.preprocessing import OrdinalEncoder, OneHotEncoder

# Get all the unique values if we don't have them
unique_values = pd.unique(df.values.ravel()) 

ohe = OneHotEncoder(categories=[unique_values]*df.shape[1], sparse=False)
encoded = pd.DataFrame(ohe.fit_transform(
    df), columns=ohe.get_feature_names(df.columns))
>>> encoded

   color1_0  color1_1  color1_2  color1_3  color2_0  color2_1    0
0       1.0       0.0       0.0       0.0       0.0       1.0  ...
1       0.0       0.0       0.0       1.0       0.0       1.0  ...
2       1.0       0.0       0.0       0.0       0.0       1.0  ...
3       1.0       0.0       0.0       0.0       0.0       0.0  ...
4       1.0       0.0       0.0       0.0       0.0       0.0  ...

要找回原来的课程,你可以这样做inverse_transform

>>> ohe.inverse_transform(encoded) 
array([[0, 1, 2, 3, 1],
       [3, 1, 0, 1, 1],
       [0, 1, 0, 3, 0],
       [0, 2, 0, 1, 2],
       [0, 2, 0, 3, 2]], dtype=int64)

【讨论】:

  • @marbel 我在 0.23.4 上运行它。你得到什么输出?
猜你喜欢
  • 2020-10-06
  • 2021-09-11
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 2019-07-27
  • 2020-03-10
  • 2013-12-23
  • 1970-01-01
相关资源
最近更新 更多