Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132928 views
License: OTHER
1
# -*- coding: utf-8 -*-
2
'''VGG16 model for Keras.
3
4
# Reference:
5
6
- [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)
7
8
'''
9
from __future__ import print_function
10
11
import numpy as np
12
import warnings
13
14
from keras.models import Model
15
from keras.layers import Flatten, Dense, Input
16
from keras.layers import Convolution2D, MaxPooling2D
17
from keras.preprocessing import image
18
from keras.utils.layer_utils import convert_all_kernels_in_model
19
from keras.utils.data_utils import get_file
20
from keras import backend as K
21
# from imagenet_utils import decode_predictions, preprocess_input
22
23
24
TH_WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_th_dim_ordering_th_kernels.h5'
25
TF_WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels.h5'
26
TH_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_th_dim_ordering_th_kernels_notop.h5'
27
TF_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5'
28
29
30
def VGG16(include_top=True, weights='imagenet',
31
input_tensor=None):
32
'''Instantiate the VGG16 architecture,
33
optionally loading weights pre-trained
34
on ImageNet. Note that when using TensorFlow,
35
for best performance you should set
36
`image_dim_ordering="tf"` in your Keras config
37
at ~/.keras/keras.json.
38
39
The model and the weights are compatible with both
40
TensorFlow and Theano. The dimension ordering
41
convention used by the model is the one
42
specified in your Keras config file.
43
44
# Arguments
45
include_top: whether to include the 3 fully-connected
46
layers at the top of the network.
47
weights: one of `None` (random initialization)
48
or "imagenet" (pre-training on ImageNet).
49
input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)
50
to use as image input for the model.
51
52
# Returns
53
A Keras model instance.
54
'''
55
if weights not in {'imagenet', None}:
56
raise ValueError('The `weights` argument should be either '
57
'`None` (random initialization) or `imagenet` '
58
'(pre-training on ImageNet).')
59
# Determine proper input shape
60
if K.image_dim_ordering() == 'th':
61
if include_top:
62
input_shape = (3, 224, 224)
63
else:
64
input_shape = (3, None, None)
65
else:
66
if include_top:
67
input_shape = (224, 224, 3)
68
else:
69
input_shape = (None, None, 3)
70
71
if input_tensor is None:
72
img_input = Input(shape=input_shape)
73
else:
74
if not K.is_keras_tensor(input_tensor):
75
img_input = Input(tensor=input_tensor)
76
else:
77
img_input = input_tensor
78
# Block 1
79
x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv1')(img_input)
80
x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv2')(x)
81
x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)
82
83
# Block 2
84
x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv1')(x)
85
x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv2')(x)
86
x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)
87
88
# Block 3
89
x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv1')(x)
90
x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv2')(x)
91
x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv3')(x)
92
x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)
93
94
# Block 4
95
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv1')(x)
96
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv2')(x)
97
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv3')(x)
98
x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)
99
100
# Block 5
101
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv1')(x)
102
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv2')(x)
103
x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv3')(x)
104
x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)
105
106
if include_top:
107
# Classification block
108
x = Flatten(name='flatten')(x)
109
x = Dense(4096, activation='relu', name='fc1')(x)
110
x = Dense(4096, activation='relu', name='fc2')(x)
111
x = Dense(1000, activation='softmax', name='predictions')(x)
112
113
# Create model
114
model = Model(img_input, x)
115
116
# load weights
117
if weights == 'imagenet':
118
print('K.image_dim_ordering:', K.image_dim_ordering())
119
if K.image_dim_ordering() == 'th':
120
if include_top:
121
weights_path = get_file('vgg16_weights_th_dim_ordering_th_kernels.h5',
122
TH_WEIGHTS_PATH,
123
cache_subdir='models')
124
else:
125
weights_path = get_file('vgg16_weights_th_dim_ordering_th_kernels_notop.h5',
126
TH_WEIGHTS_PATH_NO_TOP,
127
cache_subdir='models')
128
model.load_weights(weights_path)
129
if K.backend() == 'tensorflow':
130
warnings.warn('You are using the TensorFlow backend, yet you '
131
'are using the Theano '
132
'image dimension ordering convention '
133
'(`image_dim_ordering="th"`). '
134
'For best performance, set '
135
'`image_dim_ordering="tf"` in '
136
'your Keras config '
137
'at ~/.keras/keras.json.')
138
convert_all_kernels_in_model(model)
139
else:
140
if include_top:
141
weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels.h5',
142
TF_WEIGHTS_PATH,
143
cache_subdir='models')
144
else:
145
weights_path = get_file('vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
146
TF_WEIGHTS_PATH_NO_TOP,
147
cache_subdir='models')
148
model.load_weights(weights_path)
149
if K.backend() == 'theano':
150
convert_all_kernels_in_model(model)
151
return model
152
153
154
if __name__ == '__main__':
155
model = VGG16(include_top=True, weights='imagenet')
156
157
img_path = 'elephant.jpg'
158
img = image.load_img(img_path, target_size=(224, 224))
159
x = image.img_to_array(img)
160
x = np.expand_dims(x, axis=0)
161
x = preprocess_input(x)
162
print('Input image shape:', x.shape)
163
164
preds = model.predict(x)
165
print('Predicted:', decode_predictions(preds))
166
167