Bird
Raised Fist0
Computer Visionml~20 mins

Why pre-trained models save time in Computer Vision - Experiment to Prove It

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Experiment - Why pre-trained models save time
Problem:You want to classify images into categories but training a model from scratch takes a long time and needs a lot of data.
Current Metrics:Training from scratch: training accuracy 95%, validation accuracy 70%, training time 2 hours.
Issue:The model overfits and training takes too long because it starts learning from zero.
Your Task
Use a pre-trained model to reduce training time and improve validation accuracy to at least 80%.
You must use transfer learning with a pre-trained model.
You can only fine-tune the last layers.
Keep training time under 30 minutes.
Hint 1
Hint 2
Hint 3
Solution
Computer Vision
import tensorflow as tf
from tensorflow.keras.applications import MobileNetV2
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.image import ImageDataGenerator

# Load pre-trained MobileNetV2 without top layers
base_model = MobileNetV2(weights='imagenet', include_top=False, input_shape=(224, 224, 3))

# Freeze base model layers
base_model.trainable = False

# Add new classification layers
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(128, activation='relu')(x)
predictions = Dense(5, activation='softmax')(x)  # Assuming 5 classes

model = Model(inputs=base_model.input, outputs=predictions)

# Compile model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

# Prepare data generators
train_datagen = ImageDataGenerator(rescale=1./255, validation_split=0.2)
train_generator = train_datagen.flow_from_directory(
    'data/train', target_size=(224, 224), batch_size=32, class_mode='categorical', subset='training')
validation_generator = train_datagen.flow_from_directory(
    'data/train', target_size=(224, 224), batch_size=32, class_mode='categorical', subset='validation')

# Train only top layers
history = model.fit(train_generator, epochs=5, validation_data=validation_generator)

# Optionally unfreeze some layers and fine-tune
base_model.trainable = True
for layer in base_model.layers[:-20]:
    layer.trainable = False

model.compile(optimizer=tf.keras.optimizers.Adam(1e-5), loss='categorical_crossentropy', metrics=['accuracy'])
history_fine = model.fit(train_generator, epochs=5, validation_data=validation_generator)
Used MobileNetV2 pre-trained on ImageNet as base model.
Froze early layers to keep learned features.
Added new classification layers for the specific task.
Trained only the new layers first, then fine-tuned some base layers.
Reduced training time from 2 hours to under 30 minutes.
Improved validation accuracy from 70% to over 80%.
Results Interpretation

Before: Training accuracy 95%, validation accuracy 70%, training time 2 hours.

After: Training accuracy 90%, validation accuracy 83%, training time 25 minutes.

Using a pre-trained model saves time because it already knows useful features from many images. You only need to teach it your specific task, which is faster and helps the model generalize better.
Bonus Experiment
Try using a different pre-trained model like ResNet50 and compare training time and accuracy.
💡 Hint
Replace MobileNetV2 with ResNet50 and keep the same training steps to see which model works better for your data.

Practice

(1/5)
1. Why do pre-trained models save time in computer vision projects?
easy
A. They require more data to train from scratch
B. They eliminate the need for any data preprocessing
C. They always produce perfect results without any training
D. They reuse features learned from large datasets, reducing training time

Solution

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

    Pre-trained models have already learned useful features from large datasets, so you don't start from zero.
  2. Step 2: Connect this to time saved

    Since the model already knows many features, you spend less time training it on your own data.
  3. Final Answer:

    They reuse features learned from large datasets, reducing training time -> Option D
  4. Quick Check:

    Pre-trained models reuse features = B [OK]
Hint: Pre-trained means already learned features reused [OK]
Common Mistakes:
  • Thinking pre-trained models need more data
  • Believing they need no training at all
  • Assuming they remove all preprocessing
2. Which of the following is the correct way to load a pre-trained model in Python using PyTorch?
easy
A. model = torchvision.models.resnet50(pretrained=True)
B. model = torchvision.models.resnet50(pretrained=False)
C. model = torchvision.load_model('resnet50')
D. model = torch.load('resnet50_pretrained')

Solution

  1. Step 1: Recall PyTorch syntax for loading pre-trained models

    In PyTorch, you use torchvision.models with pretrained=True to load a pre-trained model.
  2. Step 2: Check options for correctness

    model = torchvision.models.resnet50(pretrained=True) uses the correct function and argument. model = torchvision.models.resnet50(pretrained=False) loads without pre-training. Options C and D are incorrect function calls.
  3. Final Answer:

    model = torchvision.models.resnet50(pretrained=True) -> Option A
  4. Quick Check:

    PyTorch pre-trained load = A [OK]
Hint: Use pretrained=True to load pre-trained models in PyTorch [OK]
Common Mistakes:
  • Using pretrained=False by mistake
  • Calling non-existent functions like torchvision.load_model
  • Trying to load model weights incorrectly
3. Consider this Python code using TensorFlow to load a pre-trained MobileNetV2 model and predict on an input image:
import tensorflow as tf
model = tf.keras.applications.MobileNetV2(weights='imagenet')
import numpy as np
input_data = np.random.rand(1, 224, 224, 3).astype('float32')
predictions = model.predict(input_data)
print(predictions.shape)

What will be the printed output shape?
medium
A. (224, 224, 3)
B. (1, 1000)
C. (1, 224, 224, 3)
D. (1000,)

Solution

  1. Step 1: Understand MobileNetV2 output shape

    MobileNetV2 pre-trained on ImageNet outputs predictions for 1000 classes, so output shape is (batch_size, 1000).
  2. Step 2: Check input batch size and output

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

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

    Output shape = (batch, 1000 classes) = A [OK]
Hint: Output shape matches batch size and number of classes [OK]
Common Mistakes:
  • Confusing input shape with output shape
  • Ignoring batch dimension
  • Expecting output shape to match input image size
4. You tried to fine-tune a pre-trained model but got an error: AttributeError: 'Sequential' object has no attribute 'fc'. What is the likely cause?
medium
A. You used a model architecture without an 'fc' layer and tried to access it
B. You forgot to load pre-trained weights
C. You passed wrong input shape to the model
D. You used the wrong optimizer

Solution

  1. Step 1: Understand the error message

    The error says the model has no attribute 'fc', which usually means the model architecture does not have a fully connected layer named 'fc'.
  2. Step 2: Connect error to cause

    Trying to access or modify 'fc' layer on a Sequential model that doesn't have it causes this error.
  3. Final Answer:

    You used a model architecture without an 'fc' layer and tried to access it -> Option A
  4. Quick Check:

    Missing 'fc' layer attribute = D [OK]
Hint: Check if model has the layer before accessing it [OK]
Common Mistakes:
  • Assuming all models have 'fc' layer
  • Ignoring error details
  • Blaming optimizer or input shape wrongly
5. You want to use a pre-trained model to classify images of cats and dogs but your dataset has only 500 images. Which approach saves the most time while achieving good accuracy?
hard
A. Use a pre-trained model without any fine-tuning and directly predict
B. Train a new model from scratch with random weights on your 500 images
C. Use a pre-trained model and fine-tune only the last layer on your dataset
D. Manually label more images before training any model

Solution

  1. Step 1: Consider dataset size and training time

    With only 500 images, training from scratch is slow and likely inaccurate.
  2. Step 2: Use pre-trained model fine-tuning

    Fine-tuning only the last layer uses learned features and adapts to your task quickly and efficiently.
  3. Final Answer:

    Use a pre-trained model and fine-tune only the last layer on your dataset -> Option C
  4. Quick Check:

    Fine-tune last layer for small data = C [OK]
Hint: Fine-tune last layer for small datasets [OK]
Common Mistakes:
  • Training from scratch with little data
  • Skipping fine-tuning and expecting perfect results
  • Spending time labeling more data unnecessarily