Last active
March 23, 2021 19:57
-
-
Save bkaankuguoglu/c668c4c1490baa3ba8db006203d2f65c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class LSTMModel(nn.Module): | |
| def __init__(self, input_dim, hidden_dim, layer_dim, output_dim, dropout_prob): | |
| super(LSTMModel, self).__init__() | |
| # Defining the number of layers and the nodes in each layer | |
| self.hidden_dim = hidden_dim | |
| self.layer_dim = layer_dim | |
| # LSTM layers | |
| self.lstm = nn.LSTM( | |
| input_dim, hidden_dim, layer_dim, batch_first=True, dropout=dropout_prob | |
| ) | |
| # Fully connected layer | |
| self.fc = nn.Linear(hidden_dim, output_dim) | |
| def forward(self, x): | |
| # Initializing hidden state for first input with zeros | |
| h0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_() | |
| # Initializing cell state for first input with zeros | |
| c0 = torch.zeros(self.layer_dim, x.size(0), self.hidden_dim).requires_grad_() | |
| # We need to detach as we are doing truncated backpropagation through time (BPTT) | |
| # If we don't, we'll backprop all the way to the start even after going through another batch | |
| # Forward propagation by passing in the input, hidden state, and cell state into the model | |
| out, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach())) | |
| # Reshaping the outputs in the shape of (batch_size, seq_length, hidden_size) | |
| # so that it can fit into the fully connected layer | |
| out = out[:, -1, :] | |
| # Convert the final state to our desired output shape (batch_size, output_dim) | |
| out = self.fc(out) | |
| return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment