シーケンス分類タスクの仕事は、テキスト シーケンスを、このタイプのタスクに属するニュース分類、センチメント分類などの事前設定タイプに分類することです。
感情の分類
以下はpipelines
感情分類に使用する例です。具体的なタスクは、入力テキストがネガティブかポジティブかを判断することです。
例:
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
result = classifier("I hate you")[0]
print(f"label: {
result['label']}, with score: {
round(result['score'], 4)}")
result = classifier("I love you")[0]
print(f"label: {
result['label']}, with score: {
round(result['score'], 4)}")
出力結果:
label: NEGATIVE, with score: 0.9991
label: POSITIVE, with score: 0.9999
- モデルはテキストのラベル、つまり
NEGATIVE
またはPOSITIVE
、およびそのラベルの評価スコアを返しますscore
。
文の言い換え
以下は文の言い換えの例です。主なタスクは、モデルを使用して 2 つのシーケンスが相互に説明できるかどうかを判断することです。プロセスは次のとおりです。
- テキスト トークナイザー (トークナイザー) と BERT モデル (モデル) をインスタンス化し、事前トレーニングされた重みを読み込みます。
- モデル固有の区切り文字、トークン タイプ ID、およびアテンション マスクを使用して 2 つの文のシーケンスを構築します。このステップは、テキスト トークナイザーを使用して自動的に生成できます。
- 作成したシーケンスをモデルに入力し、分類結果を取得します。結果は 2 つのクラスで構成されます: 0 (言い換えなしを意味する) と 1 (言い換え可能を意味する)。
- ソフトマックスを使用して、これを分類確率に変換します。
- 結果を印刷します。
例:
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased-finetuned-mrpc")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased-finetuned-mrpc")
classes = ["不能释义", "可以释义"]
sentence_0 = "I am a student coming from China."
sentence_1 = "I am a big pig."
sentence_2 = "I am a person who studies in the school"
paraphrase = tokenizer(sentence_0, sentence_2, return_tensors="pt")
not_paraphrase = tokenizer(sentence_0, sentence_1, return_tensors="pt")
paraphrase_classification = model(**paraphrase)
not_paraphrase_classification = model(**not_paraphrase)
p_result = torch.softmax(paraphrase_classification[0], dim=1)[0]
np_result = torch.softmax(not_paraphrase_classification[0], dim=1)[0]
print(sentence_0, "\n", sentence_2)
for i in range(len(classes)):
print("{}:{:.2f}%".format(classes[i], p_result[i].item() * 100))
print(sentence_0, "\n", sentence_1)
for i in range(len(classes)):
print("{}:{:.2f}%".format(classes[i], np_result[i].item() * 100))
出力結果:
I am a student coming from China.
I am a person who studies in the school
不能释义:23.34%
可以释义:76.66%
I am a student coming from China.
I am a big pig.
不能释义:92.51%
可以释义:7.49%