-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvgg.py
316 lines (250 loc) · 12.3 KB
/
vgg.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
import os
import numpy as np
import tensorflow as tf
import time
VGG_MEAN = [103.939, 116.779, 123.68]
class Vgg16:
def __init__(self, vgg16_npy_path=None):
if vgg16_npy_path is None:
self.data_dict = {}
else:
assert os.path.isfile(vgg16_npy_path), vgg16_npy_path + " doesn't exist."
self.data_dict = np.load(vgg16_npy_path).item()
print "npy file loaded"
def build(self, rgb):
"""
load variable from npy to build the VGG
:param rgb: rgb image [batch, height, width, 3] values scaled [0, 1]
"""
start_time = time.time()
print "build model started"
rgb_scaled = rgb * 255.0
# Convert RGB to BGR
red, green, blue = tf.split(axis=3, num_or_size_splits=3, value=rgb_scaled)
assert red.get_shape().as_list()[1:] == [224, 224, 1]
assert green.get_shape().as_list()[1:] == [224, 224, 1]
assert blue.get_shape().as_list()[1:] == [224, 224, 1]
bgr = tf.concat(axis=3, values=[
blue - VGG_MEAN[0],
green - VGG_MEAN[1],
red - VGG_MEAN[2],
])
assert bgr.get_shape().as_list()[1:] == [224, 224, 3]
self.training = tf.Variable(True, trainable = False, name = "training")
self.conv1_1 = self.conv_layer(bgr, "conv1_1")
self.conv1_2 = self.conv_layer(self.conv1_1, "conv1_2")
self.pool1 = self.max_pool(self.conv1_2, 'pool1')
self.conv2_1 = self.conv_layer(self.pool1, "conv2_1")
self.conv2_2 = self.conv_layer(self.conv2_1, "conv2_2")
self.pool2 = self.max_pool(self.conv2_2, 'pool2')
self.conv3_1 = self.conv_layer(self.pool2, "conv3_1")
self.conv3_2 = self.conv_layer(self.conv3_1, "conv3_2")
self.conv3_3 = self.conv_layer(self.conv3_2, "conv3_3")
self.pool3 = self.max_pool(self.conv3_3, 'pool3')
self.conv4_1 = self.conv_layer(self.pool3, "conv4_1")
self.conv4_2 = self.conv_layer(self.conv4_1, "conv4_2")
self.conv4_3 = self.conv_layer(self.conv4_2, "conv4_3")
self.pool4 = self.max_pool(self.conv4_3, 'pool4')
self.conv5_1 = self.conv_layer(self.pool4, "conv5_1")
self.conv5_2 = self.conv_layer(self.conv5_1, "conv5_2")
self.conv5_3 = self.conv_layer(self.conv5_2, "conv5_3")
self.pool5 = self.max_pool(self.conv5_3, 'pool5')
self.keep_prob = tf.cond(self.training, lambda : tf.constant(0.5), lambda : tf.constant(1.0), name = "keep_prob")
self.fc6 = self.fc_layer(self.pool5, "fc6")
assert self.fc6.get_shape().as_list()[1:] == [4096]
self.relu6 = tf.nn.relu(self.fc6, name = "relu6")
self.drop6 = tf.nn.dropout(self.relu6, self.keep_prob, name = "drop6")
self.fc7 = self.fc_layer(self.drop6, "fc7")
self.relu7 = tf.nn.relu(self.fc7, name = "relu7")
self.drop7 = tf.nn.dropout(self.relu7, self.keep_prob, name = "drop7")
self.fc8 = self.fc_layer(self.drop7, "fc8")
self.prob = tf.nn.softmax(self.fc8, name="prob")
self.data_dict = None
print "build model finished: %ds" % (time.time() - start_time)
def avg_pool(self, bottom, name):
return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def max_pool(self, bottom, name):
return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def conv_layer(self, bottom, name):
with tf.variable_scope(name):
filt = self.get_conv_filter(bottom, name)
conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME')
conv_biases = self.get_bias(bottom, name)
bias = tf.nn.bias_add(conv, conv_biases)
relu = tf.nn.relu(bias)
return relu
def fc_layer(self, bottom, name):
with tf.variable_scope(name):
shape = bottom.get_shape().as_list()
dim = 1
for d in shape[1:]:
dim *= d
x = tf.reshape(bottom, [-1, dim])
weights = self.get_fc_weight(x, name)
biases = self.get_bias(x, name)
# Fully connected layer. Note that the '+' operation automatically
# broadcasts the biases.
fc = tf.nn.bias_add(tf.matmul(x, weights), biases)
return fc
def get_n_out(self, name):
if name[:4] == 'conv':
n_out = 64 * (2 ** (min(int(name[4]),4) - 1))
else:
if name[2] == '8':
n_out = 1000
else:
n_out = 4096
return n_out
def get_conv_filter(self, bottom, name):
if self.data_dict.get(name, None) is None:
print 'No pretrained weight for', name, 'filter'
n_in = bottom.get_shape()[-1].value
n_out = self.get_n_out(name)
print 'n_in', n_in, 'n_out', n_out
return tf.get_variable("filter",
shape=[3, 3, n_in, n_out],
dtype=tf.float32,
initializer=tf.contrib.layers.xavier_initializer_conv2d())
return tf.Variable(self.data_dict[name][0], name="filter")
def get_bias(self, bottom, name):
if self.data_dict.get(name, None) is None:
print 'No pretrained weight for', name, 'biases'
n_out = self.get_n_out(name)
print 'n_out', n_out
return tf.Variable(tf.constant(0.0, shape=[n_out], dtype=tf.float32), trainable=True, name='biases')
return tf.Variable(self.data_dict[name][1], name="biases")
def get_fc_weight(self, bottom, name):
if self.data_dict.get(name, None) is None:
print 'No pretrained weight for', name, 'weights'
n_in = bottom.get_shape()[-1].value
n_out = self.get_n_out(name)
print 'n_in', n_in, 'n_out', n_out
return tf.get_variable("weights",
shape=[n_in, n_out],
dtype=tf.float32,
initializer=tf.contrib.layers.xavier_initializer())
return tf.Variable(self.data_dict[name][0], name="weights")
class Vgg19:
def __init__(self, vgg19_npy_path=None):
if vgg19_npy_path is None:
self.data_dict = {}
else:
assert os.path.isfile(vgg19_npy_path), vgg19_npy_path + " doesn't exist."
self.data_dict = np.load(vgg19_npy_path).item()
print "npy file loaded"
def build(self, rgb):
"""
load variable from npy to build the VGG
:param rgb: rgb image [batch, height, width, 3] values scaled [0, 1]
"""
start_time = time.time()
print("build model started")
rgb_scaled = rgb * 255.0
# Convert RGB to BGR
red, green, blue = tf.split(axis=3, num_or_size_splits=3, value=rgb_scaled)
assert red.get_shape().as_list()[1:] == [224, 224, 1]
assert green.get_shape().as_list()[1:] == [224, 224, 1]
assert blue.get_shape().as_list()[1:] == [224, 224, 1]
bgr = tf.concat(axis=3, values=[
blue - VGG_MEAN[0],
green - VGG_MEAN[1],
red - VGG_MEAN[2],
])
assert bgr.get_shape().as_list()[1:] == [224, 224, 3]
self.training = tf.Variable(True, trainable = False, name = "training")
self.conv1_1 = self.conv_layer(bgr, "conv1_1")
self.conv1_2 = self.conv_layer(self.conv1_1, "conv1_2")
self.pool1 = self.max_pool(self.conv1_2, 'pool1')
self.conv2_1 = self.conv_layer(self.pool1, "conv2_1")
self.conv2_2 = self.conv_layer(self.conv2_1, "conv2_2")
self.pool2 = self.max_pool(self.conv2_2, 'pool2')
self.conv3_1 = self.conv_layer(self.pool2, "conv3_1")
self.conv3_2 = self.conv_layer(self.conv3_1, "conv3_2")
self.conv3_3 = self.conv_layer(self.conv3_2, "conv3_3")
self.conv3_4 = self.conv_layer(self.conv3_3, "conv3_4")
self.pool3 = self.max_pool(self.conv3_4, 'pool3')
self.conv4_1 = self.conv_layer(self.pool3, "conv4_1")
self.conv4_2 = self.conv_layer(self.conv4_1, "conv4_2")
self.conv4_3 = self.conv_layer(self.conv4_2, "conv4_3")
self.conv4_4 = self.conv_layer(self.conv4_3, "conv4_4")
self.pool4 = self.max_pool(self.conv4_4, 'pool4')
self.conv5_1 = self.conv_layer(self.pool4, "conv5_1")
self.conv5_2 = self.conv_layer(self.conv5_1, "conv5_2")
self.conv5_3 = self.conv_layer(self.conv5_2, "conv5_3")
self.conv5_4 = self.conv_layer(self.conv5_3, "conv5_4")
self.pool5 = self.max_pool(self.conv5_4, 'pool5')
self.keep_prob = tf.cond(self.training, lambda : tf.constant(0.5), lambda : tf.constant(1.0), name = "keep_prob")
self.fc6 = self.fc_layer(self.pool5, "fc6")
assert self.fc6.get_shape().as_list()[1:] == [4096]
self.relu6 = tf.nn.relu(self.fc6, name = "relu6")
self.drop6 = tf.nn.dropout(self.relu6, self.keep_prob, name = "drop6")
self.fc7 = self.fc_layer(self.drop6, "fc7")
self.relu7 = tf.nn.relu(self.fc7, name = 'relu7')
self.drop7 = tf.nn.dropout(self.relu7, self.keep_prob, name = "drop7")
self.fc8 = self.fc_layer(self.drop7, "fc8")
self.prob = tf.nn.softmax(self.fc8, name="prob")
self.data_dict = None
print("build model finished: %ds" % (time.time() - start_time))
def avg_pool(self, bottom, name):
return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def max_pool(self, bottom, name):
return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def conv_layer(self, bottom, name):
with tf.variable_scope(name):
filt = self.get_conv_filter(bottom, name)
conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME')
conv_biases = self.get_bias(bottom, name)
bias = tf.nn.bias_add(conv, conv_biases)
relu = tf.nn.relu(bias)
return relu
def fc_layer(self, bottom, name):
with tf.variable_scope(name):
shape = bottom.get_shape().as_list()
dim = 1
for d in shape[1:]:
dim *= d
x = tf.reshape(bottom, [-1, dim])
weights = self.get_fc_weight(x, name)
biases = self.get_bias(x, name)
# Fully connected layer. Note that the '+' operation automatically
# broadcasts the biases.
fc = tf.nn.bias_add(tf.matmul(x, weights), biases)
return fc
def get_n_out(self, name):
if name[:4] == 'conv':
n_out = 64 * (2 ** (min(int(name[4]),4) - 1))
else:
if name[2] == '8':
n_out = 1000
else:
n_out = 4096
return n_out
def get_conv_filter(self, bottom, name):
if self.data_dict.get(name, None) is None:
print 'No pretrained weight for', name, 'filter'
n_in = bottom.get_shape()[-1].value
n_out = self.get_n_out(name)
print 'n_in', n_in, 'n_out', n_out
return tf.get_variable("filter",
shape=[3, 3, n_in, n_out],
dtype=tf.float32,
initializer=tf.contrib.layers.xavier_initializer_conv2d())
return tf.Variable(self.data_dict[name][0], name="filter")
def get_bias(self, bottom, name):
if self.data_dict.get(name, None) is None:
print 'No pretrained weight for', name, 'biases'
n_out = self.get_n_out(name)
print 'n_out', n_out
return tf.Variable(tf.constant(0.0, shape=[n_out], dtype=tf.float32), trainable=True, name='biases')
return tf.Variable(self.data_dict[name][1], name="biases")
def get_fc_weight(self, bottom, name):
if self.data_dict.get(name, None) is None:
print 'No pretrained weight for', name, 'weights'
n_in = bottom.get_shape()[-1].value
n_out = self.get_n_out(name)
print 'n_in', n_in, 'n_out', n_out
return tf.get_variable("weights",
shape=[n_in, n_out],
dtype=tf.float32,
initializer=tf.contrib.layers.xavier_initializer())
return tf.Variable(self.data_dict[name][0], name="weights")