-
Notifications
You must be signed in to change notification settings - Fork 0
/
run.py
257 lines (181 loc) · 8.43 KB
/
run.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
#coding:utf-8
import os
import sys
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from data import *
from models import *
import torchvision
from torchvision import transforms, utils
from tensorboardX import SummaryWriter
import pandas as pd
# set device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
layer_n = int(sys.argv[1])
ckpt_name = "checkpoints/ResNet-%d_cifar10.pth" %(layer_n*6+2)
log_name = "./logs/ResNet-%d_cifar10_log/" %(layer_n*6+2)
#ckpt_name = "checkpoints/PlainNet-%d_cifar10.pth" %(layer_n*6+2)
#log_name = "./logs/PlainNet-%d_cifar10_log/" %(layer_n*6+2)
batch_size = 100
def train(cnn_model, start_epoch, train_loader, test_loader, lr, auto_lr=True):
# train model from scratch
num_epochs = 500
learning_rate = lr
print("lr: %f" %(learning_rate))
optimizer = torch.optim.SGD(cnn_model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=0.0001)
criterion = torch.nn.CrossEntropyLoss()
train_writer = SummaryWriter(log_dir=log_name+'train')
test_writer = SummaryWriter(log_dir=log_name+'test')
train_offset = 0
train_iter = 0
for epc in range(num_epochs):
epoch = epc + start_epoch
train_total = 0
train_correct = 0
if (train_iter == 64000):
break
for batch_idx, (data_x, data_y) in enumerate(train_loader):
train_iter = train_offset + epoch * len(train_loader) + batch_idx
if (auto_lr):
if (32000 == train_iter):
learning_rate = learning_rate / 10.
optimizer = torch.optim.SGD(cnn_model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=0.0001)
if (48000 == train_iter):
learning_rate = learning_rate / 10.
optimizer = torch.optim.SGD(cnn_model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=0.0001)
if (64000 == train_iter):
learning_rate = learning_rate / 10.
optimizer = torch.optim.SGD(cnn_model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=0.0001)
if (train_iter == 64000):
break
data_x = data_x.to(device)
data_y = data_y.to(device)
optimizer.zero_grad()
output = cnn_model(data_x)
loss = criterion(output, data_y)
_, predicted = torch.max(output.data, 1)
train_total += batch_size
train_correct += (predicted == data_y).sum().item()
loss.backward()
optimizer.step()
if (train_iter % 10 == 0):
print("Epoch %d/%d, Step %d/%d, iter %d Loss: %f, lr: %f" \
%(epoch, start_epoch+num_epochs, batch_idx, len(train_loader), train_iter, loss.item(), learning_rate))
train_writer.add_scalar('data/loss', loss, train_iter)
if (train_iter % 100 == 0):
train_acc = float(train_correct) / train_total
print("iter %d, Train Accuracy: %f" %(train_iter, train_acc))
print("iter %d, Train correct/count: %d/%d" %(train_iter, train_correct, train_total))
train_writer.add_scalar('data/accuracy', train_acc, train_iter)
train_writer.add_scalar('data/error', 1.0-train_acc, train_iter)
train_total = 0
train_correct = 0
if (train_iter % 100 == 0):
with torch.no_grad():
correct = 0
total = 0
loss = 0
for test_batch_idx, (images, labels) in enumerate(test_loader):
images = images.to(device)
labels = labels.to(device)
outputs = cnn_model(images)
loss += criterion(outputs.squeeze(), labels.squeeze())
_, predicted = torch.max(outputs.data, 1)
total += batch_size
correct += (predicted == labels).sum().item()
loss = float(loss) / len(test_loader)
test_writer.add_scalar('data/loss', loss, train_iter)
acc = float(correct)/total
print("iter %d, Test Accuracy: %f" %(train_iter, acc))
print("iter %d, Test avg Loss: %f" %(train_iter, loss))
test_writer.add_scalar('data/accuracy', acc, train_iter)
test_writer.add_scalar('data/error', 1.0-acc, train_iter)
# save models
state_dict = {"state": cnn_model.state_dict(), "epoch": epoch, "acc": acc, "lr": learning_rate}
torch.save(state_dict, ckpt_name)
print("Model saved! %s" %(ckpt_name))
def test(cnn_model, real_test_loader):
labels = []
ids = []
for batch_idx, (images, image_name) in enumerate(real_test_loader):
images = images.to(device)
outputs = cnn_model(images)
prob = torch.nn.functional.softmax(outputs.data)
prob = prob.data.tolist()
_, predicted = torch.max(outputs.data, 1)
print("batch %d/%d" %(batch_idx, len(real_test_loader)))
for name in image_name:
ids.append(os.path.basename(name).split('.')[0])
predicted = predicted.data.tolist()
for item in predicted:
labels.append(item)
submission = pd.DataFrame({'id': ids, 'label': labels})
output_file_name = "submission.csv"
submission.to_csv(output_file_name, index=False)
print("# %s generated!" %(output_file_name))
def weight_init(cnn_model):
## offical usage:
# if type(cnn_model) == nn.Linear:
# cnn_model.weight.data.fill_(1.0)
# print(cnn_model.weight)
if isinstance(cnn_model, nn.Linear):
nn.init.xavier_normal_(cnn_model.weight)
nn.init.constant_(cnn_model.bias, 0)
elif isinstance(cnn_model, nn.Conv2d):
nn.init.kaiming_normal_(cnn_model.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(cnn_model, nn.BatchNorm2d):
nn.init.constant_(cnn_model.weight, 1)
nn.init.constant_(cnn_model.bias, 0)
def main():
if (len(sys.argv) < 3):
print("Error: usage: python main.py train/test!")
exit(0)
else:
# argv[1] for global layer_n
mode = sys.argv[2]
print(mode)
# enhance
# Use the torch.transforms, a package on PIL Image.
transform_enhanc_func = transforms.Compose([
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomCrop(32, padding=4, padding_mode='edge'),
transforms.ToTensor(),
transforms.Lambda(lambda x: x.mul(255)),
transforms.Normalize([125., 123., 114.], [1., 1., 1.])
])
# transform
transform_func = transforms.Compose([
transforms.ToTensor(),
transforms.Lambda(lambda x: x.mul(255)),
transforms.Normalize([125., 123., 114.], [1., 1., 1.])
])
# model create
model = ResNet(layer_n).to(device)
#model = PlainNet(layer_n).to(device)
print("Model created!")
start_epoch = 0
lr = 0.1
# model resume
if (os.path.exists(ckpt_name)):
status_dict = torch.load(ckpt_name)
model_state = status_dict["state"]
start_epoch = status_dict["epoch"] + 1
acc = status_dict["acc"]
lr = status_dict["lr"]
model.load_state_dict(model_state)
print("Model loaded!")
# train
if (mode == 'train'):
train_data_path = '/home/chen/dataset/cifar10/cifar-10-batches-bin/train/'
test_data_path = '/home/chen/dataset/cifar10/cifar-10-batches-bin/test/'
train_data_ratio = 1.0
test_dataset = Cifar10(test_data_path, True, False, train_data_ratio, transform_func)
test_dataloader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=8)
train_dataset = Cifar10(train_data_path, True, False, train_data_ratio, transform_enhanc_func)
val_dataset = Cifar10(train_data_path, True, True,train_data_ratio, transform_func)
train_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=8)
val_dataloader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False, num_workers=8)
train(model, start_epoch, train_dataloader, test_dataloader, lr, True)
if __name__ == "__main__":
main()