LabelEncoder() 如何对值进行编码?

How does LabelEncoder() encode values?

我想知道 LabelEncoder() 是如何工作的。 这是我的代码的一部分

for att in all_features_test:
if (str(test_home_data[att].dtypes) == 'object'):
    test_home_data[att].fillna( 'Nothing', inplace = True)
    train_home_data[att].fillna( 'Nothing', inplace = True)

    train_home_data[att] = LabelEncoder().fit_transform(train_home_data[att])
    test_home_data[att] = LabelEncoder().fit_transform(test_home_data[att])
else:
    test_home_data[att].fillna( 0, inplace = True)
    train_home_data[att].fillna( 0, inplace = True)

训练和测试数据集都有一个属性 'Condition',它可以保存值 - 差、平均和好

假设 LabelEncoder() 在 train_home_data 中将 Bad 编码为 0,Average 编码为 2,Good 编码为 1。现在 test_home 数据是否相同?

如果没有,那我该怎么办?

你不应该在分裂之后标记,而是在分裂之前。

唯一标签(= classes)是根据字母表排序的,请参阅从页面右上角的 sklearn.preprocessing.LabelEncoder which links to the [source] 截取的源代码中的 uniques = sorted(set(values))

python方法:

def _encode_python(values, uniques=None, encode=False):
    # only used in _encode below, see docstring there for details
    if uniques is None:
        uniques = sorted(set(values))
        uniques = np.array(uniques, dtype=values.dtype)
    if encode:
        table = {val: i for i, val in enumerate(uniques)}
        try:
            encoded = np.array([table[v] for v in values])
        except KeyError as e:
            raise ValueError("y contains previously unseen labels: %s"
                             % str(e))
        return uniques, encoded
    else:
        return uniques

numpy 数组与 classes 相同,参见 return np.unique(values),因为 unique() 默认排序:

numpy 方法:

def _encode_numpy(values, uniques=None, encode=False, check_unknown=True):
    # only used in _encode below, see docstring there for details
    if uniques is None:
        if encode:
            uniques, encoded = np.unique(values, return_inverse=True)
            return uniques, encoded
        else:
            # unique sorts
            return np.unique(values)
    if encode:
        if check_unknown:
            diff = _encode_check_unknown(values, uniques)
            if diff:
                raise ValueError("y contains previously unseen labels: %s"
                                 % str(diff))
        encoded = np.searchsorted(uniques, values)
        return uniques, encoded
    else:
        return uniques

您永远无法确定测试集和训练集具有完全相同的 classes。训练或测试集可能只是缺少三个标签列 'Condition'.

中的一个 class

如果您迫切希望在 train/test 拆分后进行编码,则需要在编码前检查两组中 classes 的数量是否相同。

引用脚本:

Uses pure python method for object dtype, and numpy method for all other dtypes.

python方法(对象类型):

assert sorted(set(train_home_data[att])) == sorted(set(test_home_data[att]))

numpy 方法(所有其他类型):

assert np.unique(train_home_data[att]) == np.unique(test_home_data[att])

我猜我得到了答案。

代码

data1 = [('A', 1), ('B', 2),('C', 3) ,('D', 4)]
data2 = [('D', 1), ('A', 2),('A', 3) ,('B', 4)]

df1 = pd.DataFrame(data1, columns = ['col1', 'col2'])
df2 = pd.DataFrame(data2, columns = ['col1', 'col2'])

print(df1['col1'])
print(df2['col1'])

df1['col1'] = LabelEncoder().fit_transform(df1['col1'])
df2['col1'] = LabelEncoder().fit_transform(df2['col1'])

print(df1['col1'])
print(df2['col1'])

输出

0    A
1    B
2    C
3    D
Name: col1, dtype: object # df1
0    D
1    A
2    A
3    B
Name: col1, dtype: object # df2
0    0
1    1
2    2
3    3
Name: col1, dtype: int64 #df1 encoded
0    2
1    0
2    0
3    1
Name: col1, dtype: int64 #df2 encoded

df1的B编码为1。

并且,

df2的B也被编码为1

因此,如果我对训练和测试数据集进行编码,那么训练集中的编码值将反映在测试数据集中(仅当两者都是标签编码时)

我建议在一个数据集上安装标签编码器并转换两者:

data1 = [('A', 1), ('B', 2),('C', 3) ,('D', 4)]
data2 = [('D', 1), ('A', 2),('A', 3) ,('B', 4)]

df1 = pd.DataFrame(data1, columns = ['col1', 'col2'])
df2 = pd.DataFrame(data2, columns = ['col1', 'col2'])

# here comes the new code:
le = LabelEncoder()
df1['col1'] = le.fit_transform(df1['col1'])
df2['col1'] = le.transform(df2['col1'])