-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.py
221 lines (177 loc) · 6.93 KB
/
main.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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 25 16:40:18 2019
@author: aithlab
"""
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import time
import matplotlib.pyplot as plt
import argparse
from torchvision.datasets import MNIST, CIFAR10
from torch.utils.data import DataLoader
from ur_lstm import UR_LSTM
from utils import Flatten, Accuracy
SEED = 7777
torch.manual_seed(SEED)
np.random.seed(SEED)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('PyTorch with %s' %device)
parser = argparse.ArgumentParser()
parser.add_argument('--save_dir', type=str, default='./result',
help='Save directory of result files')
parser.add_argument('--batch_size', type=int, default=64,
help='The number of batch size')
parser.add_argument('--dataset', type=str, default='mnist',
help='Dataset')
args = parser.parse_args()
save_dir = args.save_dir
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
print("Save result files in %s" %save_dir)
batch_size = args.batch_size
n_class = 10
max_epoch = 100
lr = 1e-3
hidden_size = 512
transform = torchvision.transforms.Compose([torchvision.transforms.ToTensor(),
Flatten()])
dataset_loader = MNIST if args.dataset == 'mnist' else CIFAR10
dataset_ori_shape = [28,28,1] if dataset_loader == MNIST else [32,32,3]
input_dim = 1 if dataset_loader == MNIST else 3
dataset_trn = dataset_loader('./', train=True, transform=transform,download=True)
dataset_test = dataset_loader('./', train=False, transform=transform)
dataloader_trn = DataLoader(dataset_trn, batch_size, shuffle=True)
dataloader_test = DataLoader(dataset_test, batch_size, shuffle=True)
# Check data.
# =============================================================================
# imgs, labels = next(iter(dataloader_trn))
# batch = 0
# plt.imshow(imgs[batch].reshape(dataset_ori_shape), cmap='gray')
# print('Label:', labels[batch].numpy())
# =============================================================================
class UR_Model(nn.Module):
def __init__(self, input_dim, hidden_size, seq_len, num_class, num_layers=1):
super(UR_Model, self).__init__()
self.lstm = UR_LSTM(input_dim, hidden_size, num_layers, batch_first=True)
self.fc1 = nn.Linear(hidden_size*seq_len, 256)
self.fc2 = nn.Linear(256, num_class)
def forward(self, x):
batch_size, _, _ = x.shape
x, (h_n, c_n) = self.lstm(x)
x = x.reshape(batch_size, -1)
x = torch.relu(self.fc1(x))
out = self.fc2(x)
return out
class Basic_Model(nn.Module):
def __init__(self, input_dim, hidden_size, seq_len, num_class, num_layers=1):
super(Basic_Model, self).__init__()
self.lstm = nn.LSTM(input_dim, hidden_size, num_layers, batch_first=True)
self.fc1 = nn.Linear(hidden_size*seq_len, 256)
self.fc2 = nn.Linear(256, num_class)
def forward(self, x):
batch_size, _, _ = x.shape
x, (h_n, c_n) = self.lstm(x)
x = x.reshape(batch_size, -1)
x = torch.relu(self.fc1(x))
out = self.fc2(x)
return out
seq_len = np.prod(dataset_ori_shape[:-1])
ur_model = UR_Model(input_dim, hidden_size, seq_len, n_class).to(device)
basic_model = Basic_Model(input_dim, hidden_size, seq_len, n_class).to(device)
loss = nn.CrossEntropyLoss()
optimizer_ur = optim.Adam(ur_model.parameters(), lr)
optimizer_lstm = optim.Adam(basic_model.parameters(), lr)
losses, losses_test = [],[]
epoch_acc_trn, epoch_acc_test = [], []
for epoch in range(max_epoch):
epoch_loss, acc_trn = [],[]
for iter_, (imgs, labels) in enumerate(dataloader_trn):
start_t = time.time()
out_ur = ur_model(imgs.to(device))
out_lstm = basic_model(imgs.to(device))
acc_ur = Accuracy(out_ur, labels)
acc_lstm = Accuracy(out_lstm, labels)
acc_trn.append([acc_ur, acc_lstm])
batch_loss = []
out_optim = zip([out_ur, out_lstm], [optimizer_ur, optimizer_lstm])
for out, optimizer in out_optim:
loss_ = loss(out, labels.to(device))
optimizer.zero_grad()
loss_.backward()
optimizer.step()
batch_loss.append(loss_.cpu().detach().numpy())
epoch_loss.append(batch_loss)
iter_t = time.time() - start_t
print('\rIteration [%4d/%4d] loss(ur): %.3f, loss(lstm): %.3f, time: %.2fs/it' \
%(iter_+1, len(dataloader_trn), batch_loss[0], batch_loss[1], iter_t),
end='')
acc_trn = np.stack(acc_trn).mean(axis=0)
epoch_acc_trn.append(acc_trn)
epoch_loss = np.stack(epoch_loss).mean(axis=0)
losses.append(epoch_loss)
print('\rEpoch [%3d/%3d] [avg. loss] ur: %.3f, vanilla: %.3f, [acc] ur: %.2f%%, vanilla: %.2f%%' \
%(epoch+1, max_epoch, epoch_loss[0], epoch_loss[1], acc_trn[0]*100, acc_trn[1]*100))
print('Testing...', end='')
epoch_loss, acc_test = [], []
for iter_, (imgs, labels) in enumerate(dataloader_test):
start_t = time.time()
out_lstm = basic_model(imgs.to(device))
out_ur = ur_model(imgs.to(device))
batch_loss = []
out_optim = zip([out_ur, out_lstm], [optimizer_ur, optimizer_lstm])
for out, optimizer in out_optim:
loss_ = loss(out, labels.to(device))
batch_loss.append(loss_.cpu().detach().numpy())
epoch_loss.append(batch_loss)
acc_ur = Accuracy(out_ur, labels)
acc_lstm = Accuracy(out_lstm, labels)
acc_test.append([acc_ur, acc_lstm])
iter_t = time.time() - start_t
acc_test = np.stack(acc_test).mean(axis=0)
epoch_acc_test.append(acc_test)
epoch_loss = np.stack(epoch_loss).mean(axis=0)
losses_test.append(epoch_loss)
print('\r[Test] [avg. loss] ur: %.3f, vanilla: %.3f, [acc] ur: %.2f%%, vanilla: %.2f%%' \
%(epoch_loss[0], epoch_loss[1], acc_test[0]*100, acc_test[1]*100))
losses = np.stack(losses)
plt.figure()
plt.title('[Trn] Loss of UR LSTM')
plt.plot(losses[:, 0])
plt.savefig(os.path.join(save_dir, 'trn_loss_ur.jpg'))
plt.figure()
plt.title('[Trn] Loss of Vanilla LSTM')
plt.plot(losses[:, 1])
plt.savefig(os.path.join(save_dir, 'trn_loss_vanilla.jpg'))
epoch_acc_trn = np.stack(epoch_acc_trn)
plt.figure()
plt.title('[Trn] Acc. of UR LSTM')
plt.plot(epoch_acc_trn[:, 0])
plt.savefig(os.path.join(save_dir, 'trn_acc_ur.jpg'))
plt.figure()
plt.title('[Trn] Acc. of Vanilla LSTM')
plt.plot(epoch_acc_trn[:, 1])
plt.savefig(os.path.join(save_dir, 'test_acc_vanilla.jpg'))
losses_test = np.stack(losses_test)
plt.figure()
plt.title('[Test] Loss of UR LSTM')
plt.plot(losses_test[:, 0])
plt.savefig(os.path.join(save_dir, 'test_loss_ur.jpg'))
plt.figure()
plt.title('[Test] Loss of Vanilla LSTM')
plt.plot(losses_test[:, 1])
plt.savefig(os.path.join(save_dir, 'test_loss_vanilla.jpg'))
epoch_acc_test = np.stack(epoch_acc_test)
plt.figure()
plt.title('[Test] Acc. of UR LSTM')
plt.plot(epoch_acc_test[:, 0])
plt.savefig(os.path.join(save_dir, 'test_acc_ur.jpg'))
plt.figure()
plt.title('[Test] Acc. of Vanilla LSTM')
plt.plot(epoch_acc_test[:, 1])
plt.savefig(os.path.join(save_dir, 'test_acc_vanilla.jpg'))