📚 The CoCalc Library - books, templates and other resources
cocalc-examples / data-science-ipython-notebooks / deep-learning / keras-tutorial / deep_learning_models / vgg19.py
132930 viewsLicense: OTHER
# -*- coding: utf-8 -*-1'''VGG19 model for Keras.23# Reference:45- [Very Deep Convolutional Networks for Large-Scale Image Recognition](https://arxiv.org/abs/1409.1556)67'''8from __future__ import print_function910import numpy as np11import warnings1213from keras.models import Model14from keras.layers import Flatten, Dense, Input15from keras.layers import Convolution2D, MaxPooling2D16from keras.preprocessing import image17from keras.utils.layer_utils import convert_all_kernels_in_model18from keras.utils.data_utils import get_file19from keras import backend as K202122TH_WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_th_dim_ordering_th_kernels.h5'23TF_WEIGHTS_PATH = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels.h5'24TH_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_th_dim_ordering_th_kernels_notop.h5'25TF_WEIGHTS_PATH_NO_TOP = 'https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5'262728def VGG19(include_top=True, weights='imagenet',29input_tensor=None):30'''Instantiate the VGG19 architecture,31optionally loading weights pre-trained32on ImageNet. Note that when using TensorFlow,33for best performance you should set34`image_dim_ordering="tf"` in your Keras config35at ~/.keras/keras.json.3637The model and the weights are compatible with both38TensorFlow and Theano. The dimension ordering39convention used by the model is the one40specified in your Keras config file.4142# Arguments43include_top: whether to include the 3 fully-connected44layers at the top of the network.45weights: one of `None` (random initialization)46or "imagenet" (pre-training on ImageNet).47input_tensor: optional Keras tensor (i.e. output of `layers.Input()`)48to use as image input for the model.4950# Returns51A Keras model instance.52'''53if weights not in {'imagenet', None}:54raise ValueError('The `weights` argument should be either '55'`None` (random initialization) or `imagenet` '56'(pre-training on ImageNet).')57# Determine proper input shape58if K.image_dim_ordering() == 'th':59if include_top:60input_shape = (3, 224, 224)61else:62input_shape = (3, None, None)63else:64if include_top:65input_shape = (224, 224, 3)66else:67input_shape = (None, None, 3)6869if input_tensor is None:70img_input = Input(shape=input_shape)71else:72if not K.is_keras_tensor(input_tensor):73img_input = Input(tensor=input_tensor)74else:75img_input = input_tensor76# Block 177x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv1')(img_input)78x = Convolution2D(64, 3, 3, activation='relu', border_mode='same', name='block1_conv2')(x)79x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)8081# Block 282x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv1')(x)83x = Convolution2D(128, 3, 3, activation='relu', border_mode='same', name='block2_conv2')(x)84x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)8586# Block 387x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv1')(x)88x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv2')(x)89x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv3')(x)90x = Convolution2D(256, 3, 3, activation='relu', border_mode='same', name='block3_conv4')(x)91x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)9293# Block 494x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv1')(x)95x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv2')(x)96x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv3')(x)97x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block4_conv4')(x)98x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)99100# Block 5101x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv1')(x)102x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv2')(x)103x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv3')(x)104x = Convolution2D(512, 3, 3, activation='relu', border_mode='same', name='block5_conv4')(x)105x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x)106107if include_top:108# Classification block109x = Flatten(name='flatten')(x)110x = Dense(4096, activation='relu', name='fc1')(x)111x = Dense(4096, activation='relu', name='fc2')(x)112x = Dense(1000, activation='softmax', name='predictions')(x)113114# Create model115model = Model(img_input, x)116117# load weights118if weights == 'imagenet':119print('K.image_dim_ordering:', K.image_dim_ordering())120if K.image_dim_ordering() == 'th':121if include_top:122weights_path = get_file('vgg19_weights_th_dim_ordering_th_kernels.h5',123TH_WEIGHTS_PATH,124cache_subdir='models')125else:126weights_path = get_file('vgg19_weights_th_dim_ordering_th_kernels_notop.h5',127TH_WEIGHTS_PATH_NO_TOP,128cache_subdir='models')129model.load_weights(weights_path)130if K.backend() == 'tensorflow':131warnings.warn('You are using the TensorFlow backend, yet you '132'are using the Theano '133'image dimension ordering convention '134'(`image_dim_ordering="th"`). '135'For best performance, set '136'`image_dim_ordering="tf"` in '137'your Keras config '138'at ~/.keras/keras.json.')139convert_all_kernels_in_model(model)140else:141if include_top:142weights_path = get_file('vgg19_weights_tf_dim_ordering_tf_kernels.h5',143TF_WEIGHTS_PATH,144cache_subdir='models')145else:146weights_path = get_file('vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5',147TF_WEIGHTS_PATH_NO_TOP,148cache_subdir='models')149model.load_weights(weights_path)150if K.backend() == 'theano':151convert_all_kernels_in_model(model)152return model153154155if __name__ == '__main__':156model = VGG19(include_top=True, weights='imagenet')157158img_path = 'cat.jpg'159img = image.load_img(img_path, target_size=(224, 224))160x = image.img_to_array(img)161x = np.expand_dims(x, axis=0)162x = preprocess_input(x)163print('Input image shape:', x.shape)164165preds = model.predict(x)166print('Predicted:', decode_predictions(preds))167168169