始める無料で始める

テキスト用のCNNモデルを学習する

TextClassificationCNN クラスの定義はお見事です。次は PyBooks でモデルを学習し、書評の感情分析を高精度に行えるよう最適化していきます。

次のパッケージはすでにインポートされています: torchtorch.nnnntorch.nn.functionalFtorch.optimoptim

vocab_sizeembed_dim を引数にした TextClassificationCNN() のインスタンスも読み込み済みで、model として保存されています。

この演習はコースの一部です

PyTorch で学ぶテキストの Deep Learning

コースを見る

演習の手順

  • 二値分類に用いる損失関数を定義し、criterion として保存します。
  • 学習ループの開始時に勾配をゼロにリセットします。
  • ループの最後でパラメータを更新します。

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

# Define the loss function
criterion = nn.____()
optimizer = optim.SGD(model.parameters(), lr=0.1)

for epoch in range(10):
    for sentence, label in data:     
        # Clear the gradients
        model.____()
        sentence = torch.LongTensor([word_to_ix.get(w, 0) for w in sentence]).unsqueeze(0) 
        label = torch.LongTensor([int(label)])
        outputs = model(sentence)
        loss = criterion(outputs, label)
        loss.backward()
        # Update the parameters
        ____.____()
print('Training complete!')
コードを編集して実行