Attention के साथ RNN मॉडल का ट्रेनिंग और टेस्टिंग
PyBooks में, टीम ने पहले attention मैकेनिज़्म के बिना word prediction के लिए एक RNN मॉडल बनाया था. इस शुरुआती मॉडल को rnn_model कहा जाता है. इसे पहले ही ट्रेन किया जा चुका है और इसका इंस्टेंस प्रीलोडेड है. अब आपका काम नए RNNWithAttentionModel को ट्रेन करना और उसकी भविष्यवाणियों की तुलना पहले वाले rnn_model से करना है.
आपके लिए निम्नलिखित प्रीलोडेड हैं:
inputs: इनपुट सीक्वेंसेज़ की सूची, टेन्सर्स के रूप मेंtargets: हर इनपुट सीक्वेंस के लिए target शब्दों वाला टेन्सरoptimizer: Adam optimizer फंक्शनcriterion: CrossEntropyLoss फंक्शनpad_sequences: बैचिंग के लिए इनपुट सीक्वेंसेज़ को pad करने वाला फंक्शनattention_model: पिछले अभ्यास में परिभाषित मॉडल क्लासrnn_model: PyBooks की टीम द्वारा ट्रेन किया गया RNN मॉडल
यह अभ्यास पाठ्यक्रम का हिस्सा है
PyTorch के साथ टेक्स्ट के लिए डीप लर्निंग
अभ्यास निर्देश
- टेस्ट डेटा के साथ जाँचने से पहले RNN मॉडल को evaluation मोड में सेट करें.
- उपयुक्त इनपुट को RNN मॉडल में पास करके RNN आउटपुट प्राप्त करें.
- RNN आउटपुट से सबसे उच्च prediction स्कोर वाले शब्द को निकालें.
- इसी तरह, attention मॉडल के लिए, attention आउटपुट से सबसे उच्च prediction स्कोर वाला शब्द निकालें.
इंटरैक्टिव व्यावहारिक अभ्यास
इस अभ्यास को इस नमूना कोड को पूरा करके आज़माएँ।
for epoch in range(epochs):
attention_model.train()
optimizer.zero_grad()
padded_inputs = pad_sequences(inputs)
outputs = attention_model(padded_inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
for input_seq, target in zip(input_data, target_data):
input_test = torch.tensor(input_seq, dtype=torch.long).unsqueeze(0)
# Set the RNN model to evaluation mode
rnn_model.____()
# Get the RNN output by passing the appropriate input
rnn_output = ____(____)
# Extract the word with the highest prediction score
rnn_prediction = ix_to_word[torch.____(____).item()]
attention_model.eval()
attention_output = attention_model(input_test)
# Extract the word with the highest prediction score
attention_prediction = ix_to_word[torch.____(____).item()]
print(f"\nInput: {' '.join([ix_to_word[ix] for ix in input_seq])}")
print(f"Target: {ix_to_word[target]}")
print(f"RNN prediction: {rnn_prediction}")
print(f"RNN with Attention prediction: {attention_prediction}")