如何根据python 3中函数返回的数组检索字典键值对

2024-09-27 07:29:22 发布

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

我不熟悉python编码,其中一个函数返回一个numpy.ndarray,其中包含如下六个值

[1 0 1 0 1 1]

这些实际上是多类分类模型的预测,如果匹配,则值为1,否则为0

我希望给这六个预测一些含义,为此我创建了一本字典,如下所示:

toxics = {1:'Toxic', 2:'Severely Toxic', 3:'Obscene', 4:'Threat', 5:'Insult', 6:'Identity Hate'}

如何将我的个人预测映射/链接到字典,并为用户显示/打印一些消息。例如,在上述数据中:

"The text is Toxic, Obscene, Insult, Identity Hate" as I have a prediction of '1' at 0,2,4,5 position in the array.

提前谢谢


Tags: 函数模型numpy编码字典分类identityndarray
3条回答

以下是实现上述结果的简单理解:

arr = [1, 0, 1, 0, 1, 1]
toxic_str = ",".join([toxics[i] for i, val in enumerate(arr, 1) if val == 1])
print("This text is", toxic_str)

枚举(arr,1)将返回具有索引(从1开始)和值的元组列表

希望这有帮助

下面是一个示例代码,说明如何执行此操作:

import numpy as np
results =np.array([1,0,1,0, 1, 1])
toxics = {1:'Toxic', 2:'Severely Toxic', 3:'Obscene', 4:'Threat', 5:'Insult', 6:'Identity Hate'}
strings =[toxics[k] for k in (np.argwhere(results==1)+1).reshape(-1) if k in toxics]
'The text is ' + ', '.join(strings)+' as I have a prediction of 1 at ' + ', '.join(np.char.mod('%d',(np.argwhere(results==1)).reshape(-1)))

输出:

'The text is Toxic, Obscene, Insult, Identity Hate as I have a prediction of 1 at 0, 2, 4, 5'

你不需要口述,你可以简单地用zip把你的预测和你的毒物联系起来。然后,您可以使用列表理解来获得1。您可以使用np.where来获取索引值

from numpy import array, where

preds = array([1, 0, 1, 0, 1, 1])
toxics = ["Toxic", "Severely Toxic", "Obscene", "Threat", "Inuslt", "Identity Hate"]
results = [toxic for pred, toxic in zip(preds, toxics) if pred == 1]
indexs = where(preds == 1)

print("'The text is", ", ".join(results) + "' as i have a prediction of '1' at",  ",".join([str(i) for i in indexs[0]]))

输出

'The text is Toxic, Obscene, Inuslt, Identity Hate' as i have a prediction of '1' at 0,2,4,5

相关问题 更多 >

    热门问题