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