自作のLLMを使用した感情分析ツールの構築
はじめに
感情分析は、テキストの感情的なトーンを決定するプロセスであり、マーケティング、顧客サポート、世論調査など多くの分野で応用されます。この記事では、大規模言語モデル(LLM)を利用した自作の感情分析ツールの構築方法を紹介します。
モデルの選択
最初のステップは適切な言語モデルの選択です。選択肢は以下の通りです:
- 事前学習済みモデル(例:BERT、RoBERTa、DistilBERT) - 使用準備が整っているが、調整が必要です。
- 専門モデル(例:VADER、TextBlob) - 感情分析に特化して設計されています。
- 独自モデル - 独自のドメインに特化したデータで学習されます。
この例では、Hugging Face TransformersとDistilBERTモデルを使用します。DistilBERTはBERTの軽量版で、感情分析タスクに適しています。
必要なライブラリのインストール
始める前に、必要なライブラリをインストールします:
pip install transformers torch pandas
モデルとトークナイザーの読み込み
次に、モデルとトークナイザーを読み込みます:
from transformers import pipeline
# 感情分析ツールの読み込み
sentiment_pipeline = pipeline("sentiment-analysis")
データの準備
テスト用のデータセットを準備します。簡単な例を使用します:
texts = [
"この製品が大好きです、素晴らしいです!",
"お勧めしません、非常にがっかりしました。",
"平均的な製品、特に何もありません。",
"効果は満足ですが、価格が高すぎます。"
]
感情分析
これで、テキストに対する感情分析を実行できます:
results = sentiment_pipeline(texts)
for text, result in zip(texts, results):
print(f"テキスト: {text}")
print(f"感情: {result['label']} (確信度: {result['score']:.2f})")
print("---")
モデルの調整
独自のデータにモデルを調整したい場合は、Hugging Face Transformersライブラリを使用してモデルを独自のデータセットで学習できます。
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from transformers import Trainer, TrainingArguments
import pandas as pd
from sklearn.model_selection import train_test_split
# 例のデータセット
data = pd.DataFrame({
"text": ["この製品が大好きです", "お勧めしません", "平均的な製品"],
"label": [1, 0, 0] # 1 - ポジティブ、0 - ネガティブ
})
# データをトレーニングセットとテストセットに分割
train_texts, test_texts, train_labels, test_labels = train_test_split(
data["text"], data["label"], test_size=0.2
)
# トークナイザーとモデルの読み込み
model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name, num_labels=2)
# データのトークナイゼーション
train_encodings = tokenizer(list(train_texts), truncation=True, padding=True)
test_encodings = tokenizer(list(test_texts), truncation=True, padding=True)
# データを扱うクラス
class SentimentDataset(torch.utils.data.Dataset):
def __init__(self, encodings, labels):
self.encodings = encodings
self.labels = labels
def __getitem__(self, idx):
item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()}
item["labels"] = torch.tensor(self.labels[idx])
return item
def __len__(self):
return len(self.labels)
train_dataset = SentimentDataset(train_encodings, train_labels)
test_dataset = SentimentDataset(test_encodings, test_labels)
# トレーニングの設定
training_args = TrainingArguments(
output_dir="./results",
num_train_epochs=3,
per_device_train_batch_size=16,
per_device_eval_batch_size=64,
warmup_steps=500,
weight_decay=0.01,
logging_dir="./logs",
logging_steps=10,
)
# モデルのトレーニング
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
eval_dataset=test_dataset
)
trainer.train()
モデルのデプロイ
モデルを学習した後、保存して感情分析に使用できます:
model.save_pretrained("./custom_sentiment_model")
tokenizer.save_pretrained("./custom_sentiment_model")
# 調整済みモデルの読み込み
custom_model = AutoModelForSequenceClassification.from_pretrained("./custom_sentiment_model")
custom_tokenizer = AutoTokenizer.from_pretrained("./custom_sentiment_model")
# 例の分析
custom_pipeline = pipeline("sentiment-analysis", model=custom_model, tokenizer=custom_tokenizer)
print(custom_pipeline("この製品は素晴らしいです!"))
まとめ
この記事では、大規模言語モデルを利用した自作の感情分析ツールの構築方法を紹介しました。モデルの選択、データの準備、感情分析、モデルの調整についてステップバイステップで説明しました。このツールを使用すれば、さまざまな分野でテキストの感情的なトーンを効果的に分析できます。