/
vgg.py
504 lines (424 loc) · 20 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
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
import collections
import os
import sys
import numpy
try:
from PIL import Image
available = True
except ImportError as e:
available = False
_import_error = e
import chainer
from chainer.dataset.convert import concat_examples
from chainer.dataset import download
from chainer import function
from chainer.functions.activation.relu import relu
from chainer.functions.activation.softmax import softmax
from chainer.functions.array.reshape import reshape
from chainer.functions.math.sum import sum
from chainer.functions.noise.dropout import dropout
from chainer.functions.pooling.max_pooling_nd import max_pooling_2d
from chainer.initializers import constant
from chainer.initializers import normal
from chainer import link
from chainer.links.connection.convolution_2d import Convolution2D
from chainer.links.connection.linear import Linear
from chainer.serializers import npz
from chainer.utils import argument
from chainer.utils import imgproc
from chainer.variable import Variable
class VGGLayers(link.Chain):
"""A pre-trained CNN model provided by VGG team.
You can use ``VGG16Layers`` or ``VGG19Layers`` for concrete
implementations. During initialization, this chain model
automatically downloads the pre-trained caffemodel, convert to
another chainer model, stores it on your local directory,
and initializes all the parameters with it.
This model would be useful when you want to extract a semantic
feature vector from a given image, or fine-tune the model
on a different dataset.
Note that these pre-trained models are released under Creative Commons
Attribution License.
If you want to manually convert the pre-trained caffemodel to a chainer
model that can be specified in the constructor,
please use ``convert_caffemodel_to_npz`` classmethod instead.
See: K. Simonyan and A. Zisserman, `Very Deep Convolutional Networks
for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`_
Args:
pretrained_model (str): the destination of the pre-trained
chainer model serialized as a ``.npz`` file.
If this argument is specified as ``auto``,
it automatically downloads the caffemodel from the internet.
Note that in this case the converted chainer model is stored
on ``$CHAINER_DATASET_ROOT/pfnet/chainer/models`` directory,
where ``$CHAINER_DATASET_ROOT`` is set as
``$HOME/.chainer/dataset`` unless you specify another value
as a environment variable. The converted chainer model is
automatically used from the second time.
If the argument is specified as ``None``, all the parameters
are not initialized by the pre-trained model, but the default
initializer used in the original paper, i.e.,
``chainer.initializers.Normal(scale=0.01)``.
n_layers (int): The number of layers of this model. It should be
either 16 or 19.
Attributes:
available_layers (list of str): The list of available layer names
used by ``forward`` and ``extract`` methods.
"""
def __init__(self, pretrained_model='auto', n_layers=16):
super(VGGLayers, self).__init__()
if pretrained_model:
# As a sampling process is time-consuming,
# we employ a zero initializer for faster computation.
init = constant.Zero()
kwargs = {'initialW': init, 'initial_bias': init}
else:
# employ default initializers used in the original paper
kwargs = {
'initialW': normal.Normal(0.01),
'initial_bias': constant.Zero(),
}
if n_layers not in [16, 19]:
raise ValueError(
'The n_layers argument should be either 16 or 19, '
'but {} was given.'.format(n_layers)
)
with self.init_scope():
self.conv1_1 = Convolution2D(3, 64, 3, 1, 1, **kwargs)
self.conv1_2 = Convolution2D(64, 64, 3, 1, 1, **kwargs)
self.conv2_1 = Convolution2D(64, 128, 3, 1, 1, **kwargs)
self.conv2_2 = Convolution2D(128, 128, 3, 1, 1, **kwargs)
self.conv3_1 = Convolution2D(128, 256, 3, 1, 1, **kwargs)
self.conv3_2 = Convolution2D(256, 256, 3, 1, 1, **kwargs)
self.conv3_3 = Convolution2D(256, 256, 3, 1, 1, **kwargs)
self.conv4_1 = Convolution2D(256, 512, 3, 1, 1, **kwargs)
self.conv4_2 = Convolution2D(512, 512, 3, 1, 1, **kwargs)
self.conv4_3 = Convolution2D(512, 512, 3, 1, 1, **kwargs)
self.conv5_1 = Convolution2D(512, 512, 3, 1, 1, **kwargs)
self.conv5_2 = Convolution2D(512, 512, 3, 1, 1, **kwargs)
self.conv5_3 = Convolution2D(512, 512, 3, 1, 1, **kwargs)
self.fc6 = Linear(512 * 7 * 7, 4096, **kwargs)
self.fc7 = Linear(4096, 4096, **kwargs)
self.fc8 = Linear(4096, 1000, **kwargs)
if n_layers == 19:
self.conv3_4 = Convolution2D(256, 256, 3, 1, 1, **kwargs)
self.conv4_4 = Convolution2D(512, 512, 3, 1, 1, **kwargs)
self.conv5_4 = Convolution2D(512, 512, 3, 1, 1, **kwargs)
if pretrained_model == 'auto':
if n_layers == 16:
_retrieve(
'VGG_ILSVRC_16_layers.npz',
'https://www.robots.ox.ac.uk/%7Evgg/software/very_deep/'
'caffe/VGG_ILSVRC_16_layers.caffemodel',
self)
else:
_retrieve(
'VGG_ILSVRC_19_layers.npz',
'http://www.robots.ox.ac.uk/%7Evgg/software/very_deep/'
'caffe/VGG_ILSVRC_19_layers.caffemodel',
self)
elif pretrained_model:
npz.load_npz(pretrained_model, self)
@property
def functions(self):
# This class will not be used directly.
raise NotImplementedError
@property
def available_layers(self):
return list(self.functions.keys())
@classmethod
def convert_caffemodel_to_npz(cls, path_caffemodel, path_npz):
"""Converts a pre-trained caffemodel to a chainer model.
Args:
path_caffemodel (str): Path of the pre-trained caffemodel.
path_npz (str): Path of the converted chainer model.
"""
# As CaffeFunction uses shortcut symbols,
# we import CaffeFunction here.
from chainer.links.caffe.caffe_function import CaffeFunction
caffemodel = CaffeFunction(path_caffemodel)
npz.save_npz(path_npz, caffemodel, compression=False)
def forward(self, x, layers=None, **kwargs):
"""forward(self, x, layers=['prob'])
Computes all the feature maps specified by ``layers``.
Args:
x (~chainer.Variable): Input variable. It should be prepared by
``prepare`` function.
layers (list of str): The list of layer names you want to extract.
If ``None``, 'prob' will be used as layers.
Returns:
Dictionary of ~chainer.Variable: A dictionary in which
the key contains the layer and the value contains the
corresponding feature map variable.
"""
if layers is None:
layers = ['prob']
if kwargs:
argument.check_unexpected_kwargs(
kwargs, test='test argument is not supported anymore. '
'Use chainer.using_config'
)
argument.assert_kwargs_empty(kwargs)
h = x
activations = {}
target_layers = set(layers)
for key, funcs in self.functions.items():
if not target_layers:
break
for func in funcs:
h = func(h)
if key in target_layers:
activations[key] = h
target_layers.remove(key)
return activations
def extract(self, images, layers=None, size=(224, 224), **kwargs):
"""extract(self, images, layers=['fc7'], size=(224, 224))
Extracts all the feature maps of given images.
The difference of directly executing ``forward`` is that
it directly accepts images as an input and automatically
transforms them to a proper variable. That is,
it is also interpreted as a shortcut method that implicitly calls
``prepare`` and ``forward`` functions.
Unlike ``predict`` method, this method does not override
``chainer.config.train`` and ``chainer.config.enable_backprop``
configuration. If you want to extract features without updating
model parameters, you need to manually set configuration when
calling this method as follows:
.. code-block:: python
# model is an instance of VGGLayers (16 or 19 layers)
with chainer.using_config('train', False):
with chainer.using_config('enable_backprop', False):
feature = model.extract([image])
Args:
images (iterable of PIL.Image or numpy.ndarray): Input images.
layers (list of str): The list of layer names you want to extract.
size (pair of ints): The resolution of resized images used as
an input of CNN. All the given images are not resized
if this argument is ``None``, but the resolutions of
all the images should be the same.
Returns:
Dictionary of ~chainer.Variable: A directory in which
the key contains the layer name and the value contains
the corresponding feature map variable.
"""
if layers is None:
layers = ['fc7']
if kwargs:
argument.check_unexpected_kwargs(
kwargs, test='test argument is not supported anymore. '
'Use chainer.using_config',
volatile='volatile argument is not supported anymore. '
'Use chainer.using_config')
argument.assert_kwargs_empty(kwargs)
x = concat_examples([prepare(img, size=size) for img in images])
x = Variable(self.xp.asarray(x))
return self(x, layers=layers)
def predict(self, images, oversample=True):
"""Computes all the probabilities of given images.
Args:
images (iterable of PIL.Image or numpy.ndarray): Input images.
When you specify a color image as a :class:`numpy.ndarray`,
make sure that color order is RGB.
oversample (bool): If ``True``, it averages results across
center, corners, and mirrors. Otherwise, it uses only the
center.
Returns:
~chainer.Variable: Output that contains the class probabilities
of given images.
"""
x = concat_examples([prepare(img, size=(256, 256)) for img in images])
if oversample:
x = imgproc.oversample(x, crop_dims=(224, 224))
else:
x = x[:, :, 16:240, 16:240]
# Use no_backprop_mode to reduce memory consumption
with function.no_backprop_mode(), chainer.using_config('train', False):
x = Variable(self.xp.asarray(x))
y = self(x, layers=['prob'])['prob']
if oversample:
n = len(y) // 10
y_shape = y.shape[1:]
y = reshape(y, (n, 10) + y_shape)
y = sum(y, axis=1) / 10
return y
class VGG16Layers(VGGLayers):
"""A pre-trained CNN model with 16 layers provided by VGG team.
During initialization, this chain model automatically downloads
the pre-trained caffemodel, convert to another chainer model,
stores it on your local directory, and initializes all the parameters
with it. This model would be useful when you want to extract a semantic
feature vector from a given image, or fine-tune the model
on a different dataset.
Note that this pre-trained model is released under Creative Commons
Attribution License.
If you want to manually convert the pre-trained caffemodel to a chainer
model that can be specified in the constructor,
please use ``convert_caffemodel_to_npz`` classmethod instead.
See: K. Simonyan and A. Zisserman, `Very Deep Convolutional Networks
for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`_
Args:
pretrained_model (str): the destination of the pre-trained
chainer model serialized as a ``.npz`` file.
If this argument is specified as ``auto``,
it automatically downloads the caffemodel from the internet.
Note that in this case the converted chainer model is stored
on ``$CHAINER_DATASET_ROOT/pfnet/chainer/models`` directory,
where ``$CHAINER_DATASET_ROOT`` is set as
``$HOME/.chainer/dataset`` unless you specify another value
as a environment variable. The converted chainer model is
automatically used from the second time.
If the argument is specified as ``None``, all the parameters
are not initialized by the pre-trained model, but the default
initializer used in the original paper, i.e.,
``chainer.initializers.Normal(scale=0.01)``.
Attributes:
available_layers (list of str): The list of available layer names
used by ``forward`` and ``extract`` methods.
"""
def __init__(self, pretrained_model='auto'):
super(VGG16Layers, self).__init__(pretrained_model, 16)
@property
def functions(self):
return collections.OrderedDict([
('conv1_1', [self.conv1_1, relu]),
('conv1_2', [self.conv1_2, relu]),
('pool1', [_max_pooling_2d]),
('conv2_1', [self.conv2_1, relu]),
('conv2_2', [self.conv2_2, relu]),
('pool2', [_max_pooling_2d]),
('conv3_1', [self.conv3_1, relu]),
('conv3_2', [self.conv3_2, relu]),
('conv3_3', [self.conv3_3, relu]),
('pool3', [_max_pooling_2d]),
('conv4_1', [self.conv4_1, relu]),
('conv4_2', [self.conv4_2, relu]),
('conv4_3', [self.conv4_3, relu]),
('pool4', [_max_pooling_2d]),
('conv5_1', [self.conv5_1, relu]),
('conv5_2', [self.conv5_2, relu]),
('conv5_3', [self.conv5_3, relu]),
('pool5', [_max_pooling_2d]),
('fc6', [self.fc6, relu, dropout]),
('fc7', [self.fc7, relu, dropout]),
('fc8', [self.fc8]),
('prob', [softmax]),
])
class VGG19Layers(VGGLayers):
"""A pre-trained CNN model with 19 layers provided by VGG team.
During initialization, this chain model automatically downloads
the pre-trained caffemodel, convert to another chainer model,
stores it on your local directory, and initializes all the parameters
with it. This model would be useful when you want to extract a semantic
feature vector from a given image, or fine-tune the model
on a different dataset.
Note that this pre-trained model is released under Creative Commons
Attribution License.
If you want to manually convert the pre-trained caffemodel to a chainer
model that can be specified in the constructor,
please use ``convert_caffemodel_to_npz`` classmethod instead.
See: K. Simonyan and A. Zisserman, `Very Deep Convolutional Networks
for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`_
Args:
pretrained_model (str): the destination of the pre-trained
chainer model serialized as a ``.npz`` file.
If this argument is specified as ``auto``,
it automatically downloads the caffemodel from the internet.
Note that in this case the converted chainer model is stored
on ``$CHAINER_DATASET_ROOT/pfnet/chainer/models`` directory,
where ``$CHAINER_DATASET_ROOT`` is set as
``$HOME/.chainer/dataset`` unless you specify another value
as a environment variable. The converted chainer model is
automatically used from the second time.
If the argument is specified as ``None``, all the parameters
are not initialized by the pre-trained model, but the default
initializer used in the original paper, i.e.,
``chainer.initializers.Normal(scale=0.01)``.
Attributes:
available_layers (list of str): The list of available layer names
used by ``forward`` and ``extract`` methods.
"""
def __init__(self, pretrained_model='auto'):
super(VGG19Layers, self).__init__(pretrained_model, 19)
@property
def functions(self):
return collections.OrderedDict([
('conv1_1', [self.conv1_1, relu]),
('conv1_2', [self.conv1_2, relu]),
('pool1', [_max_pooling_2d]),
('conv2_1', [self.conv2_1, relu]),
('conv2_2', [self.conv2_2, relu]),
('pool2', [_max_pooling_2d]),
('conv3_1', [self.conv3_1, relu]),
('conv3_2', [self.conv3_2, relu]),
('conv3_3', [self.conv3_3, relu]),
('conv3_4', [self.conv3_4, relu]),
('pool3', [_max_pooling_2d]),
('conv4_1', [self.conv4_1, relu]),
('conv4_2', [self.conv4_2, relu]),
('conv4_3', [self.conv4_3, relu]),
('conv4_4', [self.conv4_4, relu]),
('pool4', [_max_pooling_2d]),
('conv5_1', [self.conv5_1, relu]),
('conv5_2', [self.conv5_2, relu]),
('conv5_3', [self.conv5_3, relu]),
('conv5_4', [self.conv5_4, relu]),
('pool5', [_max_pooling_2d]),
('fc6', [self.fc6, relu, dropout]),
('fc7', [self.fc7, relu, dropout]),
('fc8', [self.fc8]),
('prob', [softmax]),
])
def prepare(image, size=(224, 224)):
"""Converts the given image to the numpy array for VGG models.
Note that you have to call this method before ``forward``
because the pre-trained vgg model requires to resize the given image,
covert the RGB to the BGR, subtract the mean,
and permute the dimensions before calling.
Args:
image (PIL.Image or numpy.ndarray): Input image.
If an input is ``numpy.ndarray``, its shape must be
``(height, width)``, ``(height, width, channels)``,
or ``(channels, height, width)``, and
the order of the channels must be RGB.
size (pair of ints): Size of converted images.
If ``None``, the given image is not resized.
Returns:
numpy.ndarray: The converted output array.
"""
if not available:
raise ImportError('PIL cannot be loaded. Install Pillow!\n'
'The actual import error is as follows:\n' +
str(_import_error))
dtype = chainer.get_dtype()
if isinstance(image, numpy.ndarray):
if image.ndim == 3:
if image.shape[0] == 1:
image = image[0, :, :]
elif image.shape[0] == 3:
image = image.transpose((1, 2, 0))
image = Image.fromarray(image.astype(numpy.uint8))
image = image.convert('RGB')
if size:
image = image.resize(size)
image = numpy.asarray(image, dtype=dtype)
image = image[:, :, ::-1]
image -= numpy.array(
[103.939, 116.779, 123.68], dtype=dtype)
image = image.transpose((2, 0, 1))
return image
def _max_pooling_2d(x):
return max_pooling_2d(x, ksize=2)
def _make_npz(path_npz, url, model):
path_caffemodel = download.cached_download(url)
sys.stderr.write(
'Now loading caffemodel (usually it may take few minutes)\n')
sys.stderr.flush()
VGGLayers.convert_caffemodel_to_npz(path_caffemodel, path_npz)
npz.load_npz(path_npz, model)
return model
def _retrieve(name, url, model):
root = download.get_dataset_directory('pfnet/chainer/models/')
path = os.path.join(root, name)
return download.cache_or_load_file(
path, lambda path: _make_npz(path, url, model),
lambda path: npz.load_npz(path, model))