微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何显示来自文本分类的其他情绪分数?

如何解决如何显示来自文本分类的其他情绪分数?

我正在做情绪分析,我想知道如何通过对我的句子进行分类显示其他情绪分数:“特斯拉的股票刚刚上涨了 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。