在字典上使用标签编码器

2024-10-02 22:25:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用sklearnLabelEncoder。我知道如何将其用于一维阵列,但我的用例如下:

我有多个这样的dict数组(这实际上是在分类器中分配每个文本标签u'a'u'b'等的开销),所有这些都在dict中:

{'open_model':    
[
    {u'a': 47502.125, u'c': 45.3, u'd': 2.3, u'e': 0.45},
    {u'b': 121, u'a': 1580.5625, u'c': 12, u'e': 62,u'd':0.343},
    {u'e': 12321, u'b': 4, u'a': 0.1112}
    ],
 'closed_model':
 [
    {u'a': 1231.22, u'c': 43.1},
    {u'b': 342.2, u'a': 121.1, u'c': 343},
    {u'b': 14.2, u'a': 53.2}
    ]
}

我需要能够将其编码为数字标签,然后解码回所有标签,例如:

^{pr2}$

我可以有效地为每一行生成最佳标签的预测,因此:

[5, 4, 1] perhaps in this case.

我需要做的是把这个解码回:

[u'e',u'd', u'a'] perhaps in this case.

如何在dict键是我的标签的dict数组上获得相同的LabelEncoder功能?在

注意,dict数组中的dict是一个不同的长度,但是我有所有潜在标签的列表,即对于开放的模型标签,set([u'a',u'b',u'c',u'd',u'e']),对于封闭的模型标签:set([u'a',u'b',u'c'])。在


Tags: in模型文本model分类器标签数组open
2条回答

似乎你总是有“a”、“b”、“c”、“d”、“e”。如果是这样的话,你为什么不使用熊猫数据帧而忘记编码器呢?你有点需要重写你使用的字典的键,所以它无论如何都会很混乱!在

import pandas as pd
i = [
{u'a': 47502.125, u'b': 1580.5625, u'c': 45.3, u'd': 2.3, u'e': 0.45},
{u'b': 121, u'a': 1580.5625, u'c': 12, u'e': 62, u'd': 0.343},
{u'e': 12321, u'b': 4, u'd': 5434, u'c': 2.3, u'a': 0.1112}
]
# transform to data frame
df = pd.DataFrame(i)
print df
            a          b     c         d         e
0  47502.1250  1580.5625  45.3     2.300      0.45
1   1580.5625   121.0000  12.0     0.343     62.00
2      0.1112     4.0000   2.3  5434.000  12321.00

# create a mapping between columns and encoders
mapping = dict((k, v) for k, v in enumerate(df.columns))

# rename columns
df.columns = range(len(df.columns))

# print your new input data
print df.to_dict(orient='records)
[{0: 47502.125, 1: 1580.5625, 2: 45.3, 3: 2.3, 4: 0.45},
 {0: 1580.5625, 1: 121.0, 2: 12.0, 3: 0.343, 4: 62.0},
 {0: 0.1112, 1: 4.0, 2: 2.3, 3: 5434.0, 4: 12321.0}]

# translate prediction
prediction = [3, 4, 1]
print [mapping[k] for k in prediction]
[u'd', u'e', u'b']

这不是直截了当的,但我想它会比使用编码器花费更少的时间:)

虽然使用已经实现的功能是一个很好的实践,但是您可以通过几行代码轻松地实现这一点。根据您的列表输入:

dico = [
{u'a': 47502.125, u'b': 1580.5625, u'c': 45.3, u'd': 2.3, u'e': 0.45},
{u'b': 121, u'a': 1580.5625, u'c': 12, u'e': 62, u'd': 0.343},
{u'e': 12321, u'b': 4, u'd': 5434, u'c': 2.3, u'a': 0.1112}
]

您可以通过以下方法获得标签集:

^{pr2}$

使用mappinginv_mapping可以通过以下方式更改数据的表示:

for inner_dict in dico:
    for key in inner_dict.keys():
        inner_dict[mapping[key]] = inner_dict.pop(key)
print dico

这将给您[{1: 47502.125, ...}],然后如果需要:

for inner_dict in dico:
    for key in inner_dict.keys():
        inner_dict[inv_mapping[key]] = inner_dict.pop(key)
print dico

以获得初始版本。在

另外,可能与您的问题更密切相关,您可以通过以下方式轻松转换输出[5, 4, 1]

print [inv_mapping[i] for i in x]

相关问题 更多 >