-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcnn_text_final_model.py
196 lines (148 loc) · 5.6 KB
/
cnn_text_final_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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
from train_text_iterators import train_model
from cnn_text_model import create_model_iterators
import torch.nn as nn
import torch.optim as optim
from sentence_encoder import *
import cyclic_sceduler
import matplotlib.pyplot as plt
def build_final_text_model_cyclic_lr():
"""
Build final model for title classification with concolutionnal network with
cyclic learning rate
"""
TRAIN_CSV_FILE = "dataset/train_set_cleaned.csv"
VAL_CSV_FILE = "dataset/validation_set_cleaned.csv"
TEST_CSV_FILE = "dataset/book30-listing-test_cleaned.csv"
MIN_LR = 0.0001
MAX_LR = 0.03
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/"
model, iterators = create_model_iterators(TRAIN_CSV_FILE, VAL_CSV_FILE, TEST_CSV_FILE, BATCH_SIZE)
dataset_sizes = {key: len(iterator.data()) for key, iterator in iterators.items()}
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
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, iterators, 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 + "cnn_final_text_model_cyclic_lr.pdf")
plt.close()
torch.save(model.state_dict(), MODEL_DIR + "cnn_final_text_model_cyclic_lr.pt")
return model, stats, lrstats
def build_final_text_model_adam():
"""
Build final model for title classification with concolutionnal network with
Adam optimizer
"""
TRAIN_CSV_FILE = "dataset/train_set_cleaned.csv"
VAL_CSV_FILE = "dataset/validation_set_cleaned.csv"
TEST_CSV_FILE = "dataset/book30-listing-test_cleaned.csv"
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/"
model, iterators = create_model_iterators(TRAIN_CSV_FILE, VAL_CSV_FILE, TEST_CSV_FILE, BATCH_SIZE)
dataset_sizes = {key: len(iterator.data()) for key, iterator in iterators.items()}
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr = LR)
model, stats, lrstats = train_model(model, iterators, 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 + "cnn_final_text_model_adam.pdf")
plt.close()
torch.save(model.state_dict(), MODEL_DIR + "cnn_final_text_model_adam.pt")
return model, stats, lrstats
def build_final_text_model_adam_10():
"""
Build final model for title classification with concolutionnal network with
Adam optimizer for the 10 classes dataset
"""
TRAIN_CSV_FILE = "dataset/train_set_cleaned_10.csv"
VAL_CSV_FILE = "dataset/validation_set_cleaned_10.csv"
TEST_CSV_FILE = "dataset/book30-listing-test_cleaned_10.csv"
LR = 0.001
EPOCHS = 100
BATCH_SIZE = 4
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/"
model, iterators = create_model_iterators(TRAIN_CSV_FILE, VAL_CSV_FILE, TEST_CSV_FILE, BATCH_SIZE)
dataset_sizes = {key: len(iterator.data()) for key, iterator in iterators.items()}
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr = LR)
model, stats, lrstats = train_model(model, iterators, 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 + "cnn_final_text_model_adam_10.pdf")
plt.close()
torch.save(model.state_dict(), MODEL_DIR + "cnn_final_text_model_adam_10.pt")
return model, stats, lrstats
def compare_adam_cyclic():
"""
Compare the results obtained with Adam optimizer and cyclic learning rate
"""
PLOT_DIR = "plots_text_model/"
adam_model, adam_stats, adam_lrstats = build_final_text_model_adam()
cyclic_model, cyclic_stats, cyclic_lrstats = build_final_text_model_cyclic_lr()
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 + "cnn_compare_text_cyclic_adam.pdf")
plt.close()
if __name__ == "__main__":
#build_final_text_model_cyclic_lr()
#build_final_text_model_adam()
#compare_adam_cyclic()
build_final_text_model_adam_10()