-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfinal_text_model.py
180 lines (136 loc) · 5.19 KB
/
final_text_model.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
from learning_rate_cyclic import train_model
from text_model import create_model_3 as create_model
from text_model import create_model_10, create_model_18, create_model_19
from text_model import load_data_loaders
import torch.nn as nn
import torch.optim as optim
from sentence_encoder import *
import cyclic_sceduler
import matplotlib.pyplot as plt
import os
def build_final_text_model_cyclic_lr():
"""
Build final model based on title with Infersent and cyclic learning rate
"""
MIN_LR = 0.0001
MAX_LR = 0.05
EPOCHS = 500
BATCH_SIZE = 64
NB_INPUTS = 4096
NB_OUTPUTS = 30
CYCLE_LENGTH = 4
try:
os.mkdir("plots_text_model")
except:
pass
try:
os.mkdir("text_models")
except:
pass
PLOT_DIR = "plots_text_model/"
MODEL_DIR = "text_models/"
dataloaders = load_data_loaders("dataloaders/encoded_text_data_loaders_{}.pickle".format(BATCH_SIZE))
dataset_sizes = {phase: len(dataloader.dataset) for phase, dataloader in dataloaders.items()}
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = create_model(NB_INPUTS, NB_OUTPUTS)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr = MIN_LR, momentum = 0.9)
scheduler = cyclic_sceduler.CyclicLR(optimizer, base_lr = MIN_LR, max_lr = MAX_LR,
step_size = CYCLE_LENGTH * dataset_sizes['train'] / BATCH_SIZE)
model, stats, lrstats = train_model(model, dataloaders, dataset_sizes, BATCH_SIZE, criterion, optimizer, scheduler,
num_epochs = EPOCHS, device = device, scheduler_step = "batch", clip_gradient = True)
plt.plot(stats.epochs['val'], stats.accuracies['val'])
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.grid(True)
plt.savefig(PLOT_DIR + "final_text_model_cyclic_lr.pdf")
torch.save(model.state_dict(), MODEL_DIR + "final_text_model_cyclic_lr.pt")
return model, stats, lrstats
def build_final_text_model_adam():
"""
Build final model based on title with Infersent and Adam optimizer
"""
LR = 0.001
EPOCHS = 500
BATCH_SIZE = 64
NB_INPUTS = 4096
NB_OUTPUTS = 30
try:
os.mkdir("plots_text_model")
except:
pass
try:
os.mkdir("text_models")
except:
pass
PLOT_DIR = "plots_text_model/"
MODEL_DIR = "text_models/"
dataloaders = load_data_loaders("dataloaders/encoded_text_data_loaders_{}.pickle".format(BATCH_SIZE))
dataset_sizes = {phase: len(dataloader.dataset) for phase, dataloader in dataloaders.items()}
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = create_model(NB_INPUTS, NB_OUTPUTS)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr = LR)
model, stats, lrstats = train_model(model, dataloaders, dataset_sizes, BATCH_SIZE, criterion, optimizer,
num_epochs = EPOCHS, device = device, scheduler_step = "batch", clip_gradient = True)
plt.plot(stats.epochs['val'], stats.accuracies['val'])
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.grid(True)
plt.savefig(PLOT_DIR + "final_text_model_adam.pdf")
torch.save(model.state_dict(), MODEL_DIR + "final_text_model_adam.pt")
return model, stats, lrstats
def build_10_classes_model():
"""
Build final model based on title with Infersent and Adam optimizer
on the 10 classes dataset
"""
LR = 0.001
EPOCHS = 500
BATCH_SIZE = 4
NB_INPUTS = 4096
NB_OUTPUTS = 10
try:
os.mkdir("plots_text_model")
except:
pass
try:
os.mkdir("text_models")
except:
pass
PLOT_DIR = "plots_text_model/"
MODEL_DIR = "text_models/"
dataloaders = load_data_loaders("dataloaders/encoded_text_data_loaders_{}_10.pickle".format(BATCH_SIZE))
dataset_sizes = {phase: len(dataloader.dataset) for phase, dataloader in dataloaders.items()}
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
model = create_model_19(NB_INPUTS, NB_OUTPUTS)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr = LR)
model, stats, lrstats = train_model(model, dataloaders, dataset_sizes, BATCH_SIZE, criterion, optimizer,
num_epochs = EPOCHS, device = device, scheduler_step = "batch", clip_gradient = True)
plt.plot(stats.epochs['val'], stats.accuracies['val'])
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.grid(True)
plt.savefig(PLOT_DIR + "final_text_model_10.pdf")
torch.save(model.state_dict(), MODEL_DIR + "final_text_model_10.pt")
return model, stats, lrstats
def compare_adam_cyclic():
"""
Compare cyclic learning rate to Adam optimizer for text model with Infersent
"""
PLOT_DIR = "plots_text_model/"
cyclic_model, cyclic_stats, cyclic_lrstats = build_final_text_model_cyclic_lr()
adam_model, adam_stats, adam_lrstats = build_final_text_model_adam()
plt.plot(cyclic_stats.epochs['val'], cyclic_stats.accuracies['val'], label = "cyclic_lr")
plt.plot(adam_stats.epochs['val'], adam_stats.accuracies['val'], label = "adam")
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.grid(True)
plt.legend()
plt.savefig(PLOT_DIR + "compare_text_cyclic_adam.pdf")
if __name__ == "__main__":
#build_final_text_model_cyclic_lr()
#build_final_text_model_adam()
#compare_adam_cyclic()
build_10_classes_model()