从分类器输出中提取字典值

问题描述

我正在尝试零镜头分类。我得到如下输出

[{'labels': ['rep_appreciation','cx_service_appreciation','issue_resolved','recommend_product','callback_realted','billing_payment_related','disppointed_product'],'scores': [0.9198898673057556,0.8672246932983398,0.79215407371521,0.6239275336265564,0.4782547056674957,0.39024001359939575,0.010263209231197834],'sequence': 'Alan Edwards provided me with nothing less the excellent assistance'}

在数据帧中,以上输出为一行

我希望最终构建一个数据帧列,并按以下方式映射输出值。如果分数高于特定阈值,则标签为1

output sample

任何帮助解决此问题的微调/帮助。

解决方法

定义一个函数,该函数将为每行返回一个key:value字典,其中key为标签,基于阈值的value为1/0

def get_label_score_dict(row,threshold):
    result_dict = dict()
    for _label,_score in zip(row['labels'],row['scores']):
        if _score > threshold:
            result_dict.update({_label: 1})
        else:
            result_dict.update({_label: 0})
    return result_dict

现在,如果您有一个 list_of_rows ,并且每一行都具有上述形式,那么您可以使用 map 函数为每行获取上述字典。一旦获得,将其转换为DataFrame。

th = 0.5    #whatever threshold value you want
result = list(map(lambda x: get_label_score_dict(x,th),list_of_rows))
result_df = pd.DataFrame(result)