プリンキピア

第16章自然言語処理:応用

16.2.3. Training and Evaluating the Model16.2.3 モデルを訓練し評価する

Now we can train the bidirectional RNN for sentiment analysis.
英語のヒント
これで、感情分析のために双方向RNNを訓練できる。
lr, num_epochs = 0.01, 5
trainer = torch.optim.Adam(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss(reduction="none")
d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs, devices)
loss 0.277, train acc 0.884, test acc 0.861
2608.4 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]
We define the following function to predict the sentiment of a text sequence using the trained model net.
英語のヒント
訓練したモデルnetを使ってテキストの系列の感情を予測する、次の関数を定義する。
#@save
def predict_sentiment(net, vocab, sequence):
    """Predict the sentiment of a text sequence."""
    sequence = torch.tensor(vocab[sequence.split()], device=d2l.try_gpu())
    label = torch.argmax(net(sequence.reshape(1, -1)), dim=1)
    return 'positive' if label == 1 else 'negative'
Finally, let’s use the trained model to predict the sentiment for two simple sentences.
英語のヒント
最後に、訓練したモデルを使って、二つの簡単な文の感情を予測しよう。
predict_sentiment(net, vocab, 'this movie is so great')
'positive'
predict_sentiment(net, vocab, 'this movie is so bad')
'negative'