-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathehr_models.py
More file actions
46 lines (42 loc) · 1.71 KB
/
Copy pathehr_models.py
File metadata and controls
46 lines (42 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import torch
import torch.nn as nn
import torch.nn.functional as F
class LSTM(nn.Module):
def __init__(self, input_dim=76, num_classes=1, hidden_dim=128, batch_first=True, dropout=0.0, layers=1):
super(LSTM, self).__init__()
self.hidden_dim = hidden_dim
self.layers = layers
for layer in range(layers):
setattr(self, f'layer{layer}', nn.LSTM(
input_dim, hidden_dim,
batch_first=batch_first,
dropout = dropout)
)
input_dim = hidden_dim
self.do = None
if dropout > 0.0:
self.do = nn.Dropout(dropout)
self.feats_dim = hidden_dim
self.dense_layer = nn.Linear(hidden_dim, num_classes)
self.initialize_weights()
# self.activation = torch.sigmoid
def initialize_weights(self):
for model in self.modules():
if type(model) in [nn.Linear]:
nn.init.xavier_uniform_(model.weight)
nn.init.zeros_(model.bias)
elif type(model) in [nn.LSTM, nn.RNN, nn.GRU]:
nn.init.orthogonal_(model.weight_hh_l0)
nn.init.xavier_uniform_(model.weight_ih_l0)
nn.init.zeros_(model.bias_hh_l0)
nn.init.zeros_(model.bias_ih_l0)
def forward(self, x, seq_lengths):
x = torch.nn.utils.rnn.pack_padded_sequence(x, seq_lengths, batch_first=True, enforce_sorted=False)
for layer in range(self.layers):
x, (ht, _) = getattr(self, f'layer{layer}')(x)
feats = ht.squeeze()
if self.do is not None:
feats = self.do(feats)
out = self.dense_layer(feats)
scores = torch.sigmoid(out)
return scores, feats