Vrk commited on
Commit
4f67b8b
1 Parent(s): 8758be0

PyTorch Model

Browse files
Files changed (1) hide show
  1. Model.py +57 -0
Model.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+ import numpy as np
6
+
7
+
8
+ def gather_last_relevant_hidden(hiddens, seq_lens):
9
+ """Extract and collect the last relevant
10
+ hidden state based on the sequence length."""
11
+ seq_lens = seq_lens.long().detach().cpu().numpy() - 1
12
+ out = []
13
+ for batch_index, column_index in enumerate(seq_lens):
14
+ out.append(hiddens[batch_index, column_index])
15
+ return torch.stack(out)
16
+
17
+
18
+ class SkimlitModel(nn.Module):
19
+ def __init__(self, embedding_dim, vocab_size, hidden_dim, n_layers, linear_output, num_classes, pretrained_embeddings=None, padding_idx=0):
20
+ super(SkimlitModel, self).__init__()
21
+
22
+ # Initalizing embeddings
23
+ if pretrained_embeddings is None:
24
+ self.embeddings = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim)
25
+ else:
26
+ pretrained_embeddings = torch.from_numpy(pretrained_embeddings).float()
27
+ self.embeddings = nn.Embedding(num_embeddings=vocab_size, embedding_dim=embedding_dim, _weight=pretrained_embeddings, padding_idx=padding_idx)
28
+
29
+ # LSTM layers
30
+ self.lstm1 = nn.LSTM(embedding_dim, hidden_dim, num_layers=n_layers, batch_first=True, bidirectional=True)
31
+
32
+ # FC layers
33
+ self.fc_text = nn.Linear(2*hidden_dim, linear_output)
34
+
35
+ self.fc_line_num = nn.Linear(20, 64)
36
+ self.fc_total_line = nn.Linear(24, 64)
37
+
38
+ self.fc_final = nn.Linear((64+64+linear_output), num_classes)
39
+ self.dropout = nn.Dropout(0.3)
40
+
41
+ def forward(self, inputs):
42
+ x_in, seq_lens, line_nums, total_lines = inputs
43
+ x_in = self.embeddings(x_in)
44
+
45
+ # RNN outputs
46
+ out, b_n = self.lstm1(x_in)
47
+ x_1 = gather_last_relevant_hidden(hiddens=out, seq_lens=seq_lens)
48
+
49
+ # FC layers output
50
+ x_1 = F.relu(self.fc_text(x_1))
51
+ x_2 = F.relu(self.fc_line_num(line_nums))
52
+ x_3 = F.relu(self.fc_total_line(total_lines))
53
+
54
+ x = torch.cat((x_1, x_2, x_3), dim=1)
55
+ x = self.dropout(x)
56
+ x = self.fc_final(x)
57
+ return x