-
Notifications
You must be signed in to change notification settings - Fork 314
/
captcha_train.py
45 lines (39 loc) · 1.36 KB
/
captcha_train.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
# -*- coding: UTF-8 -*-
import torch
import torch.nn as nn
from torch.autograd import Variable
import my_dataset
from captcha_cnn_model import CNN
# Hyper Parameters
num_epochs = 30
batch_size = 100
learning_rate = 0.001
def main():
cnn = CNN()
cnn.train()
print('init net')
criterion = nn.MultiLabelSoftMarginLoss()
optimizer = torch.optim.Adam(cnn.parameters(), lr=learning_rate)
# Train the Model
train_dataloader = my_dataset.get_train_data_loader()
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_dataloader):
images = Variable(images)
labels = Variable(labels.float())
predict_labels = cnn(images)
# print(predict_labels.type)
# print(labels.type)
loss = criterion(predict_labels, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
if (i+1) % 10 == 0:
print("epoch:", epoch, "step:", i, "loss:", loss.item())
if (i+1) % 100 == 0:
torch.save(cnn.state_dict(), "./model.pkl") #current is model.pkl
print("save model")
print("epoch:", epoch, "step:", i, "loss:", loss.item())
torch.save(cnn.state_dict(), "./model.pkl") #current is model.pkl
print("save last model")
if __name__ == '__main__':
main()