python - LabelEncoder() 对于相同的输入返回不同的值?

标签 python python-3.x scikit-learn

我使用 LabelEncoder() 将分类数据转换为数值数据。我有一个数据集,如下所示:

['x','s','n','t','p','f','c','n','k','e','e','s','s','w','w','p','w','o','p','k','s','u','p']
['x','s','y','t','a','f','c','b','k','e','c','s','s','w','w','p','w','o','p','n','n','g','e']
['b','s','w','t','l','f','c','b','n','e','c','s','s','w','w','p','w','o','p','n','n','m','e']
...

我使用 labelEncoder() 进行转换。代码如下。

for m in M:
  le = preprocessing.LabelEncoder()
  le_fitted = le.fit(m)
  le.classes_
  encoding = list(le.transform(m))

这是我的结果:

[11, 7, 4, 8, 6, 2, 0, 4, 3, 1, 1, 7, 7, 10, 10, 6, 10, 5, 6, 3, 7, 9]

[13, 10, 14, 11, 0, 4, 2, 1, 6, 3, 2, 10, 10, 12, 12, 9, 12, 8, 9, 7, 7, 5]

[0, 9, 11, 10, 4, 3, 1, 0, 6, 2, 1, 9, 9, 11, 11, 8, 11, 7, 8, 6, 6, 5]

我的问题是。为什么同一个角色的数值不同?例如,第一个列表和第二个列表的第一个值都是'x',但我得到了不同的数字:1113。为什么会发生这样的事情呢?当我对这些值进行逆变换时,我可以获得相同的结果。我不是这些结果有什么问题吗?会影响我以后的操作,比如使用朴素贝叶斯分类器吗?

最佳答案

您正在为循环中的每个 m 创建并安装一个新的 LabelEncoder。相反,您希望适合编码器一次,然后使用它来转换每个列表。

您可以通过首先通过所有列表的集合并集来获取所有可能的值进行编码来实现此目的。

from sklearn.preprocessing import LabelEncoder
from functools import reduce

# map each list in M to a set and then reduce using the set union (|)
all_M = list(reduce(lambda u, v: u | v, map(set, M)))
print all_M
#['a', 'c', 'b', 'e', 'g', 'f', 'k', 'm', 'l', 'o', 'n', 'p', 's', 'u', 't', 'w', 'y', 'x']

接下来创建一个编码器并在 all_M 上调用 fit()。然后在您的列表中使用这个合适的编码器:

le = LabelEncoder()
le.fit(all_M)

for m in M:
    encoding = list(le.transform(m))
    print encoding
#[16, 12, 9, 13, 11, 4, 2, 9, 6, 3, 3, 12, 12, 15, 15, 11, 15, 10, 11, 6, 12, 14, 11]
#[16, 12, 17, 13, 0, 4, 2, 1, 6, 3, 2, 12, 12, 15, 15, 11, 15, 10, 11, 9, 9, 5, 3]
#[1, 12, 15, 13, 7, 4, 2, 1, 9, 3, 2, 12, 12, 15, 15, 11, 15, 10, 11, 9, 9, 8, 3]

一般来说,对于任何预处理步骤,您只需调用 fit() 一次(通常是在训练数据上)。随后的数据(包括测试数据)将使用相同的拟合对象进行 transform() 步骤。

关于python - LabelEncoder() 对于相同的输入返回不同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48891875/

相关文章:

python-3.x - 任何级别的日志记录都可以让 assertLogs 通过

python - 如何在 scikit-learn 中获得有意义的 kmeans 结果

Python多项式回归绘图错误?

python - 如何将字符串添加到文件中的奇数行?

python - 如何使用两个单独的数据框在 Pandas 中执行 SumProduct()

python - scikit 总是过度拟合

python - Python while 语句中的 Else 子句

python - Python 中唯一的一组随机数字对

java - 为什么 Java Tensorflow session 似乎重置了状态,而 Python Tensorflow session 却没有?

python - 为什么Python简单的除法计算返回0?