-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodel.py
More file actions
94 lines (70 loc) · 3.3 KB
/
model.py
File metadata and controls
94 lines (70 loc) · 3.3 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(False)
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.embed = nn.Linear(resnet.fc.in_features, embed_size)
def forward(self, images):
features = self.resnet(images)
features = features.view(features.size(0), -1)
features = self.embed(features)
return features
class DecoderRNN(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):
super(DecoderRNN, self).__init__()
# define embedding
self.embedding = nn.Embedding(vocab_size, embed_size)
# define LSTM(s)
self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True)
# define fully-connected layer for model output
self.fc = nn.Linear(hidden_size, vocab_size)
# initialize model weights
self.w_init()
def w_init(self):
# initialize embedding weights
self.embedding.weight.data.uniform_(-0.1,0.1)
# initialize fully-connected layer weights
nn.init.xavier_normal_(self.fc.weight)
self.fc.weight.data.uniform_(-0.1,0.1)
self.fc.bias.data.fill_(0.01)
# initialize bias for all forget gates to 1. to improve performance
# Source: https://discuss.pytorch.org/t/set-forget-gate-bias-of-lstm/1745/4
for names in self.lstm._all_weights:
for name in filter(lambda n: "bias" in n, names):
bias = getattr(self.lstm, name)
n = bias.size(0)
start, end = n//4, n//2
bias.data[start:end].fill_(1.)
def forward(self, features, captions):
# embed captions
captions_embed = self.embedding(captions[:,:-1]) # discard <end> tag in caption
# concat features with captions embed
embeddings = torch.cat((features.unsqueeze(1), captions_embed), 1)
# pass embeddings through LSTM(s)
lstm_outputs, _ = self.lstm(embeddings)
# pass LSTM outputs through output FC layer
outputs = self.fc(lstm_outputs)
return outputs
def sample(self, inputs, states=None, max_len=20):
" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) "
output = []
for i in range(max_len):
# pass input image tensor through LSTM(s)
lstm_outputs, states = self.lstm(inputs, states)
lstm_outputs = self.fc(lstm_outputs.squeeze(1))
# store id of predicted word
_, predict_id = lstm_outputs.max(1)
output.append(predict_id.item())
# break if <end> tag is predicted
if(predict_id.item() == 1):
break
# prepare inputs for next iteration
inputs = self.embedding(predict_id)
inputs = inputs.unsqueeze(1)
return output