VGG16 and VGG19: Foundational Architectures in CNN-based Image Recognition
From the publisher’s feed, collected in the ZeroLabs newsroom.
The paper published in 2012 on “ImageNet Classification with Deep Convolutional Neural Networks,” authored by Alex Krizhevsky, Ilya Sutskever, and Geoffrey E. Hinton, created a new pathway for researchers to come up with new architectures. Researchers explored various methods to modify and update the current architecture for improved results. One such group of researchers that was significantly able to achieve excellent performance and state-of-the-art accuracy on ILSVRC classification and localization tasks was the Visual Geometry Group (VGG) from the University of Oxford.These models are known for their simplicity, effectiveness, and remarkable performance in image classification tasks. They have released two of the best-performing models, VGG16 and VGG19.VGG16 and VGG19, proposed in 2014 by Karen Simonyan and Andrew Zisserman, University of Oxford, were pivotal in advancing the concept of deep learning and pushing the boundaries of image classification accuracy.ArchitectureThe VGG16 and VGG19 architectures both consist of several stacked convolutional layers, interspersed with max-pooling layers to downsample spatial dimensions. They end with fully connected layers responsible for classifying the image into different categories.VGG16The VGG16 model comprises 16 layers, including 13 convolutional layers and 3 fully connected layers.The convolutional layers mainly use 3×3 filters with a stride of 1 and a padding of 1, ensuring that the spatial resolution remains unchanged after each convolution.The max-pooling layers employ 2×2 filters with a stride of 2, halving the spatial dimensions at each step.Out of the 3 fully connected layers, the first two have 4096 channels each, and the third contains 1000 channels (For ILSVRC classification, one channel for each class)The activation function in the hidden layers is ReLu, and the final layer has softmax activation.The architecture does not consist of Local Response Normalization (LRN) as it was present in the AlexNet. The authors noted that LRN did not improve the performance of the ILSVRC dataset, but led to an increase in memory consumption and computation time.VGG19The VGG19 model takes the architecture of VGG16 a step further, incorporating 19 layers, with 16 convolutional layers and 3 fully connected layers.The additional layers make the model deeper, allowing it to capture more complex patterns and hierarchical representations from the input images.The depth of VGG16 and VGG19 is both their strength and their limitation. The models’ depth enables them to learn intricate features, resulting in impressive accuracy on various image classification benchmarks.However, the increasing depth also comes with a considerable increase in parameters, making training and deploying these models computationally expensive and resource-intensive.A vital advantage of these models is their usage in transfer learning. Since these models have been pre-trained on vast datasets like ImageNet, the convolutional layers learn to recognize general features that can be applied to other image-related tasks.Researchers and developers can achieve excellent results even with limited data by leveraging the pre-trained weights and fine-tuning a specific dataset. For any other application, these models can also serve as a good feature extractor from the images.In the above figure, column D represents the VGG16 architecture and column E represents the VGG19 architecture.Python ImplementationVGG-16import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow.keras import layersfrom tensorflow.keras.datasets import mnistfrom tensorflow.keras.layers import Dense, Flatten, Input, Dropoutfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.keras.models import Sequential, Modelfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStoppingfrom sklearn.metrics import confusion_matrix# Configurable ParametersEPOCHS = 10BATCH_SIZE = 32LOSS = tf.keras.metrics.categorical_crossentropyOPTIMIZER = tf.keras.optimizers.SGD()METRIC = ['accuracy']def plot_errors(history, epochs): # Plotting Train and Validation Loss epochs_range = list(range(1, epochs + 1)) train_loss = history.history['loss'] val_loss = history.history['val_loss'] plt.figure(1, figsize=(10, 6)) plt.plot(epochs_range, train_loss, label='train_loss') plt.plot(epochs_range, val_loss, label='validation_loss') plt.xlabel('Epochs') plt.ylabel('Categorical Cross Entropy') plt.legend() plt.show()def plot_confusion_matrix(y_test, y_pred, classes=[]): cm = confusion_matrix(y_test, y_pred, labels=classes) cm_df = pd.DataFrame(cm, index=classes, columns=classes) plt.figure(1, figsize=(16, 8)) sns.set(font_scale=1.5, color_codes=True, palette='deep') sns.heatmap(cm_df, annot=True, annot_kws={'size': 16}, fmt='d', cmap='YlGnBu') plt.ylabel("True Label") plt.xlabel("Predicted Label") plt.title('Confusion Matrix') plt.show()def model_training(model, X_train, y_train, X_cv, y_cv, epochs, batch_size,loss, optimizer, metrics): # Initialise optimizers model.compile(loss=loss, optimizer=optimizer, metrics=metrics) # Enabling Early Stopping es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3) # Enabling check point mc = ModelCheckpoint(filepath='bestModel.h5', monitor='val_acc', mode='max', verbose=1, save_best_only=True) # Model fitting history = model.fit(X_train, y_train, validation_data=(X_cv, y_cv), epochs=epochs, batch_size=batch_size, verbose=1, callbacks=[es, mc]) return model, historyclass VGG: def __init__(self, input_shape, output_shape): self.input_shape = input_shape self.output_shape = output_shape def model_initialise_vgg16(self): # Define the AlexNet Architecture ip = Input(shape= self.input_shape) # 1st Convolutional Layer x = Conv2D(filters=64, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(ip) # 2nd Convolutional Layer x = Conv2D(filters=64, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # 3rd Convolutional Layer x = Conv2D(filters=128, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 4th Convolutional Layer x = Conv2D(filters=128, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # 5th Convolutional Layer x = Conv2D(filters=256, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 6th Convolutional Layer x = Conv2D(filters=256, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 7th Convolutional Layer x = Conv2D(filters=256, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # 8th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 9th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 10th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # 11th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 12th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 13th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # Flattening x = Flatten()(x) # 1st Fully Connected Layer x = Dense(units=4096, activation="relu")(x) # 2nd Fully Connected Layer x = Dense(units=4096, activation="relu")(x) # Output Layer op = Dense(units=self.output_shape, activation="softmax")(x) # Define Model model = Model(inputs=ip, outputs=op) model.summary() return modelif __name__ == '__main__': # Loading the dataset and perform splitting (X_train, y_train), (X_test, y_test) = mnist.load_data() print(X_train.shape, X_test.shape, y_train.shape, y_test.shape) # Resize image to 32x 32 X_train = np.array([np.pad(X_train[i], pad_width=2) for i in range(X_train.shape[0])]) X_test = np.array([np.pad(X_test[i], pad_width=2) for i in range(X_test.shape[0])]) # Performing reshaping operation X_train = X_train.reshape(X_train.shape[0], 32, 32, 1) X_test = X_test.reshape(X_test.shape[0], 32, 32, 1) # Normalization X_train = X_train / 255 X_test = X_test / 255 # One Hot Encoding y_train = tf.keras.utils.to_categorical(y_train, 10) y_test = tf.keras.utils.to_categorical(y_test, 10) # Define image size and number of classes image_size = X_train.shape[1:] classes = y_train.shape[1] print(f"Size of each image = {image_size}") print(f"Nos of Classes = {classes}") # Create model instance and initialise Lenet Model vgg = VGG(image_size, classes) model_vgg16 = vgg.model_initialise_vgg16() epochs = EPOCHS batch_size = BATCH_SIZE loss = LOSS optimizer = OPTIMIZER metric = METRIC model_vgg16, history = model_training(model_vgg16, X_train, y_train, X_test, y_test, epochs, batch_size, loss, optimizer, metric) # Plot trainning and test error plot_errors(history, min(epochs, len(history.history['loss']))) # Perform Prediction y_pred = model_vgg16.predict(X_test) # Get list of prediction y_pred = np.argmax(y_pred, axis=1) y_test = np.argmax(y_test, axis=1) # Show Confusion Matrix plot_confusion_matrix(y_test, y_pred, list(range(classes)))VGG-19import numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltimport tensorflow as tffrom tensorflow.keras import layersfrom tensorflow.keras.datasets import mnistfrom tensorflow.keras.layers import Dense, Flatten, Input, Dropoutfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, BatchNormalizationfrom tensorflow.keras.models import Sequential, Modelfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStoppingfrom sklearn.metrics import confusion_matrix# Configurable ParametersEPOCHS = 10BATCH_SIZE = 32LOSS = tf.keras.metrics.categorical_crossentropyOPTIMIZER = tf.keras.optimizers.SGD()METRIC = ['accuracy']def plot_errors(history, epochs): # Plotting Train and Validation Loss epochs_range = list(range(1, epochs + 1)) train_loss = history.history['loss'] val_loss = history.history['val_loss'] plt.figure(1, figsize=(10, 6)) plt.plot(epochs_range, train_loss, label='train_loss') plt.plot(epochs_range, val_loss, label='validation_loss') plt.xlabel('Epochs') plt.ylabel('Categorical Cross Entropy') plt.legend() plt.show()def plot_confusion_matrix(y_test, y_pred, classes=[]): cm = confusion_matrix(y_test, y_pred, labels=classes) cm_df = pd.DataFrame(cm, index=classes, columns=classes) plt.figure(1, figsize=(16, 8)) sns.set(font_scale=1.5, color_codes=True, palette='deep') sns.heatmap(cm_df, annot=True, annot_kws={'size': 16}, fmt='d', cmap='YlGnBu') plt.ylabel("True Label") plt.xlabel("Predicted Label") plt.title('Confusion Matrix') plt.show()def model_training(model, X_train, y_train, X_cv, y_cv, epochs, batch_size,loss, optimizer, metrics): # Initialise optimizers model.compile(loss=loss, optimizer=optimizer, metrics=metrics) # Enabling Early Stopping es = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=3) # Enabling check point mc = ModelCheckpoint(filepath='bestModel.h5', monitor='val_acc', mode='max', verbose=1, save_best_only=True) # Model fitting history = model.fit(X_train, y_train, validation_data=(X_cv, y_cv), epochs=epochs, batch_size=batch_size, verbose=1, callbacks=[es, mc]) return model, historyclass VGG: def __init__(self, input_shape, output_shape): self.input_shape = input_shape self.output_shape = output_shape def model_initialise_vgg19(self): # Define the AlexNet Architecture ip = Input(shape= self.input_shape) # 1st Convolutional Layer x = Conv2D(filters=64, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(ip) # 2nd Convolutional Layer x = Conv2D(filters=64, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # 3rd Convolutional Layer x = Conv2D(filters=128, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 4th Convolutional Layer x = Conv2D(filters=128, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # 5th Convolutional Layer x = Conv2D(filters=256, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 6th Convolutional Layer x = Conv2D(filters=256, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 7th Convolutional Layer x = Conv2D(filters=256, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 8th Convolutional Layer x = Conv2D(filters=256, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # 9th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 10th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 11th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 12th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # 13th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 14th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 15th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # 16th Convolutional Layer x = Conv2D(filters=512, kernel_size=(3,3), padding="same", strides=(1,1), activation ="relu")(x) # Max Pooling Layer x = MaxPooling2D(pool_size = (2,2), padding="same", strides=(2,2))(x) # Flattening x = Flatten()(x) # 1st Fully Connected Layer x = Dense(units=4096, activation="relu")(x) # 2nd Fully Connected Layer x = Dense(units=4096, activation="relu")(x) # Output Layer op = Dense(units=self.output_shape, activation="softmax")(x) # Define Model model = Model(inputs=ip, outputs=op) model.summary() return modelif __name__ == '__main__': # Loading the dataset and perform splitting (X_train, y_train), (X_test, y_test) = mnist.load_data() print(X_train.shape, X_test.shape, y_train.shape, y_test.shape) # Resize image to 32x 32 X_train = np.array([np.pad(X_train[i], pad_width=2) for i in range(X_train.shape[0])]) X_test = np.array([np.pad(X_test[i], pad_width=2) for i in range(X_test.shape[0])]) # Performing reshaping operation X_train = X_train.reshape(X_train.shape[0], 32, 32, 1) X_test = X_test.reshape(X_test.shape[0], 32, 32, 1) # Normalization X_train = X_train / 255 X_test = X_test / 255 # One Hot Encoding y_train = tf.keras.utils.to_categorical(y_train, 10) y_test = tf.keras.utils.to_categorical(y_test, 10) # Define image size and number of classes image_size = X_train.shape[1:] classes = y_train.shape[1] print(f"Size of each image = {image_size}") print(f"Nos of Classes = {classes}") # Create model instance and initialise Lenet Model vgg = VGG(image_size, classes) model_vgg19 = vgg.model_initialise_vgg19() epochs = EPOCHS batch_size = BATCH_SIZE loss = LOSS optimizer = OPTIMIZER metric = METRIC model_vgg16, history = model_training(model_vgg19, X_train, y_train, X_test, y_test, epochs, batch_size, loss, optimizer, metric) # Plot trainning and test error plot_errors(history, min(epochs, len(history.history['loss']))) # Perform Prediction y_pred = model_vgg16.predict(X_test) # Get list of prediction y_pred = np.argmax(y_pred, axis=1) y_test = np.argmax(y_test, axis=1) # Show Confusion Matrix plot_confusion_matrix(y_test, y_pred, list(range(classes)))The Python code and the corresponding Jupyter Notebook can be obtained from the repository below.GitHub - SP2203/VGG: Implementation of VGG16 and VGG19References:https://papers.nips.cc/paper/2012/file/c399862d3b9d6b76c8436e924a68c45b-Paper.pdfhttps://keras.io/api/— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —If this was useful, consider giving it a clap, it really helps. I write about ML, AI, and technology. Follow me here on Medium so you don’t miss the next one.📌 More from me:→ Keras Implementation of LE-NET→ AlexNet: Pioneering the Path to Modern Deep Learning→ Unleashing the Power of ONNX for Speedier SBERT InferenceVGG16 and VGG19: Foundational Architectures in CNN-based Image Recognition was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.