開始使用免費開始

為文字訓練一個 CNN 模型

做得好,已經定義了 TextClassificationCNN 類別。接下來 PyBooks 需要訓練模型,讓它能更準確地做書評的情感分析。

以下套件已為你匯入: torchtorch.nn 作為 nntorch.nn.functional 作為 Ftorch.optim 作為 optim

一個以 vocab_sizeembed_dim 作為引數建立的 TextClassificationCNN() 實例也已載入並儲存為 model

本練習屬於課程

Deep Learning for Text with PyTorch

檢視課程

練習說明

  • 定義用於二元分類的損失函式,並儲存為 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!')
編輯並執行程式碼