我刚开始编写python代码,其中一个函数将返回一个numpy.ndarray,其中6个值如下所示
[1 0 1 0 1 1]
这些实际上是对多类分类模型的预测,如果匹配These 0,则值为1。
我想给这六个预测一些意义,为此我创建了一本字典如下:
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.提前谢谢。
发布于 2020-05-15 15:20:42
以下是实现上述结果的简单理解:
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开始)和值的元组列表。
希望这能帮上忙!
发布于 2020-05-15 15:25:54
这里是一个示例代码,您如何做到这一点:
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'发布于 2020-05-15 15:30:26
你不需要一个白痴,你可以简单地用拉链把你的预测和你的毒物联系起来。然后,您只需使用一个列表理解得到的是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,5https://stackoverflow.com/questions/61822447
复制相似问题