-
Notifications
You must be signed in to change notification settings - Fork 0
/
IMDB.Embeddings.py
183 lines (136 loc) · 5.6 KB
/
IMDB.Embeddings.py
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
from torchtext import data,datasets
from torchtext.vocab import GloVe,FastText,CharNGram
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch
from torchtext.datasets import IMDB
import sys
from apex import amp
is_cuda = True
TEXT = data.Field(lower=True, batch_first=True,fix_length=40,)
LABEL = data.Field(sequential=False,)
train, test = IMDB.splits(TEXT, LABEL)
print('train.fields', train.fields)
print('len(train)', len(train))
print('vars(train[0])', vars(train[0]))
TEXT.build_vocab(train, vectors=GloVe(name='6B', dim=300),max_size=10000,min_freq=10)
LABEL.build_vocab(train,)
LABEL.vocab.freqs
d = vars(TEXT.vocab)
d.keys()
TEXT.vocab.vectors
len(TEXT.vocab.stoi)
train_iter, test_iter = data.BucketIterator.splits((train, test), batch_size=32)
train_iter.repeat = False
test_iter.repeat = False
class EmbNet(nn.Module):
def __init__(self, emb_size, hidden_size1, hidden_size2=400):
super().__init__()
self.embedding = nn.Embedding(emb_size, hidden_size1)
self.fc = nn.Linear(hidden_size2, 3)
def forward(self, x):
embeds = self.embedding(x).view(x.size(0), -1)
out = self.fc(embeds)
return F.log_softmax(out, dim=-1)
model = EmbNet(len(TEXT.vocab.stoi),10).cuda()
optimizer = optim.Adam(model.parameters(),lr=0.001)
model, optimizer = amp.initialize(model, optimizer)
train_iter, test_iter = data.BucketIterator.splits((train, test), batch_size=32,shuffle=True)
train_iter.repeat = False
test_iter.repeat = False
def fit(epoch, model, data_loader, phase='training', volatile=False):
if phase == 'training':
model.train()
if phase == 'validation':
model.eval()
volatile = True
running_loss = 0.0
running_correct = 0
for batch_idx, batch in enumerate(data_loader):
text, target = batch.text, batch.label
if is_cuda:
text, target = text.cuda(), target.cuda()
if phase == 'training':
optimizer.zero_grad()
output = model(text)
loss = F.nll_loss(output, target)
running_loss += F.nll_loss(output, target, reduction='sum').data.item()
preds = output.data.max(dim=1, keepdim=True)[1]
running_correct += preds.eq(target.data.view_as(preds)).cpu().sum()
if phase == 'training':
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
optimizer.step()
loss = running_loss / len(data_loader.dataset)
accuracy = 100. * running_correct / len(data_loader.dataset)
print(
f'{phase} loss is {loss:{5}.{2}} and {phase} accuracy is {running_correct}/{len(data_loader.dataset)}{accuracy:{10}.{4}}')
return loss, accuracy
train_losses , train_accuracy = [],[]
val_losses , val_accuracy = [],[]
from time import time
ST = time()
for epoch in range(1,10):
print("Epoch #", epoch, sep="")
epoch_loss, epoch_accuracy = fit(epoch,model,train_iter,phase='training')
val_epoch_loss , val_epoch_accuracy = fit(epoch,model,test_iter,phase='validation')
train_losses.append(epoch_loss)
train_accuracy.append(epoch_accuracy)
val_losses.append(val_epoch_loss)
val_accuracy.append(val_epoch_accuracy)
print("Completed in", time() - ST, "seconds.")
# GLOVE
TEXT = data.Field(lower=True, batch_first=True,fix_length=40,)
LABEL = data.Field(sequential=False,)
train, test = IMDB.splits(TEXT, LABEL)
TEXT.build_vocab(train,test, vectors=GloVe(name='6B', dim=300),max_size=10000,min_freq=10)
LABEL.build_vocab(train,)
TEXT.vocab.vectors
model = EmbNet(len(TEXT.vocab.stoi),300,12000)
model = model.cuda()
model.embedding.weight.data = TEXT.vocab.vectors.cuda()
model.embedding.weight.requires_grad = False
optimizer = optim.Adam([ param for param in model.parameters() if param.requires_grad == True],lr=0.001)
model, optimizer = amp.initialize(model,optimizer)
train_iter, test_iter = data.BucketIterator.splits((train, test), batch_size=64, shuffle=True)
train_iter.repeat = False
test_iter.repeat = False
def fit(epoch, model, data_loader, phase='training', volatile=False):
if phase == 'training':
model.train()
if phase == 'validation':
model.eval()
volatile = True
running_loss = 0.0
running_correct = 0
for batch_idx, batch in enumerate(data_loader):
text, target = batch.text, batch.label
if is_cuda:
text, target = text.cuda(), target.cuda()
if phase == 'training':
optimizer.zero_grad()
output = model(text)
loss = F.nll_loss(output, target)
running_loss += F.nll_loss(output, target, reduction='sum').data.item()
preds = output.data.max(dim=1, keepdim=True)[1]
running_correct += preds.eq(target.data.view_as(preds)).cpu().sum()
if phase == 'training':
with amp.scale_loss(loss, optimizer) as scaled_loss:
scaled_loss.backward()
optimizer.step()
loss = running_loss / len(data_loader.dataset)
accuracy = 100. * running_correct / len(data_loader.dataset)
print(
f'{phase} loss is {loss:{5}.{2}} and {phase} accuracy is {running_correct}/{len(data_loader.dataset)}{accuracy:{10}.{4}}')
return loss, accuracy
ST=time()
for epoch in range(1,10):
print("Epoch #", epoch, sep="")
epoch_loss, epoch_accuracy = fit(epoch,model,train_iter,phase='training')
val_epoch_loss , val_epoch_accuracy = fit(epoch,model,test_iter,phase='validation')
train_losses.append(epoch_loss)
train_accuracy.append(epoch_accuracy)
val_losses.append(val_epoch_loss)
val_accuracy.append(val_epoch_accuracy)
print("Completed in", time() - ST, "seconds.")