-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvgg16.py
537 lines (418 loc) · 21.3 KB
/
vgg16.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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
"""
Example TensorFlow script for finetuning a VGG model on your own data.
Uses tf.contrib.data module which is in release v1.2
Based on PyTorch example from Justin Johnson
(https://gist.github.com/jcjohnson/6e41e8512c17eae5da50aebef3378a4c)
Required packages: tensorflow (v1.2)
Download the weights trained on ImageNet for VGG:
```
wget http://download.tensorflow.org/models/vgg_16_2016_08_28.tar.gz
tar -xvf vgg_16_2016_08_28.tar.gz
rm vgg_16_2016_08_28.tar.gz
```
For this example we will use a tiny dataset of images from the COCO dataset.
We have chosen eight types of animals (bear, bird, cat, dog, giraffe, horse,
sheep, and zebra); for each of these categories we have selected 100 training
images and 25 validation images from the COCO dataset. You can download and
unpack the data (176 MB) by running:
```
wget cs231n.stanford.edu/coco-animals.zip
unzip coco-animals.zip
rm coco-animals.zip
```
The training data is stored on disk; each category has its own folder on disk
and the images for that category are stored as .jpg files in the category folder.
In other words, the directory structure looks something like this:
coco-animals/
train/
bear/
COCO_train2014_000000005785.jpg
COCO_train2014_000000015870.jpg
[...]
bird/
cat/
dog/
giraffe/
horse/
sheep/
zebra/
val/
bear/
bird/
cat/
dog/
giraffe/
horse/
sheep/
zebra/
"""
import argparse
import os
import tensorflow as tf
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets
import time
import random
import numpy as np
# from quadratic_weighted_kappa import *
parser = argparse.ArgumentParser()
parser.add_argument('--train_dir', default='coco-animals/train')
parser.add_argument('--val_dir', default='coco-animals/val')
parser.add_argument('--model_path', default='./weights/vgg_16.ckpt', type=str)
parser.add_argument('--batch_size', default=32, type=int)
parser.add_argument('--num_workers', default=4, type=int)
parser.add_argument('--num_epochs1', default=20, type=int)
parser.add_argument('--num_epochs2', default=10, type=int)
parser.add_argument('--learning_rate1', default=1e-3, type=float)
parser.add_argument('--learning_rate2', default=1e-5, type=float)
parser.add_argument('--dropout_keep_prob', default=0.5, type=float)
parser.add_argument('--weight_decay', default=5e-4, type=float)
# new arguments
parser.add_argument('--restore_ckpt', default=0, type=int) # 1 for True
parser.add_argument('--evaluation', default=0, type=int) # 1 for True
parser.add_argument('--weightFile', default='./models/my-model', type=str)
parser.add_argument('--ckpt_dir', default='./models/alchemic', type=str)
parser.add_argument('--dn_train', default=20, type=int)
parser.add_argument('--dn_test', default=5, type=int)
VGG_MEAN = [123.68, 116.78, 103.94]
def list_images(directory):
"""
Get all the images and labels in directory/label/*.jpg
"""
labels = os.listdir(directory)
# Sort the labels so that training and validation get them in the same order
labels.sort()
files_and_labels = []
for label in labels:
for f in os.listdir(os.path.join(directory, label)):
files_and_labels.append((os.path.join(directory, label, f), label))
filenames, labels = zip(*files_and_labels)
filenames = list(filenames)
labels = list(labels)
unique_labels = list(set(labels))
label_to_int = {}
for i, label in enumerate(unique_labels):
label_to_int[label] = i
labels = [label_to_int[l] for l in labels]
return filenames, labels
def check_accuracy_bak(sess, correct_prediction, labels, prediction, is_training, dataset_init_op):
"""
Check the accuracy of the model on either train or val (depending on dataset_init_op).
"""
# Initialize the correct dataset
sess.run(dataset_init_op)
num_correct, num_samples = 0, 0
gt_labels = []
predicted_labels = []
while True:
try:
correct_pred, label_value, prediction_value = sess.run([correct_prediction, labels, prediction], {is_training: False})
print(type(label_value))
print(type(prediction_value))
num_correct += correct_pred.sum()
num_samples += correct_pred.shape[0]
except tf.errors.OutOfRangeError:
break
# Return the fraction of datapoints that were correctly classified
acc = float(num_correct) / num_samples
acc_weighted = quadratic_weighted_kappa(gt_labels, predicted_labels)
return acc
def check_accuracy(sess, correct_prediction, is_training, dataset_init_op):
"""
Check the accuracy of the model on either train or val (depending on dataset_init_op).
"""
# Initialize the correct dataset
sess.run(dataset_init_op)
num_correct, num_samples = 0, 0
while True:
try:
correct_pred = sess.run(correct_prediction, {is_training: False})
num_correct += correct_pred.sum()
num_samples += correct_pred.shape[0]
except tf.errors.OutOfRangeError:
break
# Return the fraction of datapoints that were correctly classified
acc = float(num_correct) / num_samples
return acc
def main(args):
# Get the list of filenames and corresponding list of labels for training et validation
# train_filenames, train_labels = list_images(args.train_dir)
# val_filenames, val_labels = list_images(args.val_dir)
def generateList(filename, step=None):
with open(filename, 'r') as f:
lines = f.readlines()
# init dictionary for saving all the images.
cls_dict = {}
for line in lines:
splt = line.split(' ')
path, label = splt[0], int(splt[1])
if label not in cls_dict.keys():
cls_dict[label] = [path]
else:
cls_dict[label].append(path)
# shuffle the list and pick 1/20 samples
pathset = []
labelset = []
random.seed(2222)
pos_weights = np.zeros((len(cls_dict.keys())))
for key in cls_dict.keys():
sample_num = len(cls_dict[key])
#print("The {}-th class has {:5d} samples before downsample.".format(key, sample_num))
#print("shuffle the list and pick 1/20 samples")
random.shuffle(cls_dict[key])
cls_dict[key] = cls_dict[key][::step]
sample_num = len(cls_dict[key])
#print("The {:5}-th class has {:5d} samples after downsample.".format(key, sample_num))
#print("First 3 samples\n {}".format(cls_dict[key][:3]))
# get the downsampled list
pathset += cls_dict[key]
labelset += sample_num * [key]
pos_weights[key] = sample_num
pos_weights = 1 / pos_weights * len(pathset)
pathAndLabel = zip(pathset, labelset)
random.shuffle(pathAndLabel)
#print(pathAndLabel)
#print(type(pathAndLabel))
pathset = []
labelset = []
for tmp in pathAndLabel:
pathset.append(tmp[0])
labelset.append(tmp[1])
#print(len(pathset), pathset[:5])
#print(len(labelset), labelset[:5])
print(pos_weights)
# time.sleep(100)
return pathset, labelset, pos_weights
train_filenames, train_labels, pos_weights= generateList('train.txt', step=20)
val_filenames, val_labels, _ = generateList('test.txt', step=20)
assert set(train_labels) == set(val_labels),\
"Train and val labels don't correspond:\n{}\n{}".format(set(train_labels),
set(val_labels))
num_classes = len(set(train_labels))
# --------------------------------------------------------------------------
# In TensorFlow, you first want to define the computation graph with all the
# necessary operations: loss, training op, accuracy...
# Any tensor created in the `graph.as_default()` scope will be part of `graph`
graph = tf.Graph()
with graph.as_default():
# Standard preprocessing for VGG on ImageNet taken from here:
# https://github.com/tensorflow/models/blob/master/research/slim/preprocessing/vgg_preprocessing.py
# Also see the VGG paper for more details: https://arxiv.org/pdf/1409.1556.pdf
# Preprocessing (for both training and validation):
# (1) Decode the image from jpg format
# (2) Resize the image so its smaller side is 256 pixels long
def _parse_function(filename, label):
image_string = tf.read_file(filename)
image_decoded = tf.image.decode_jpeg(image_string, channels=3) # (1)
image = tf.cast(image_decoded, tf.float32)
smallest_side = 256.0
height, width = tf.shape(image)[0], tf.shape(image)[1]
height = tf.to_float(height)
width = tf.to_float(width)
scale = tf.cond(tf.greater(height, width),
lambda: smallest_side / width,
lambda: smallest_side / height)
new_height = tf.to_int32(height * scale)
new_width = tf.to_int32(width * scale)
resized_image = tf.image.resize_images(image, [new_height, new_width]) # (2)
return resized_image, label
# Preprocessing (for training)
# (3) Take a random 224x224 crop to the scaled image
# (4) Horizontally flip the image with probability 1/2
# (5) Substract the per color mean `VGG_MEAN`
# Note: we don't normalize the data here, as VGG was trained without normalization
def training_preprocess(image, label):
crop_image = tf.random_crop(image, [224, 224, 3]) # (3)
flip_image = tf.image.random_flip_left_right(crop_image) # (4)
means = tf.reshape(tf.constant(VGG_MEAN), [1, 1, 3])
centered_image = flip_image - means # (5)
return centered_image, label
# Preprocessing (for validation)
# (3) Take a central 224x224 crop to the scaled image
# (4) Substract the per color mean `VGG_MEAN`
# Note: we don't normalize the data here, as VGG was trained without normalization
def val_preprocess(image, label):
crop_image = tf.image.resize_image_with_crop_or_pad(image, 224, 224) # (3)
means = tf.reshape(tf.constant(VGG_MEAN), [1, 1, 3])
centered_image = crop_image - means # (4)
return centered_image, label
# ----------------------------------------------------------------------
# DATASET CREATION using tf.contrib.data.Dataset
# https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/data
# The tf.contrib.data.Dataset framework uses queues in the background to feed in
# data to the model.
# We initialize the dataset with a list of filenames and labels, and then apply
# the preprocessing functions described above.
# Behind the scenes, queues will load the filenames, preprocess them with multiple
# threads and apply the preprocessing in parallel, and then batch the data
# Training dataset
"""
train_dataset = tf.data.Dataset.from_tensor_slices((train_filenames, train_labels))
train_dataset = train_dataset.map(_parse_function,
num_threads=args.num_workers, output_buffer_size=args.batch_size)
train_dataset = train_dataset.map(training_preprocess,
num_threads=args.num_workers, output_buffer_size=args.batch_size)
train_dataset = train_dataset.shuffle(buffer_size=10000) # don't forget to shuffle
batched_train_dataset = train_dataset.batch(args.batch_size)
"""
train_dataset = tf.data.Dataset.from_tensor_slices((train_filenames, train_labels))
train_dataset = train_dataset.map(_parse_function)
train_dataset = train_dataset.map(training_preprocess)
train_dataset = train_dataset.shuffle(buffer_size=10000) # don't forget to shuffle
batched_train_dataset = train_dataset.batch(args.batch_size)
"""
# Validation dataset
val_dataset = tf.contrib.data.Dataset.from_tensor_slices((val_filenames, val_labels))
val_dataset = val_dataset.map(_parse_function,
num_threads=args.num_workers, output_buffer_size=args.batch_size)
val_dataset = val_dataset.map(val_preprocess,
num_threads=args.num_workers, output_buffer_size=args.batch_size)
batched_val_dataset = val_dataset.batch(args.batch_size)
"""
# Validation dataset
val_dataset = tf.data.Dataset.from_tensor_slices((val_filenames, val_labels))
val_dataset = val_dataset.map(_parse_function)
val_dataset = val_dataset.map(val_preprocess)
batched_val_dataset = val_dataset.batch(args.batch_size)
# Now we define an iterator that can operator on either dataset.
# The iterator can be reinitialized by calling:
# - sess.run(train_init_op) for 1 epoch on the training set
# - sess.run(val_init_op) for 1 epoch on the valiation set
# Once this is done, we don't need to feed any value for images and labels
# as they are automatically pulled out from the iterator queues.
# A reinitializable iterator is defined by its structure. We could use the
# `output_types` and `output_shapes` properties of either `train_dataset`
# or `validation_dataset` here, because they are compatible.
iterator = tf.data.Iterator.from_structure(batched_train_dataset.output_types,
batched_train_dataset.output_shapes)
images, labels = iterator.get_next()
train_init_op = iterator.make_initializer(batched_train_dataset)
val_init_op = iterator.make_initializer(batched_val_dataset)
# Indicates whether we are in training or in test mode
is_training = tf.placeholder(tf.bool)
# ---------------------------------------------------------------------
# Now that we have set up the data, it's time to set up the model.
# For this example, we'll use VGG-16 pretrained on ImageNet. We will remove the
# last fully connected layer (fc8) and replace it with our own, with an
# output size num_classes=8
# We will first train the last layer for a few epochs.
# Then we will train the entire model on our dataset for a few epochs.
# Get the pretrained model, specifying the num_classes argument to create a new
# fully connected replacing the last one, called "vgg_16/fc8"
# Each model has a different architecture, so "vgg_16/fc8" will change in another model.
# Here, logits gives us directly the predicted scores we wanted from the images.
# We pass a scope to initialize "vgg_16/fc8" weights with he_initializer
vgg = tf.contrib.slim.nets.vgg
with slim.arg_scope(vgg.vgg_arg_scope(weight_decay=args.weight_decay)):
logits, _ = vgg.vgg_16(images, num_classes=num_classes, is_training=is_training,
dropout_keep_prob=args.dropout_keep_prob)
# Specify where the model checkpoint is (pretrained weights).
model_path = args.model_path
assert(os.path.isfile(model_path))
# Restore only the layers up to fc7 (included)
# Calling function `init_fn(sess)` will load all the pretrained weights.
variables_all = tf.contrib.framework.get_variables_to_restore()
var_list = tf.trainable_variables()
print(len(variables_all))
for var in var_list:
print(var.name)
variables_to_restore = tf.contrib.framework.get_variables_to_restore(exclude=['vgg_16/fc8'])
init_fn = tf.contrib.framework.assign_from_checkpoint_fn(model_path, variables_to_restore)
# Initialization operation from scratch for the new "fc8" layers
# `get_variables` will only return the variables whose name starts with the given pattern
fc8_variables = tf.contrib.framework.get_variables('vgg_16/fc8')
fc8_init = tf.variables_initializer(fc8_variables)
"""
fc7_variables = tf.contrib.framework.get_variables('vgg_16/fc7')
fc7_init = tf.variables_initializer(fc7_variables)
"""
# iniitalize fc7
"""
fc7_variables = tf.contrib.framework.get_variables('vgg_16/fc7')
fc7_init = tf.variables_initializer(fc7_variables)
"""
# ---------------------------------------------------------------------
# Using tf.losses, any loss is added to the tf.GraphKeys.LOSSES collection
# We can then call the total loss easily
tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
loss = tf.losses.get_total_loss()
"""
one_hot_label = tf.one_hot(tf.cast(labels, tf.int32), depth=5)
print(logits)
print(one_hot_label)
# time.sleep(100)
loss = tf.nn.weighted_cross_entropy_with_logits(targets=one_hot_label, logits=logits, pos_weight=tf.constant(pos_weights, dtype=tf.float32))
print(tf.shape(loss))
loss = tf.reduce_mean(loss)
"""
# First we want to train only the reinitialized last layer fc8 for a few epochs.
# We run minimize the loss only with respect to the fc8 variables (weight and bias).
# fc8_optimizer = tf.train.GradientDescentOptimizer(learning_rate=args.learning_rate1)
# fc8_optimizer = tf.train.AdamOptimizer(learning_rate=args.learning_rate1)
fc8_optimizer = tf.train.MomentumOptimizer(learning_rate=args.learning_rate1, momentum=0.9)
# only optimize fc8
# fc8_train_op = fc8_optimizer.minimize(loss, var_list=fc8_variables)
# Optimize all varialbes
fc8_train_op = fc8_optimizer.minimize(loss)
# Then we want to finetune the entire model for a few epochs.
# We run minimize the loss only with respect to all the variables.
full_optimizer = tf.train.GradientDescentOptimizer(args.learning_rate2)
full_train_op = full_optimizer.minimize(loss)
# Evaluation metrics
prediction = tf.to_int32(tf.argmax(logits, 1))
correct_prediction = tf.equal(prediction, labels)
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
saver_all = tf.train.Saver()
init_g = tf.global_variables_initializer()
tf.get_default_graph().finalize()
# --------------------------------------------------------------------------
# Now that we have built the graph and finalized it, we define the session.
# The session is the interface to *run* the computational graph.
# We can call our training operations with `sess.run(train_op)` for instance
# saver_all = tf.train.Saver(var_list=var_list)
with tf.Session(graph=graph) as sess:
sess.run(init_g)
init_fn(sess) # load the pretrained weights
sess.run(fc8_init) # initialize the new fc8 layer
#sess.run(fc7_init) # initialize the new fc8 layer
# Update only the last layer for a few epochs.
for epoch in range(args.num_epochs1):
# Run an epoch over the training data.
print('Starting epoch %d / %d' % (epoch + 1, args.num_epochs1))
# Here we initialize the iterator with the training set.
# This means that we can go through an entire epoch until the iterator becomes empty.
sess.run(train_init_op)
while True:
try:
_, loss_value = sess.run([fc8_train_op, loss], {is_training: True})
except tf.errors.OutOfRangeError:
break
# saver_all.save(sess, os.path.join("weights", 'models'), global_step=epoch)
# Check accuracy on the train and val sets every epoch.
train_acc = check_accuracy(sess, correct_prediction, is_training, train_init_op)
val_acc = check_accuracy(sess, correct_prediction, is_training, val_init_op)
print("Epoch [{:1d}], loss: {:6.5f}".format(epoch, loss_value))
print('Train accuracy: %f' % train_acc)
print('Val accuracy: %f\n' % val_acc)
saver_all.save(sess, './my_model.ckpt', global_step=epoch)
# Train the entire model for a few more epochs, continuing with the *same* weights.
for epoch in range(args.num_epochs2):
print('Starting epoch %d / %d' % (epoch + 1, args.num_epochs2))
sess.run(train_init_op)
iteration = 0
while True:
iteration += 1
try:
_, loss_value = sess.run([full_train_op, loss], {is_training: True})
if iteration % 50 == 0 and iteration > 0:
print("Epoch [{:1d}], iteration [{:3d}], loss: {:6.5f}".format(epoch, iteration, loss_value))
except tf.errors.OutOfRangeError:
break
# Check accuracy on the train and val sets every epoch
train_acc = check_accuracy(sess, correct_prediction, is_training, train_init_op)
val_acc = check_accuracy(sess, correct_prediction, is_training, val_init_op)
print('Train accuracy: %f' % train_acc)
print('Val accuracy: %f\n' % val_acc)
if __name__ == '__main__':
args = parser.parse_args()
main(args)