Angad Sandhu
Search
Browse
On this page

ExerciseQuestion

Open In Colab

Exercise - Create a VGG network

import tensorflow as tf
import tensorflow_datasets as tfds
from tensorflow.keras import layers

Create named-variables dynamically

# Use the vars keyword to create a local variable named 'class'
vars()['class'] = 'foobar' 
# Here is how you access the variable
vars()['class']
'foobar'

Create a generic VGG block

This block subclasses tf.keras.Model and uses some layers like Conv2D, MaxPooling2D

class Block(tf.keras.Model):
  def __init__(self, filters, kernel_size, repetitions, pool_size=2):
    super(Block, self).__init__()
    self.filters = filters
    self.kernel_size = kernel_size
    self.repetitions = repetitions
    
    # Create a MaxPooling 2D layer with the specified pool size and strides set to 2 
    self.max_pool = # YOUR CODE HERE

    for i in range(self.repetitions):
      # Create a Convolutional 2D layer with 
      # number of filters, kernel size, activation 'ReLU', padding 'same'
      vars(self)['block_{}'.format(i)] = # YOUR CODE HERE
  
  def call(self, inputs):
    # Here we chain all the Convolutional layers
    for i in range(self.repetitions):
      layer = vars(self)['block_{}'.format(i)]
      if i == 0:
        # If the current repetition is 0, pass the batch of inputs to the block
        x = # YOUR CODE HERE
      else:
        # Otherwise chain it with the previous block
        x = # YOUR CODE HERE
    return self.max_pool(x)

Create the Custom VGG network

This model stack a series of VGG blocks and a classification head is attached in the end.

class MyVGG(tf.keras.Model):
  def __init__(self, num_classes):
    super(MyVGG, self).__init__()

    # Creating blocks of VGG with the following 
    # (filters, kernel_size, repetitions) configurations

    # Configure blocks of VGG (filters, kernel_size, repetitions) 
    # Intialize each block
    self.block_a = # Block A (64, 3, 2)
    self.block_b = # Block B (128, 3, 2) 
    self.block_c = # Block C (256, 3, 3) 
    self.block_d = # Block D (512, 3, 3) 
    self.block_e = # Block E (512, 3, 3) 

    # Classification head
    # Define a Flatten layer
    self.flatten = # YOUR CODE HERE
    # Create a Dense layer with 256 units and ReLU as the activation function
    self.fc = # YOUR CODE HERE
    # Finally add the softmax classifier using a Dense layer
    self.classifier = # YOUR CODE HERE

  def call(self, inputs):
    # Chain all the layers one after the other
    x = # YOUR CODE HERE
    x = # YOUR CODE HERE
    # ...
    return self.classifier(x)
dataset = tfds.load('cats_vs_dogs', split=tfds.Split.TRAIN)

# Initialize VGG with the number of classes 
vgg = # YOUR CODE HERE

# Compile with losses and metrics
vgg.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# Define preprocessing function
def preprocess(features):
  # Resize and normalize
  image = tf.image.resize(features['image'], (224, 224))
  return tf.cast(image, tf.float32) / 255., features['label']

# Apply transformations to dataset
dataset = dataset.map(preprocess).batch(32)

# Train the custom VGG model
vgg.fit(dataset, epochs=10)

Browse the library