始める無料で始める

Transformer モデルの学習とテスト

TransformerEncoder モデルの準備ができたら、次に PyBooks ではサンプルレビューでモデルを学習し、その性能を評価します。これらのサンプルレビューで学習することで、PyBooks は大規模なコーパスにおける感情の傾向を把握できます。十分に高性能なモデルが得られれば、PyBooks は感情分析を自動化でき、読者に有益なおすすめやフィードバックを提供しやすくなります。

次のパッケージはインポート済みです:torchnnoptim

TransformerEncoder クラスの model インスタンス、token_embeddings、そして train_sentencestrain_labelstest_sentencestest_labels はあらかじめ読み込まれています。

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

PyTorch で学ぶテキストの Deep Learning

コースを見る

演習の手順

  • 学習ループで、文をトークンに分割し、埋め込みをスタックします。
  • 勾配をゼロにリセットし、バックプロパゲーションを実行します。
  • predict 関数では、勾配計算を無効化してから感情の予測を取得します。

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

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

for epoch in range(5):  
    for sentence, label in zip(train_sentences, train_labels):
        # Split the sentences into tokens and stack the embeddings
        tokens = ____
        data = torch.____([token_embeddings[token] for token in ____], dim=1)
        output = model(data)
        loss = criterion(output, torch.tensor([label]))
        # Zero the gradients and perform a backward pass
        optimizer.____()
        loss.____()
        optimizer.step()
        print(f"Epoch {epoch}, Loss: {loss.item()}")

def predict(sentence):
    model.eval()
    # Deactivate the gradient computations and get the sentiment prediction.
    with torch.____():
        tokens = sentence.split()
        data = torch.stack([token_embeddings.get(token, torch.rand((1, 512))) for token in tokens], dim=1)
        output = model(data)
        predicted = torch.____(output, dim=1)
        return "Positive" if predicted.item() == 1 else "Negative"

sample_sentence = "This product can be better"
print(f"'{sample_sentence}' is {predict(sample_sentence)}")
コードを編集して実行