Bird
Raised Fist0
TensorFlowml~5 mins

Pre-trained models (VGG, ResNet, MobileNet) in TensorFlow

Choose your learning style10 modes available
Introduction
Pre-trained models help us use powerful AI models that are already trained on large image sets. This saves time and effort when solving new image tasks.
You want to recognize objects in photos without training a model from scratch.
You have limited data but want good image classification results.
You want to build an app that detects animals, cars, or everyday objects quickly.
You want to learn how deep learning models work by using ready-made examples.
You want to improve your model by starting from a strong base instead of random weights.
Syntax
TensorFlow
from tensorflow.keras.applications import VGG16, ResNet50, MobileNet

# Load a pre-trained model
model = VGG16(weights='imagenet', include_top=True)

# Use the model to predict on new images
predictions = model.predict(image_batch)
weights='imagenet' loads the model trained on the ImageNet dataset with 1000 classes.
include_top=True means the model includes the final classification layers.
Examples
Load VGG16 model pre-trained on ImageNet with default top layers.
TensorFlow
from tensorflow.keras.applications import VGG16
model = VGG16(weights='imagenet')
Load ResNet50 without the final classification layers to use as a feature extractor.
TensorFlow
from tensorflow.keras.applications import ResNet50
model = ResNet50(weights='imagenet', include_top=False)
Load MobileNet, a lightweight model good for mobile or low-power devices.
TensorFlow
from tensorflow.keras.applications import MobileNet
model = MobileNet(weights='imagenet')
Sample Model
This code loads the VGG16 model pre-trained on ImageNet, downloads an elephant image, preprocesses it, and predicts the top 3 classes with their probabilities.
TensorFlow
import numpy as np
from tensorflow.keras.applications import VGG16
from tensorflow.keras.applications.vgg16 import preprocess_input, decode_predictions
from tensorflow.keras.preprocessing import image
from tensorflow.keras.utils import get_file

# Load VGG16 pre-trained model
model = VGG16(weights='imagenet')

# Load and prepare an example image (elephant.jpg from Keras utils)
img_path = get_file('elephant.jpg', origin='https://storage.googleapis.com/download.tensorflow.org/example_images/elephant.jpg')
img = image.load_img(img_path, target_size=(224, 224))

# Convert image to array
x = image.img_to_array(img)

# Add batch dimension
x = np.expand_dims(x, axis=0)

# Preprocess input for VGG16
x = preprocess_input(x)

# Predict
preds = model.predict(x)

# Decode predictions to class names
print('Predicted:', decode_predictions(preds, top=3)[0])
OutputSuccess
Important Notes
Pre-trained models expect input images of specific size and preprocessing steps (like normalization).
Using include_top=False allows you to add your own classification layers for custom tasks.
MobileNet is smaller and faster but may be less accurate than VGG or ResNet.
Summary
Pre-trained models save time by using AI models already trained on big image datasets.
VGG, ResNet, and MobileNet are popular models with different sizes and speeds.
You can use these models directly for predictions or as a base for your own tasks.

Practice

(1/5)
1. Which of the following is a key benefit of using pre-trained models like VGG, ResNet, or MobileNet in TensorFlow?
easy
A. They require training from scratch for every new task.
B. They cannot be fine-tuned for new tasks.
C. They only work with text data, not images.
D. They save time by using models already trained on large datasets.

Solution

  1. Step 1: Understand what pre-trained models are

    Pre-trained models are AI models trained on large datasets like ImageNet before you use them.
  2. Step 2: Identify the main advantage

    Using these models saves time because you don't need to train from zero; you can use their learned features directly.
  3. Final Answer:

    They save time by using models already trained on large datasets. -> Option D
  4. Quick Check:

    Pre-trained models save time = B [OK]
Hint: Pre-trained means already trained, so saves time [OK]
Common Mistakes:
  • Thinking pre-trained models need full retraining
  • Believing they only work on text data
  • Assuming they cannot be fine-tuned
2. Which of the following is the correct way to load the MobileNetV2 pre-trained model in TensorFlow with weights trained on ImageNet?
easy
A. tf.keras.MobileNetV2(weights='imagenet')
B. tf.keras.applications.MobileNetV2(weights='imagenet')
C. tf.keras.applications.MobileNet(weights='imagenet')
D. tf.keras.applications.MobileNetV2(weights='random')

Solution

  1. Step 1: Recall the correct TensorFlow module for pre-trained models

    Pre-trained models are loaded from tf.keras.applications, not directly from tf.keras.
  2. Step 2: Check the correct model name and weights argument

    The correct model name is MobileNetV2 and weights='imagenet' loads pre-trained weights.
  3. Final Answer:

    tf.keras.applications.MobileNetV2(weights='imagenet') -> Option B
  4. Quick Check:

    Use tf.keras.applications + correct model name + weights='imagenet' = A [OK]
Hint: Use tf.keras.applications.ModelName(weights='imagenet') [OK]
Common Mistakes:
  • Using tf.keras.MobileNetV2 instead of tf.keras.applications.MobileNetV2
  • Using wrong model name like MobileNet instead of MobileNetV2
  • Setting weights='random' instead of 'imagenet'
3. What will be the output shape of the following code snippet using the ResNet50 model in TensorFlow?
import tensorflow as tf
model = tf.keras.applications.ResNet50(weights='imagenet')
input_shape = (1, 224, 224, 3)
sample_input = tf.random.uniform(input_shape)
output = model(sample_input)
print(output.shape)
medium
A. (1, 7, 7, 2048)
B. (224, 224, 3)
C. (1, 1000)
D. (1, 100)

Solution

  1. Step 1: Understand ResNet50 output for ImageNet weights

    ResNet50 with weights='imagenet' outputs predictions for 1000 classes, so output shape is (batch_size, 1000).
  2. Step 2: Check input batch size and output shape

    Input batch size is 1, so output shape is (1, 1000).
  3. Final Answer:

    (1, 1000) -> Option C
  4. Quick Check:

    ResNet50 output shape = (batch_size, 1000) = A [OK]
Hint: Output shape matches number of ImageNet classes (1000) [OK]
Common Mistakes:
  • Confusing output with input shape
  • Expecting feature map shape instead of final predictions
  • Assuming output has spatial dimensions
4. You tried to load the VGG16 model with this code:
model = tf.keras.applications.VGG16(weights='imagenet', include_top=False, input_shape=(28,28,3))

But got an error. What is the likely cause?
medium
A. Input shape must be at least 32x32 with 3 channels when include_top=False.
B. Weights='imagenet' is not supported for VGG16.
C. include_top=False cannot be used with input_shape argument.
D. VGG16 requires grayscale images, so 3 channels is wrong.

Solution

  1. Step 1: Check VGG16 input shape requirements

    When include_top=False, VGG16 requires input images at least 32x32 pixels with 3 color channels.
  2. Step 2: Verify input shape given

    Input shape (28,28,3) is smaller than 32x32x3 minimum when include_top=False, causing the error.
  3. Step 3: Identify common mistake

    Often error happens if input_shape is smaller than 32x32 or channels not 3. The question implies error due to input shape constraints.
  4. Final Answer:

    Input shape must be at least 32x32 with 3 channels when include_top=False. -> Option A
  5. Quick Check:

    VGG16 input shape min size = 32x32x3 [OK]
Hint: VGG16 needs input ≥32x32x3 if include_top=False [OK]
Common Mistakes:
  • Thinking weights='imagenet' is unsupported
  • Believing include_top=False forbids input_shape
  • Assuming VGG16 uses grayscale images
5. You want to build a fast image classifier for mobile devices using TensorFlow. Which pre-trained model should you choose to balance speed and accuracy?
hard
A. MobileNet, because it is designed for lightweight and fast inference.
B. ResNet50, because it uses residual connections for better training.
C. InceptionV3, because it has the most complex architecture.
D. VGG19, because it has the deepest layers and highest accuracy.

Solution

  1. Step 1: Understand model design goals

    VGG19 is large and slow, ResNet50 is accurate but heavier, MobileNet is optimized for mobile with smaller size and speed.
  2. Step 2: Match model to mobile device needs

    Mobile devices need fast, lightweight models, so MobileNet fits best for balancing speed and accuracy.
  3. Final Answer:

    MobileNet, because it is designed for lightweight and fast inference. -> Option A
  4. Quick Check:

    MobileNet = lightweight + fast for mobile [OK]
Hint: MobileNet is made for mobile speed and size [OK]
Common Mistakes:
  • Choosing VGG19 for mobile despite size
  • Assuming ResNet50 is fastest
  • Picking InceptionV3 without speed consideration
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard