I am struggling with understanding how to get hidden layers and concatenate them.
I am using the following code as an example:
class classifier(nn.Module):
#define all the layers used in model
def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers, 
             bidirectional, dropout):
    #Constructor
    super().__init__()
    self.batch = BATCH_SIZE
    self.hidden = hidden_dim
    self.layers = n_layers
    if(bidirectional):
        self.directions = 2
    else:
        self.directions = 1
    #embedding layer
    self.embedding = nn.Embedding(vocab_size, embedding_dim)
    #lstm layer
    self.gru = nn.GRU(embedding_dim, 
                       hidden_dim, 
                       num_layers=n_layers, 
                       bidirectional=bidirectional, 
                       dropout=dropout,
                       batch_first=True)
    #dense layer
    self.fc = nn.Linear(hidden_dim * 2, output_dim)
    #activation function
    self.act = nn.Sigmoid()
def forward(self, text, text_lengths):
    #text = [batch size,sent_length]
    embedded = self.embedding(text)
    #embedded = [batch size, sent_len, emb dim]
    #packed sequence
    packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, text_lengths,batch_first=True)
    packed_output, (hidden, cell) = self.lstm(packed_embedded)
    #hidden = [batch size, num layers * num directions,hid dim]
    #cell = [batch size, num layers * num directions,hid dim]
    #concat the final forward and backward hidden state
    hidden = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1)
    #hidden = [batch size, hid dim * num directions]
    dense_outputs=self.fc(hidden)
    #Final activation function
    outputs=self.act(dense_outputs)
    return outputs
The line hidden = torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1) I did not get it.
As per my understanding, I was doing this which did not work.
hidden2 = hidden.view(batch_size,self.layers,self.directions,self.hidden)  
hidden2 = torch.cat((hidden2[:,:,0,:],hidden2[:,:,1,:]),dim=1)
dense_outputs=self.fc(hidden2)
Can somebody please explain. I went through PyTorch documentation but did not get.