शुरू करेंमुफ़्त में शुरू करें

Transformer मॉडल का प्रशिक्षण और परीक्षण

TransformerEncoder मॉडल तैयार होने के बाद, PyBooks में अगला कदम है मॉडल को sample reviews पर train करना और उसके प्रदर्शन का मूल्यांकन करना. इन sample reviews पर प्रशिक्षण से PyBooks को अपने विशाल भंडार में मौजूद sentiments के रुझानों को समझने में मदद मिलेगी. जब मॉडल अच्छा प्रदर्शन करेगा, तो PyBooks sentiment analysis को automate कर सकेगा, ताकि पाठकों को उपयोगी सिफारिशें और फीडबैक मिलें.

आपके लिए ये पैकेज import किए गए हैं: torch, nn, optim.

TransformerEncoder क्लास का model इंस्टेंस, token_embeddings, और train_sentences, train_labels, test_sentences, test_labels पहले से लोड हैं.

यह अभ्यास पाठ्यक्रम का हिस्सा है

PyTorch के साथ टेक्स्ट के लिए डीप लर्निंग

पाठ्यक्रम देखें

अभ्यास निर्देश

  • training loop में, वाक्यों को tokens में split करें और embeddings को stack करें.
  • gradients को zero करें और backward pass चलाएँ.
  • predict फंक्शन में, पहले gradient computations निष्क्रिय करें, फिर sentiment prediction प्राप्त करें.

इंटरैक्टिव व्यावहारिक अभ्यास

इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।

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)}")
कोड संपादित करें और चलाएँ