Bird
Raised Fist0
TensorFlowml~8 mins

Model optimization (quantization, pruning) in TensorFlow - Model Metrics & Evaluation

Choose your learning style10 modes available
Metrics & Evaluation - Model optimization (quantization, pruning)
Which metric matters for Model optimization (quantization, pruning) and WHY

When optimizing models by quantization or pruning, the key metrics to watch are model size, inference speed, and accuracy or loss. These optimizations reduce model size and speed up predictions but can lower accuracy. So, we measure how much accuracy changes while improving size and speed.

Accuracy or loss tells us if the model still predicts well after optimization. Model size and speed show if the model is smaller and faster, which helps in real-life use on phones or devices with less power.

Confusion matrix or equivalent visualization

For classification tasks, we compare confusion matrices before and after optimization to see if predictions changed.

Before optimization:
| TP=90 | FP=10 |
| FN=5  | TN=95 |

After pruning:
| TP=88 | FP=12 |
| FN=7  | TN=93 |

This shows a slight drop in true positives and increase in false positives, indicating some accuracy loss.
Precision vs Recall tradeoff with concrete examples

Optimization can reduce model quality. For example, pruning might remove weights that help detect rare cases, lowering recall (missing positives). Quantization might reduce precision by making predictions less confident.

Imagine a face recognition app on a phone. We want it fast and small (optimization), but if recall drops too much, it misses faces. If precision drops, it mistakes strangers for friends. We balance size/speed with acceptable precision and recall.

What "good" vs "bad" metric values look like for this use case

Good: Model size reduced by 50% or more, inference time cut in half, and accuracy drops less than 1-2%. Precision and recall remain close to original.

Bad: Model size reduced but accuracy drops 10% or more. Precision or recall fall sharply, causing many wrong or missed predictions. Speed gains are minimal.

Metrics pitfalls
  • Ignoring accuracy drop: Only focusing on size/speed can hide big accuracy loss.
  • Data leakage: Testing on data seen during training can falsely show no accuracy loss.
  • Overfitting to optimization: Tweaking too much on test data can give misleading metrics.
  • Not measuring latency: Speed improvements matter in real use, not just size.
Self-check question

Your model after pruning is 60% smaller and runs twice as fast. But accuracy dropped from 95% to 85%. Is it good for production? Why or why not?

Answer: Probably not good. The 10% accuracy drop is large and may cause many wrong predictions. Speed and size improved, but the model became less reliable. You should try to reduce accuracy loss or test if this drop is acceptable for your use case.

Key Result
Model optimization aims to reduce size and speed while keeping accuracy loss minimal, balancing performance and quality.

Practice

(1/5)
1. What is the main goal of model pruning in TensorFlow model optimization?
easy
A. Remove less important weights to reduce model size
B. Convert model weights to lower precision
C. Add more layers to improve accuracy
D. Increase the batch size during training

Solution

  1. Step 1: Understand pruning concept

    Pruning means removing parts of the model that contribute less, usually weights with small values.
  2. Step 2: Identify pruning effect

    This reduces model size and speeds up inference by making the model simpler.
  3. Final Answer:

    Remove less important weights to reduce model size -> Option A
  4. Quick Check:

    Pruning = Remove less important weights [OK]
Hint: Pruning cuts small weights to shrink model size [OK]
Common Mistakes:
  • Confusing pruning with quantization
  • Thinking pruning adds layers
  • Believing pruning changes batch size
2. Which of the following is the correct way to apply post-training quantization in TensorFlow Lite?
easy
A. converter.optimizations = [tf.lite.Optimize.DEFAULT]
B. model.compile(optimizer='adam', loss='mse')
C. tf.keras.layers.Dense(10, activation='relu')
D. model.fit(x_train, y_train, epochs=10)

Solution

  1. Step 1: Recognize quantization syntax

    Post-training quantization in TensorFlow Lite uses the converter.optimizations property set to [tf.lite.Optimize.DEFAULT].
  2. Step 2: Eliminate unrelated options

    Other options relate to training or model layers, not quantization.
  3. Final Answer:

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

    Quantization uses converter.optimizations = [tf.lite.Optimize.DEFAULT] [OK]
Hint: Quantization uses converter.optimizations setting [OK]
Common Mistakes:
  • Confusing training code with quantization setup
  • Using model.compile for quantization
  • Applying quantization inside model.fit
3. What will be the output shape of the pruned model after applying TensorFlow Model Optimization pruning API on a model with input shape (None, 28, 28, 1) and a Dense layer with 10 units?
medium
A. (None, 28, 28, 10)
B. (None, 10)
C. (None, 28, 28, 1)
D. (10,)

Solution

  1. Step 1: Understand pruning effect on shape

    Pruning removes weights but does not change the model architecture or output shape.
  2. Step 2: Identify output shape of Dense layer

    A Dense layer with 10 units outputs shape (None, 10) regardless of pruning.
  3. Final Answer:

    (None, 10) -> Option B
  4. Quick Check:

    Pruning keeps output shape same = (None, 10) [OK]
Hint: Pruning doesn't change output shape, only weights [OK]
Common Mistakes:
  • Thinking pruning changes output dimensions
  • Confusing input shape with output shape
  • Assuming pruning adds extra dimensions
4. You applied pruning to your TensorFlow model but noticed no size reduction after saving. What is the likely cause?
medium
A. You used quantization instead of pruning
B. Pruning increases model size by adding masks
C. Model was not stripped of pruning wrappers before saving
D. Model was saved in HDF5 format

Solution

  1. Step 1: Understand pruning wrappers

    Pruning adds wrappers around layers that must be stripped before saving to reduce size.
  2. Step 2: Identify saving step

    If wrappers are not stripped, the saved model keeps extra pruning info, so size doesn't reduce.
  3. Final Answer:

    Model was not stripped of pruning wrappers before saving -> Option C
  4. Quick Check:

    Strip pruning wrappers before saving = smaller model [OK]
Hint: Strip pruning wrappers before saving model [OK]
Common Mistakes:
  • Assuming pruning always reduces size without stripping
  • Confusing pruning with quantization effects
  • Ignoring model saving format impact
5. You want to optimize a TensorFlow model for deployment on a mobile device with limited memory and CPU. Which combination of techniques is best to reduce model size and speed up inference without much accuracy loss?
hard
A. Convert model to float64 precision
B. Only increase training epochs without optimization
C. Use dropout layers and batch normalization
D. Apply pruning during training and then post-training quantization

Solution

  1. Step 1: Identify optimization goals

    For mobile deployment, reducing size and speeding inference are key, while keeping accuracy.
  2. Step 2: Choose suitable techniques

    Pruning removes unnecessary weights, quantization reduces number precision, both reduce size and speed up inference.
  3. Step 3: Eliminate wrong options

    Increasing epochs doesn't optimize size; dropout and batch norm are for training regularization; float64 increases size.
  4. Final Answer:

    Apply pruning during training and then post-training quantization -> Option D
  5. Quick Check:

    Pruning + quantization = smaller, faster model [OK]
Hint: Combine pruning and quantization for best optimization [OK]
Common Mistakes:
  • Ignoring quantization after pruning
  • Confusing training tricks with optimization
  • Using higher precision increases size
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