Antrenarea și testarea modelului Transformer
Cu modelul TransformerEncoder pregătit, următorul pas la PyBooks este să antrenezi modelul pe recenzii exemplu și să îi evaluezi performanța. Antrenarea pe aceste recenzii va ajuta PyBooks să înțeleagă tendințele de sentiment din vasta lor colecție. Odată ce modelul funcționează bine, PyBooks poate automatiza analiza sentimentelor, oferind cititorilor recomandări și feedback relevante.
Următoarele pachete au fost importate pentru tine: torch, nn, optim.
Instanța model a clasei TransformerEncoder, token_embeddings, precum și train_sentences, train_labels, test_sentences și test_labels sunt preîncărcate pentru tine.
Acest exercițiu face parte din cursul
Deep Learning pentru text cu PyTorch
Instrucțiuni pentru exercițiu
- În bucla de antrenare, împarte propozițiile în tokenuri și stivuiește încorporările.
- Resetează gradienții la zero și efectuează o trecere înapoi (backward pass).
- În funcția
predict, dezactivează calculul gradienților, apoi obține predicția de sentiment.
Exercițiu interactiv practic
Încearcă acest exercițiu completând acest cod de exemplu.
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)}")