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

Attention के साथ RNN मॉडल बनाना

PyBooks में, टीम अलग-अलग डीप लर्निंग आर्किटेक्चर तलाश रही है. कुछ रिसर्च के बाद, आप अगला शब्द भविष्यवाणी करने के लिए Attention मेकैनिज्म वाला RNN इम्प्लीमेंट करने का निर्णय लेते हैं. आपको वाक्यों वाला एक डेटासेट और उनसे बना एक vocabulary दिया गया है.

निम्नलिखित पैकेज आपके लिए इम्पोर्ट कर दिए गए हैं: torch, nn.

निम्नलिखित आपके लिए प्रीलोड किए गए हैं:

  • vocab और vocab_size: vocabulary सेट और उसका आकार
  • word_to_ix और ix_to_word: word-to-index और index-to-word की dictionary मैपिंग्स
  • input_data और target_data: इनपुट-आउटपुट पेयर्स में बदला हुआ डेटासेट
  • embedding_dim और hidden_dim: एम्बेडिंग और RNN hidden state के dimensions

उदाहरण वाक्यों को देखने के लिए आप कंसोल में data वैरिएबल inspect कर सकते हैं.

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

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

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

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

  • दिए गए embedding_dim के साथ vocabulary के लिए एक एम्बेडिंग लेयर बनाएँ.
  • Attention scores पाने के लिए RNN sequence output पर एक linear ट्रांसफॉर्मेशन लागू करें.
  • Score से attention weights प्राप्त करें.
  • Context vector को RNN outputs और attention weights के weighted sum के रूप में compute करें.

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

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

class RNNWithAttentionModel(nn.Module):
    def __init__(self):
        super(RNNWithAttentionModel, self).__init__()
        # Create an embedding layer for the vocabulary
        self.embeddings = nn.____(vocab_size, embedding_dim)
        self.rnn = nn.RNN(embedding_dim, hidden_dim, batch_first=True)
        # Apply a linear transformation to get the attention scores
        self.attention = nn.____(____, 1)
        self.fc = nn.____(hidden_dim, vocab_size)
    def forward(self, x):
        x = self.embeddings(x)
        out, _ = self.rnn(x)
        #  Get the attention weights
        attn_weights = torch.nn.functional.____(self.____(out).____(2), dim=1)
        # Compute the context vector 
        context = torch.sum(____.____(2) * out, dim=1)
        out = self.fc(context)
        return out
      
attention_model = RNNWithAttentionModel()
optimizer = torch.optim.Adam(attention_model.parameters(), lr=0.01)
criterion = nn.CrossEntropyLoss()
print("Model Instantiated")
कोड संपादित करें और चलाएँ