-
Notifications
You must be signed in to change notification settings - Fork 65
/
train.py
142 lines (113 loc) · 4.96 KB
/
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
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
import time
import os
import math
import argparse
from glob import glob
from collections import OrderedDict
import random
import warnings
from datetime import datetime
import joblib
import numpy as np
import pandas as pd
from sklearn.model_selection import KFold, StratifiedKFold
import keras
from keras.datasets import mnist
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.optimizers import SGD, Adam
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau, CSVLogger, LearningRateScheduler, TerminateOnNaN, LambdaCallback
import archs
from metrics import *
from scheduler import *
arch_names = archs.__dict__.keys()
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--name', default=None,
help='model name: (default: arch+timestamp)')
parser.add_argument('--arch', '-a', metavar='ARCH', default='vgg8',
choices=arch_names,
help='model architecture: ' +
' | '.join(arch_names) +
' (default: vgg8)')
parser.add_argument('--num-features', default=3, type=int,
help='dimention of embedded features')
parser.add_argument('--scheduler', default='CosineAnnealing',
choices=['CosineAnnealing', 'None'],
help='scheduler: ' +
' | '.join(['CosineAnnealing', 'None']) +
' (default: CosineAnnealing)')
parser.add_argument('--epochs', default=100, type=int, metavar='N',
help='number of total epochs to run')
parser.add_argument('-b', '--batch-size', default=128, type=int,
metavar='N', help='mini-batch size (default: 128)')
parser.add_argument('--optimizer', default='SGD',
choices=['Adam', 'SGD'],
help='loss: ' +
' | '.join(['Adam', 'SGD']) +
' (default: Adam)')
parser.add_argument('--lr', '--learning-rate', default=1e-1, type=float,
metavar='LR', help='initial learning rate')
parser.add_argument('--min-lr', default=1e-3, type=float,
help='minimum learning rate')
parser.add_argument('--momentum', default=0.5, type=float)
args = parser.parse_args()
return args
def main():
args = parse_args()
# add model name to args
args.name = 'mnist_%s_%dd' %(args.arch, args.num_features)
os.makedirs('models/%s' %args.name, exist_ok=True)
print('Config -----')
for arg in vars(args):
print('%s: %s' %(arg, getattr(args, arg)))
print('------------')
joblib.dump(args, 'models/%s/args.pkl' %args.name)
with open('models/%s/args.txt' %args.name, 'w') as f:
for arg in vars(args):
print('%s: %s' %(arg, getattr(args, arg)), file=f)
(X, y), (X_test, y_test) = mnist.load_data()
X = X[:, :, :, np.newaxis].astype('float32') / 255
X_test = X_test[:, :, :, np.newaxis].astype('float32') / 255
y = keras.utils.to_categorical(y, 10)
y_test = keras.utils.to_categorical(y_test, 10)
if args.optimizer == 'SGD':
optimizer = SGD(lr=args.lr, momentum=args.momentum)
elif args.optimizer == 'Adam':
optimizer = Adam(lr=args.lr)
model = archs.__dict__[args.arch](args)
model.compile(loss='categorical_crossentropy',
optimizer=optimizer,
metrics=['accuracy'])
model.summary()
callbacks = [
ModelCheckpoint(os.path.join('models', args.name, 'model.hdf5'),
verbose=1, save_best_only=True),
CSVLogger(os.path.join('models', args.name, 'log.csv')),
TerminateOnNaN()]
if args.scheduler == 'CosineAnnealing':
callbacks.append(CosineAnnealingScheduler(T_max=args.epochs, eta_max=args.lr, eta_min=args.min_lr, verbose=1))
if 'face' in args.arch:
# callbacks.append(LambdaCallback(on_batch_end=lambda batch, logs: print('W has nan value!!') if np.sum(np.isnan(model.layers[-4].get_weights()[0])) > 0 else 0))
model.fit([X, y], y, validation_data=([X_test, y_test], y_test),
batch_size=args.batch_size,
epochs=args.epochs,
callbacks=callbacks,
verbose=1)
else:
model.fit(X, y, validation_data=(X_test, y_test),
batch_size=args.batch_size,
epochs=args.epochs,
callbacks=callbacks,
verbose=1)
model.load_weights(os.path.join('models/%s/model.hdf5' %args.name))
if 'face' in args.arch:
score = model.evaluate([X_test, y_test], y_test, verbose=1)
else:
score = model.evaluate(X_test, y_test, verbose=1)
print("Test loss:", score[0])
print("Test accuracy:", score[1])
if __name__ == '__main__':
main()