gpt4 book ai didi

python - 在字典上使用标签编码器

转载 作者:行者123 更新时间:2023-12-01 03:47:01 24 4
gpt4 key购买 nike

我正在使用sklearn LabelEncoder 。我知道如何将它用于一维数组,但我的用例是这样的:

我有多个这样的字典数组(这实际上是我在分类器中分配每个文本标签 u'a'u'b' 等的成本),全部在一个字典中:

{'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}
]
}

我需要能够将其编码为数字标签,然后将它们全部解码回来,例如:

[
{1: 47502.125, 3: 45.3, 4: 2.3, 5: 0.45},
{2: 121, 1: 1580.5625, 3: 12, 5: 62, 4: 0.343},
{5: 12321, 2: 4, 1: 0.1112}
]

我有效地使用它来生成每行最佳标签的预测,因此:

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

我需要做的是能够将其解码回:

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

如何获得相同的 LabelEncoder 功能,但要在字典键是我的标签的字典数组上实现 fit_transform

注意,字典数组中的字典长度不同,但我确实有所有潜在标签的列表,即对于 open_model 标签, set([u'a',u'b',u 'c',u'd',u'e']) 以及 close_model 标签:set([u'a',u'b',u'c']).

最佳答案

尽管使用已实现的功能是一个很好的做法,但您可以通过几行代码轻松实现这一点。鉴于您的列表输入:

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}
]

您可以通过简单地获取标签集:

keyset = set(dico[0].keys()) #Get the set of keys assuming they all appear in each list item. 
mapping = { val:key+1 for key,val in enumerate(list(keyset))} # Create a mapping from int -> str
inv_mapping = { key+1:val for key,val in enumerate(list(keyset))} # Create a mapping from str:int.

有了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]

关于python - 在字典上使用标签编码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38839211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com