【问题标题】:Python sklearn - Determine the encoding order of LabelEncoderPython sklearn - 确定LabelEncoder的编码顺序
【发布时间】:2018-12-20 21:11:17
【问题描述】:

我希望确定 sklearn LabelEncoder 的标签(即 0,1,2,3,...)以适应分类变量的可能值的特定顺序(例如 ['b', 'a', ' c','d'])。我猜 LabelEncoder 选择按字典顺序拟合标签,如本例所示:

from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
le.fit(['b', 'a', 'c', 'd' ])
le.classes_
array(['a', 'b', 'c', 'd'], dtype='<U1')
le.transform(['a', 'b'])
array([0, 1])

如何强制编码器遵守 .fit 方法中第一次遇到的数据顺序(即将 'b' 编码为 0,'a' 编码为 1,'c' 编码为 2,以及' d' 到 3)?

【问题讨论】:

标签: python scikit-learn encoder


【解决方案1】:

你不能在原始版本中这样做。

LabelEncoder.fit() 使用numpy.unique,它将始终按排序返回数据,如given in source

def fit(...):
    y = column_or_1d(y, warn=True)
    self.classes_ = np.unique(y)
    return self

所以如果你想这样做,你需要重写fit() 函数。像这样的:

import pandas as pd
from sklearn.preprocessing import LabelEncoder
from sklearn.utils import column_or_1d

class MyLabelEncoder(LabelEncoder):

    def fit(self, y):
        y = column_or_1d(y, warn=True)
        self.classes_ = pd.Series(y).unique()
        return self

那么你可以这样做:

le = MyLabelEncoder()
le.fit(['b', 'a', 'c', 'd' ])
le.classes_
#Output:  array(['b', 'a', 'c', 'd'], dtype=object)

在这里,我使用pandas.Series.unique() 来获取独特的课程。如果您因任何原因无法使用 pandas,请参阅使用 numpy 完成此问题的这个问题:

【讨论】:

  • 如果有人发现这一点并询问为什么它不起作用:我不小心使用了le.fit_transform(),它没有调用自定义fit() 方法。所以检查它是否不适合你
【解决方案2】:

注意,现在使用http://contrib.scikit-learn.org/categorical-encoding/ordinal.html 可能有更好的方法来执行此操作。具体看mapping参数:

用于编码的类到标签的映射,可选。这 dict 包含键“col”和“mapping”。 “col”的值应该 是特征名称。 “映射”的值应该是一个字典 “原始标签”到“编码标签”。示例映射:[{‘col’: ‘col1’, ‘映射’:{无:0,‘a’:1,‘b’:2}}]

【讨论】:

    【解决方案3】:

    Vivek Kumar 解决方案对我有用,但必须这样做

    class LabelEncoder(LabelEncoder):
    
    def fit(self, y):
        y = column_or_1d(y, warn=True)
        self.classes_ = pd.Series(y).unique().sort()
        return self
    

    【讨论】:

    • 问题的整个想法是不对类的顺序进行排序。这就是为什么我在回答中选择不这样做。
    【解决方案4】:

    注意 :: 这不是标准方法,而是一种 hacky 方法 我使用 'classes_' 属性来自定义我的映射

    from sklearn import preprocessing
    le_temp = preprocessing.LabelEncoder()
    le_temp = le_temp.fit(df_1['Temp'])
    print(df_1['Temp'])
    le_temp.classes_ = np.array(['Cool', 'Mild','Hot'])
    print("New classes sequence::",le_temp.classes_)
    df_1['Temp'] = le_temp.transform(df_1['Temp'])
    print(df_1['Temp'])
    

    我的输出看起来像

    1      Hot
    2      Hot
    3      Hot
    4     Mild
    5     Cool
    6     Cool
    
    Name: Temp, dtype: object
    New classes sequence:: ['Cool' 'Mild' 'Hot']
    
    1     2
    2     2
    3     2
    4     1
    5     0
    6     0
    
    Name: Temp, dtype: int32
    

    【讨论】:

      猜你喜欢
      • 2022-01-15
      • 2020-03-04
      • 2017-07-26
      • 2018-08-02
      • 2020-10-29
      • 2017-06-06
      • 2017-10-12
      • 2016-12-09
      • 2020-12-22
      相关资源
      最近更新 更多