感情分析のためのHugging Faceパイプライン

Pythonで学ぶ自然言語処理(NLP)

Fouad Trad

Machine Learning Engineer

復習:NLPワークフロー

ワークフロー全体の図。第1章は前処理、第2章は特徴抽出を扱ったことを示す。

Pythonで学ぶ自然言語処理(NLP)

Hugging Faceのパイプライン

ワークフロー全体の図。第3・4章では、前処理・特徴抽出・モデリングをまとめるHugging Faceパイプラインを扱うことを示す。

  • すべての工程を1回の関数呼び出しで処理する既製ワークフロー
  • パイプライン定義に必要なもの:
    • NLPタスク
    • そのタスク用のモデル
Pythonで学ぶ自然言語処理(NLP)

感情分析のパイプライン

 

 

  • テキスト分類タスク
  • テキストがポジティブかネガティブかを判定

ポジティブは笑顔とサムズアップ、ネガティブは悲しい顔とサムズダウンの図。

Pythonで学ぶ自然言語処理(NLP)

テキスト分類向けモデル

ウェブサイトでタスクを選び、適切なモデルを探す手順を示すGIF。

1 https://huggingface.co/models
Pythonで学ぶ自然言語処理(NLP)

コードでのパイプライン

from transformers import pipeline

classification_pipeline = pipeline(
task="sentiment-analysis", # or text-classification
model="distilbert/distilbert-base-uncased-finetuned-sst-2-english" )
result = classification_pipeline("I really liked the movie!!")
print(result)
[{'label': 'POSITIVE', 'score': 0.9998093247413635}]
Pythonで学ぶ自然言語処理(NLP)

テキスト一括の感情分析

texts = ["I really liked the movie!!",
         "Great job ruining my day.",
         "This product exceeded my expectations.",
         "Wow, just what I needed... another problem.", 
         "Absolutely fantastic experience!"]

results = classification_pipeline(texts)
print(results)
[{'label': 'POSITIVE', 'score': 0.9998093247413635}, 
 {'label': 'NEGATIVE', 'score': 0.8666700124740601}, 
 {'label': 'POSITIVE', 'score': 0.998874843120575}, 
 {'label': 'POSITIVE', 'score': 0.98626708984375}, 
 {'label': 'POSITIVE', 'score': 0.9998812675476074}]
Pythonで学ぶ自然言語処理(NLP)

感情分析モデルの評価

texts = ["I really liked the movie!!",
         "Great job ruining my day.",
         "This product exceeded my expectations.",
         "Wow, just what I needed... another problem.", 
         "Absolutely fantastic experience!"]

true_labels = ["POSITIVE", "NEGATIVE", "POSITIVE", "NEGATIVE", "POSITIVE"]
results = classification_pipeline(texts)
predicted_labels = [result['label'] for result in results]
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(true_labels, predicted_labels)

print(f"Accuracy: {accuracy}")
Accuracy: 0.80
Pythonで学ぶ自然言語処理(NLP)

Ayo berlatih!

Pythonで学ぶ自然言語処理(NLP)

Preparing Video For Download...