如何显示文本分类中的其他情感得分



我正在进行情绪分析,我想知道如何显示对我的句子进行分类后的其他情绪得分:"特斯拉的股票刚刚上涨了20%">

我有三种情绪:积极消极中立

这是我的代码,其中包含我要分类的句子:

pip install happytransformer
from happytransformer import HappyTextClassification 
happy_tc = HappyTextClassification("BERT", "ProsusAI/finbert", num_labels=3)
result = happy_tc.classify_text("Tesla's stock just increased by 20%")

这是结果代码和输出:

print(result)
TextClassificationResult(label='positive', score=0.929110586643219)

这是情绪得分,它只显示积极的得分:

print(result.label)
print(result.score)
positive
0.92

现在,我如何使它显示消极、中立和积极的情绪得分?

看起来像这样的东西:

positive
0.92
negative
0.05
neutral
0.03

谢谢。

因为HappyTransformer不支持多类概率,我建议使用另一个库。flair库提供了更多的功能,可以为您提供所需的多类概率,如下所示:

from flair.models import TextClassifier
from flair.data import Sentence
tc = TextClassifier.load('en-sentiment')
sentence = Sentence('Flair is pretty neat!')
tc.predict(sentence, multi_class_prob=True)
print('Sentence above is: ', sentence.labels)

仅供pip install flair使用。

请注意,我们使用与BERT不同的模型,并且只返回两个标签,而不是三个。

另一种选择是使用HuggingFace库。它允许使用自定义标签。

from transformers import pipeline
classifier = pipeline("zero-shot-classification")
classifier(
"This is a course about the Transformers library",
candidate_labels=["education", "politics", "business"],
)
{'sequence': 'This is a course about the Transformers library',
'labels': ['education', 'business', 'politics'],
'scores': [0.8445963859558105, 0.111976258456707, 0.043427448719739914]}

在您的情况下,可以将标签切换为["positive", "negative", "neutral"]

示例来自:https://huggingface.co/course/chapter1/3?fw=pt

最新更新