テキスト分類の畳み込みニューラルネットワーク(CNN)

PyTorch で学ぶテキストの Deep Learning

Shubham Jain

Instructor

テキスト分類のためのCNN

  • ツイートを分類
    • ポジティブ
    • ネガティブ
    • ニュートラル
PyTorch で学ぶテキストの Deep Learning

畳み込み演算

畳み込み演算

  • 畳み込み演算
    • 入力上をフィルタ(カーネル)がスライド
    • 各位置で要素ごとの計算を実行

 

  • テキストでは:単語の構造と意味を学習
1 Animation from Vincent Dumoulin, Francesco Visin
PyTorch で学ぶテキストの Deep Learning

CNNにおけるフィルタとストライド

  • フィルタ:
    • 入力上をスライドする小さな行列

 

  • ストライド:
    • フィルタが動くステップ数

フィルタとストライド

1 Animation from Vincent Dumoulin, Francesco Visin
PyTorch で学ぶテキストの Deep Learning

テキスト向けCNNの構成

  • 畳み込み層:入力にフィルタを適用
  • プーリング層:重要情報を保ちつつサイズ削減
  • 全結合層:前段の出力から最終予測
PyTorch で学ぶテキストの Deep Learning

CNNでテキスト分類モデルを実装

class SentimentAnalysisCNN(nn.Module):

def __init__(self, vocab_size, embed_dim):
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.conv = nn.Conv1d(embed_dim, embed_dim, kernel_size=3, stride=1, padding=1)
self.fc = nn.Linear(embed_dim, 2) ...
  • __init__ はアーキテクチャを設定
  • super() で基底クラス nn.Module を初期化
  • nn.Embedding は単語を密ベクトル化
  • nn.Conv1d は1次元データ用
PyTorch で学ぶテキストの Deep Learning

CNNでテキスト分類モデルを実装

    ...
    def forward(self, text):
        embedded = self.embedding(text).permute(0, 2, 1)

conved = F.relu(self.conv(embedded))
conved = conved.mean(dim=2)
return self.fc(conved)
  • 埋め込み層でテキストを埋め込みへ
  • 畳み込みの想定入力にテンソルを整形
  • ReLUで重要特徴を抽出
  • 余分な次元を削減
PyTorch で学ぶテキストの Deep Learning

感情分析モデルのデータ準備

vocab = ["i", "love", "this", "book", "do", "not", "like"]
word_to_idx = {word: i for i, word in enumerate(vocab)}

vocab_size = len(word_to_ix)
embed_dim = 10
book_samples = [ ("The story was captivating and kept me hooked until the end.".split(),1), ("I found the characters shallow and the plot predictable.".split(),0) ]
model = SentimentAnalysisCNN(vocab_size, embed_dim) criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(model.parameters(), lr=0.1)
PyTorch で学ぶテキストの Deep Learning

モデルの学習

for epoch in range(10):  
    for sentence, label in data:

model.zero_grad()
sentence = torch.LongTensor([word_to_idx.get(w, 0) for w in sentence]).unsqueeze(0)
outputs = model(sentence) label = torch.LongTensor([int(label)])
loss = criterion(outputs, label) loss.backward()
optimizer.step()
PyTorch で学ぶテキストの Deep Learning

感情分析モデルの実行

for sample in book_samples:

input_tensor = torch.tensor([word_to_idx[w] for w in sample], dtype=torch.long).unsqueeze(0)
outputs = model(input_tensor)
_, predicted_label = torch.max(outputs.data, 1)
sentiment = "Positive" if predicted_label.item() == 1 else "Negative"
print(f"Book Review: {' '.join(sample)}") print(f"Sentiment: {sentiment}\n")
Book Review: The story was captivating and kept me hooked until the end
Sentiment: Positive
Book Review: I found the characters shallow and the plot predictable
Sentiment: Negative
PyTorch で学ぶテキストの Deep Learning

Let's practice!

PyTorch で学ぶテキストの Deep Learning

Preparing Video For Download...