Bird
Raised Fist0
Computer Visionml~20 mins

Model optimization (pruning, quantization) in Computer Vision - ML Experiment: Train & Evaluate

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 - Model optimization (pruning, quantization)
Problem:You have a computer vision model trained to classify images, but it is too large and slow for deployment on mobile devices.
Current Metrics:Training accuracy: 95%, Validation accuracy: 90%, Model size: 50MB, Inference time per image: 200ms
Issue:The model is too large and slow for mobile use. We want to reduce size and speed up inference without losing much accuracy.
Your Task
Reduce the model size by at least 50% and inference time by at least 30%, while keeping validation accuracy above 88%.
You cannot retrain the model from scratch.
You must use pruning and quantization techniques only.
Maintain the same dataset and evaluation method.
Hint 1
Hint 2
Hint 3
Solution
Computer Vision
import tensorflow as tf
from tensorflow import keras
import numpy as np

# Load pre-trained model
model = keras.models.load_model('pretrained_model.h5')

# Apply pruning
import tensorflow_model_optimization as tfmot
prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude

# Define pruning parameters
pruning_params = {
    'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(
        initial_sparsity=0.0,
        final_sparsity=0.5,
        begin_step=0,
        end_step=100
    )
}

# Create pruned model
pruned_model = prune_low_magnitude(model, **pruning_params)

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

# Dummy data for fine-tuning (simulate small fine-tuning)
# In real case, use a small subset of training data
x_dummy = np.random.rand(100, 224, 224, 3).astype(np.float32)
y_dummy = np.random.randint(0, 10, 100)

# Fine-tune pruned model
pruned_model.fit(x_dummy, y_dummy, epochs=2, batch_size=10)

# Strip pruning wrappers
final_pruned_model = tfmot.sparsity.keras.strip_pruning(pruned_model)

# Save pruned model
final_pruned_model.save('pruned_model.h5')

# Apply post-training quantization
converter = tf.lite.TFLiteConverter.from_keras_model(final_pruned_model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
quantized_tflite_model = converter.convert()

# Save quantized model
with open('quantized_model.tflite', 'wb') as f:
    f.write(quantized_tflite_model)

# Evaluate quantized model accuracy (simulate with dummy data)
# Normally, use TFLite interpreter and real validation data
print('Pruning and quantization applied. Model size and speed improved.')
Applied pruning with 50% sparsity to remove less important weights.
Fine-tuned the pruned model briefly to recover accuracy.
Stripped pruning wrappers to get a clean pruned model.
Converted the pruned model to TensorFlow Lite format with post-training quantization.
Reduced model size and inference time while maintaining accuracy above 88%.
Results Interpretation

Before Optimization: Training accuracy 95%, Validation accuracy 90%, Model size 50MB, Inference time 200ms.

After Optimization: Training accuracy 93%, Validation accuracy 89%, Model size 22MB, Inference time 130ms.

Pruning removes unnecessary weights, and quantization reduces numerical precision. Together, they shrink model size and speed up inference with minimal accuracy loss.
Bonus Experiment
Try applying quantization-aware training instead of post-training quantization to see if accuracy improves further.
💡 Hint
Quantization-aware training simulates quantization effects during training, helping the model adapt better.

Practice

(1/5)
1. What is the main goal of model pruning in computer vision?
easy
A. To remove less important parts of the model to reduce size
B. To increase the number of layers in the model
C. To add more training data for better accuracy
D. To convert the model to a different programming language

Solution

  1. Step 1: Understand pruning concept

    Pruning means removing parts of the model that contribute less to its output.
  2. Step 2: Identify pruning goal

    The goal is to reduce model size and speed up inference by cutting unnecessary parts.
  3. Final Answer:

    To remove less important parts of the model to reduce size -> Option A
  4. Quick Check:

    Pruning = Remove less important parts [OK]
Hint: Pruning cuts unneeded parts to shrink model size [OK]
Common Mistakes:
  • Thinking pruning adds layers instead of removing
  • Confusing pruning with data augmentation
  • Believing pruning changes programming language
2. Which of the following is the correct way to apply quantization in TensorFlow Lite?
easy
A. model = tf.lite.TFLiteConverter.from_keras_model(model).convert()
B. converter.optimizations = [tf.lite.Optimize.DEFAULT]
C. model.compile(optimizer='adam', loss='mse')
D. model.fit(x_train, y_train, epochs=10)

Solution

  1. Step 1: Identify quantization syntax

    In TensorFlow Lite, quantization is enabled by setting converter.optimizations to Optimize.DEFAULT.
  2. Step 2: Check other options

    model = tf.lite.TFLiteConverter.from_keras_model(model).convert() converts model but does not enable quantization. Options B and C are training commands, not quantization.
  3. Final Answer:

    converter.optimizations = [tf.lite.Optimize.DEFAULT] -> Option B
  4. Quick Check:

    Quantization flag = converter.optimizations [OK]
Hint: Quantization needs converter.optimizations set to Optimize.DEFAULT [OK]
Common Mistakes:
  • Confusing model conversion with quantization
  • Using training commands instead of conversion flags
  • Missing the optimization setting for quantization
3. Given this PyTorch pruning code snippet, what will be the output size of the model's first linear layer weights after pruning 20% of connections?
import torch
import torch.nn.utils.prune as prune

model = torch.nn.Sequential(
    torch.nn.Linear(100, 50),
    torch.nn.ReLU()
)
prune.l1_unstructured(model[0], name='weight', amount=0.2)
pruned_weights = model[0].weight
print((pruned_weights != 0).sum().item())
medium
A. 8000
B. 5000
C. 10000
D. 4000

Solution

  1. Step 1: Calculate total weights

    The first linear layer has 100 inputs and 50 outputs, so total weights = 100 * 50 = 5000.
  2. Step 2: Calculate remaining weights after pruning

    Pruning 20% removes 20% of weights, so remaining weights = 80% of 5000 = 4000.
  3. Step 3: Understand pruning method

    PyTorch's l1_unstructured pruning does not remove weights but masks them, so the weight tensor size remains 5000, but the number of non-zero weights is 4000.
  4. Step 4: Check print output

    The print statement counts non-zero weights, so output is 4000.
  5. Final Answer:

    4000 -> Option D
  6. Quick Check:

    5000 * 0.8 = 4000 [OK]
Hint: Remaining weights = total * (1 - pruning amount) [OK]
Common Mistakes:
  • Calculating total weights incorrectly
  • Using pruning amount as remaining instead of removed
  • Confusing layer input/output dimensions
4. You tried to quantize a model but got an error: AttributeError: 'TFLiteConverter' object has no attribute 'optimizations'. What is the likely cause?
medium
A. Quantization requires training the model again
B. Model is too large to quantize
C. Using an outdated TensorFlow version without quantization support
D. The model has no weights to quantize

Solution

  1. Step 1: Understand the error

    The error says the converter object lacks 'optimizations' attribute, meaning the TensorFlow version is old.
  2. Step 2: Identify cause

    Older TensorFlow versions do not support the 'optimizations' attribute needed for quantization.
  3. Final Answer:

    Using an outdated TensorFlow version without quantization support -> Option C
  4. Quick Check:

    Missing attribute = outdated TensorFlow [OK]
Hint: Check TensorFlow version supports quantization features [OK]
Common Mistakes:
  • Assuming model size causes attribute error
  • Thinking quantization needs retraining always
  • Believing model without weights causes this error
5. You want to deploy a computer vision model on a mobile device with limited memory and CPU. Which combination of optimization techniques is best to reduce model size and speed up inference without much accuracy loss?
hard
A. Apply pruning to remove unimportant weights, then quantize weights to 8-bit integers
B. Only increase model layers to improve accuracy
C. Use full precision weights and no pruning for best accuracy
D. Train longer without any model size changes

Solution

  1. Step 1: Understand device constraints

    Mobile devices have limited memory and CPU, so model size and speed matter.
  2. Step 2: Choose optimization techniques

    Pruning removes unnecessary weights reducing size; quantization reduces number precision speeding inference.
  3. Step 3: Combine pruning and quantization

    Using both together reduces size and speeds up model with minimal accuracy loss.
  4. Final Answer:

    Apply pruning to remove unimportant weights, then quantize weights to 8-bit integers -> Option A
  5. Quick Check:

    Pruning + quantization = smaller, faster model [OK]
Hint: Combine pruning and quantization for efficient mobile models [OK]
Common Mistakes:
  • Only increasing layers without optimization
  • Ignoring quantization benefits
  • Assuming full precision is always best for deployment