-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcars2.py
198 lines (138 loc) · 4.87 KB
/
cars2.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
# -*- coding: utf-8 -*-
from __future__ import print_function
import keras
from keras.datasets import cifar10
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, Lambda
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import BatchNormalization as BN
from keras.layers import GaussianNoise as GN
from keras.optimizers import SGD
from keras.models import Model
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import os
from keras.callbacks import LearningRateScheduler as LRS
from keras.preprocessing.image import ImageDataGenerator
batch_size = 32
num_classes = 20
epochs = 150
#### LOAD AND TRANSFORM
## Download: ONLY ONCE!
os.system('wget https://www.dropbox.com/s/sakfqp6o8pbgasm/data.tgz')
os.system('tar xvzf data.tgz')
#####
# Load
x_train = np.load('x_train.npy')
x_test = np.load('x_test.npy')
y_train = np.load('y_train.npy')
y_test = np.load('y_test.npy')
# Stats
print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)
## View some images
plt.imshow(x_train[2,:,:,: ] )
plt.show()
## Transforms
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
y_train = y_train.astype('float32')
y_test = y_test.astype('float32')
x_train /= 255
x_test /= 255
## Labels
y_train=y_train-1
y_test=y_test-1
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
###########################################################
## DEF A BLOCK CONV + BN + GN + CONV + BN + GN + MAXPOOL
def CBGN(model,filters,lname,ishape=0):
if (ishape!=0):
model.add(Conv2D(filters, (3, 3), padding='same',
input_shape=ishape))
else:
model.add(Conv2D(filters, (3, 3), padding='same'))
model.add(BN())
model.add(GN(0.3))
model.add(Activation('relu'))
model.add(Conv2D(filters, (3, 3), padding='same'))
model.add(BN())
model.add(GN(0.3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2),name=lname))
return model
############################################################
datagen = ImageDataGenerator(
width_shift_range=0.2,
height_shift_range=0.2,
rotation_range=20,
zoom_range=[1.0,1.2],
horizontal_flip=True)
## DEF CNN TOPOLOGY 1
model1 = Sequential()
model1=CBGN(model1,32,'conv_model1_1',x_train.shape[1:])
model1=CBGN(model1,64,'conv_model1_2')
model1=CBGN(model1,128,'conv_model1_3')
model1=CBGN(model1,256,'conv_model1_4')
model1=CBGN(model1,512,'conv_model1_5')
model1.add(Flatten())
model1.add(Dense(512))
model1.add(BN())
model1.add(GN(0.3))
model1.add(Activation('relu'))
model1.add(Dropout(0.5))
model1.add(Dense(num_classes))
model1.add(Activation('softmax'))
model1.summary()
## OPTIM AND COMPILE
opt = SGD(lr=0.1)
model1.compile(loss='categorical_crossentropy',
optimizer=opt,
metrics=['accuracy'])
# DEFINE A LEARNING RATE SCHEDULER
def scheduler(epoch):
if epoch < 25:
return .1
elif epoch < 50:
return 0.01
else:
return 0.001
set_lr = LRS(scheduler)
## TRAINING with DA and LRA
history=model1.fit_generator(datagen.flow(x_train, y_train,batch_size=batch_size),
steps_per_epoch=len(x_train) / batch_size,
epochs=epochs,
validation_data=(x_test, y_test),
callbacks=[set_lr],
verbose=1)
#############################
### BILINEAR ####
#############################
def outer_product(x):
phi_I = tf.einsum('ijkm,ijkn->imn',x[0],x[1]) # Einstein Notation [batch,31,31,depth] x [batch,31,31,depth] -> [batch,depth,depth]
phi_I = tf.reshape(phi_I,[-1,128*128]) # Reshape from [batch_size,depth,depth] to [batch_size, depth*depth]
phi_I = tf.divide(phi_I,31*31) # Divide by feature map size [sizexsize]
y_ssqrt = tf.multiply(tf.sign(phi_I),tf.sqrt(tf.abs(phi_I)+1e-12)) # Take signed square root of phi_I
z_l2 = tf.nn.l2_normalize(y_ssqrt) # Apply l2 normalization
return z_l2
conv=model1.get_layer('conv_model1_3')
d1=Dropout(0.5)(conv.output) ## Why??
d2=Dropout(0.5)(conv.output) ## Why??
x = Lambda(outer_product, name='outer_product')([d1,d2])
predictions=Dense(num_classes, activation='softmax', name='predictions')(x)
model = Model(inputs=model1.input, outputs=predictions)
model.compile(loss='categorical_crossentropy',
optimizer=opt,
metrics=['accuracy'])
model.summary()
## TRAINING with DA and LRA
history=model.fit_generator(datagen.flow(x_train, y_train,batch_size=batch_size),
steps_per_epoch=len(x_train) / batch_size,
epochs=epochs,
validation_data=(x_test, y_test),
callbacks=[set_lr],
verbose=1)