-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetwork.py
More file actions
70 lines (53 loc) · 1.94 KB
/
Network.py
File metadata and controls
70 lines (53 loc) · 1.94 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import torch.nn as nn
class Network(nn.Module):
"""
The RNN LSTM model used for sentiment analysis
"""
def __init__(self, vocab_size, output_size, embedding_dim, hidden_dim, n_layers, drop_prob=0.5):
"""
Initialize the model and set up the layers
"""
super().__init__()
# hyperparameters
self.output_size = output_size
self.n_layers = n_layers
self.hidden_dim = hidden_dim
# embedding layer
self.embedding = nn.Embedding(vocab_size, embedding_dim)
# LSTM layers
self.lstm = nn.LSTM(embedding_dim, hidden_dim, n_layers, dropout=drop_prob, batch_first=True)
# dropout layer
self.dropout = nn.Dropout(0.3)
# linear and sigmoid layers
self.fc = nn.Linear(hidden_dim, output_size)
self.sig = nn.Sigmoid()
def forward(self, x, hidden):
"""
Perform a forward pass
"""
batch_size = x.size(0)
x = x.long()
# embedding and lstm layers
embeds = self.embedding(x)
lstm_out, hidden = self.lstm(embeds, hidden)
# stack lstm outputs
lstm_out = lstm_out.contiguous().view(-1, self.hidden_dim)
# dropout and fully connected layer
out = self.dropout(lstm_out)
out = self.fc(out)
# sigmoid function
sig_out = self.sig(out)
# reshape to be batch_size first
sig_out = sig_out.view(batch_size, -1)
# get only last neuron output of each row
sig_out = sig_out[:, -1]
# return last sigmoid output and hidden state
return sig_out, hidden
def init_hidden(self, batch_size):
"""
Intitialize the hidden state
"""
weight = next(self.parameters()).data
hidden = (weight.new(self.n_layers, batch_size, self.hidden_dim).zero_(),
weight.new(self.n_layers, batch_size, self.hidden_dim).zero_())
return hidden