テキストの感情分析

SiEBERT - English-Language Sentiment Classification』のモデルを使って英文の感情分類をします。英文の各文章の感情をポジティブ・ネガティブで分類してみたいと思います。

Hartmann, Jochen and Heitmann, Mark and Siebert, Christian and Schamp, Christina, “More than a feeling: Accuracy and Application of Sentiment Analysis”, International Journal of Research in Marketing(2022)

ここではhuggingface上のsiebert/sentiment-roberta-large-englishのモデルを使用しています。Google Colab上でtransformersを使用する場合は事前にtransformersをインストールする必要があります。

import numpy as np
from transformers import pipeline
from IPython.display import HTML

sentiment_pipeline = pipeline(
    "sentiment-analysis", model="siebert/sentiment-roberta-large-english"
)

テキストの各文の感情を分析してみる

テキスト全体を「.」で区切ることで、一文ごとに分けています。

ここではPetrobras Webcast – 3rd Quarter Results 2022 November 5, 2022の文字起こしデータを使用しています。

transcript = """Hello!Hello!Hello!Hello!Hello!"""
ts_list = [ts for ts in transcript.split(".") if len(ts) > 20]
scores = sentiment_pipeline(ts_list)

結果を可視化

ポジティブ・ネガティブのラベルと、そのスコアを用いて結果を可視化してみます。

for t, s in zip(ts_list, scores):
    score = np.round(float(s["score"]), 4)  # 感情スコア
    font_weight = "bold" if score > 0.995 else "normal"  # 表示する文字の太さ

    # 感情ごとに色を分けて表示
    if s["label"] == "NEGATIVE":
        r = 255 - 10 * int(1000 - score * 1000)
        display(
            HTML(
                f"[score={score}] <span style='color:rgb({r},100,100);font-weight:{font_weight};'>{t}</span>"
            )
        )
    elif s["label"] == "POSITIVE":
        g = 255 - 10 * int(1000 - score * 1000)
        display(
            HTML(
                f"[score={score}] <span style='color:rgb(100,{g},100);font-weight:{font_weight};'>{t}</span>"
            )
        )

[score=0.9976] Hello!Hello!Hello!Hello!Hello!

コメント欄

※コメントは承認後に表示されます。個人情報は入力しないようにお願いします。