forked from PINTO0309/DeepLearningMugenKnock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gap_keras.py
165 lines (131 loc) · 4.58 KB
/
gap_keras.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
import keras
import cv2
import numpy as np
import argparse
from glob import glob
# GPU config
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
from keras import backend as K
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
config.gpu_options.visible_device_list="0"
sess = tf.Session(config=config)
K.set_session(sess)
# network
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D, Input, BatchNormalization
num_classes = 2
img_height, img_width = 224, 224
def GAP():
inputs = Input((img_height, img_width, 3))
x = Conv2D(96, (7, 7), padding='valid', strides=2, activation='relu', name='conv1')(inputs)
x = MaxPooling2D((3, 3), strides=2, padding='same')(x)
x = Conv2D(256, (5, 5), padding='valid', strides=2, activation='relu', name='conv2')(x)
x = keras.layers.ZeroPadding2D(1)(x)
x = MaxPooling2D((3, 3), strides=2, padding='same')(x)
x = Conv2D(384, (3, 3), padding='same', activation='relu', name='conv3')(x)
x = Conv2D(384, (3, 3), padding='same', activation='relu', name='conv4')(x)
x = Conv2D(256, (3, 3), padding='same', activation='relu', name='conv5')(x)
x = MaxPooling2D((3, 3), strides=2, padding='same')(x)
# GAP
x = Conv2D(num_classes, (1, 1), padding='same', activation=None, name='out')(x)
x = keras.layers.GlobalAveragePooling2D()(x)
x = Activation('softmax')(x)
model = Model(inputs=inputs, outputs=x, name='model')
return model
CLS = ['akahara', 'madara']
# get train data
def data_load(path, hf=False, vf=False):
xs = []
ts = []
paths = []
for dir_path in glob(path + '/*'):
for path in glob(dir_path + '/*'):
x = cv2.imread(path)
x = cv2.resize(x, (img_width, img_height)).astype(np.float32)
x /= 255.
xs.append(x)
t = [0 for _ in range(num_classes)]
for i, cls in enumerate(CLS):
if cls in path:
t[i] = 1
ts.append(t)
paths.append(path)
if hf:
xs.append(x[:, ::-1])
ts.append(t)
paths.append(path)
if vf:
xs.append(x[::-1])
ts.append(t)
paths.append(path)
if hf and vf:
xs.append(x[::-1, ::-1])
ts.append(t)
paths.append(path)
xs = np.array(xs, dtype=np.float32)
ts = np.array(ts, dtype=np.int)
return xs, ts, paths
# train
def train():
model = GAP()
for layer in model.layers:
layer.trainable = True
model.compile(
loss='categorical_crossentropy',
optimizer=keras.optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True),
metrics=['accuracy'])
xs, ts, paths = data_load('../Dataset/train/images', hf=True, vf=True)
# training
mb = 8
mbi = 0
train_ind = np.arange(len(xs))
np.random.seed(0)
np.random.shuffle(train_ind)
for i in range(500):
if mbi + mb > len(xs):
mb_ind = train_ind[mbi:]
np.random.shuffle(train_ind)
mb_ind = np.hstack((mb_ind, train_ind[:(mb-(len(xs)-mbi))]))
mbi = mb - (len(xs) - mbi)
else:
mb_ind = train_ind[mbi: mbi+mb]
mbi += mb
x = xs[mb_ind]
t = ts[mb_ind]
loss, acc = model.train_on_batch(x=x, y=t)
print("iter >>", i+1, ",loss >>", loss, ',accuracy >>', acc)
model.save('model.h5')
# test
def test():
# load trained model
model = GAP()
model.load_weights('model.h5')
xs, ts, paths = data_load("../Dataset/test/images/")
for i in range(len(paths)):
x = xs[i]
t = ts[i]
path = paths[i]
x = np.expand_dims(x, axis=0)
pred = model.predict_on_batch(x)[0]
print("in {}, predicted probabilities >> {}".format(path, pred))
def arg_parse():
parser = argparse.ArgumentParser(description='CNN implemented with Keras')
parser.add_argument('--train', dest='train', action='store_true')
parser.add_argument('--test', dest='test', action='store_true')
args = parser.parse_args()
return args
# main
if __name__ == '__main__':
args = arg_parse()
if args.train:
train()
if args.test:
test()
if not (args.train or args.test):
print("please select train or test flag")
print("train: python main.py --train")
print("test: python main.py --test")
print("both: python main.py --train --test")