Bird
Raised Fist0
TensorFlowml~10 mins

Model optimization (quantization, pruning) in TensorFlow - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to apply post-training quantization to a TensorFlow model.

TensorFlow
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [[1]]
tflite_model = converter.convert()
Drag options to blanks, or click blank then click option'
Atf.lite.Optimize.DEFAULT
Btf.lite.Optimize.NONE
Ctf.lite.Optimize.SIZE
Dtf.lite.Optimize.SPEED
Attempts:
3 left
💡 Hint
Common Mistakes
Using NONE disables optimization, so no quantization happens.
Choosing SIZE or SPEED alone may not enable full default quantization.
2fill in blank
medium

Complete the code to prune a Keras model during training using TensorFlow Model Optimization Toolkit.

TensorFlow
prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude
pruning_params = {'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.0, final_sparsity=0.5, begin_step=0, end_step=1000)}
model_for_pruning = prune_low_magnitude(model, [1]=pruning_params)
Drag options to blanks, or click blank then click option'
Aprune_schedule
Bpruning_params
Cschedule
Dpruning_schedule
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect parameter names like 'pruning_params' or 'schedule' causes errors.
Passing the whole dictionary without the correct key.
3fill in blank
hard

Fix the error in the code to correctly strip pruning wrappers after training.

TensorFlow
model_for_export = tfmot.sparsity.keras.strip_pruning([1])
Drag options to blanks, or click blank then click option'
Apruned_model
Bmodel
Cmodel_for_pruning
Dmodel_for_training
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the original model without pruning wrappers causes errors.
Using an undefined variable name.
4fill in blank
hard

Fill both blanks to create a pruning callback and apply it during model training.

TensorFlow
callbacks = [tfmot.sparsity.keras.UpdatePruningStep(), tfmot.sparsity.keras.[1](log_dir='logs')]
model_for_pruning.fit(x_train, y_train, epochs=5, callbacks=[2])
Drag options to blanks, or click blank then click option'
APruningSummaries
BPruningCallback
CPruningLogger
DPruningMonitor
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent callback name causes errors.
Not passing the callbacks list to fit disables pruning updates.
5fill in blank
hard

Fill all three blanks to convert a pruned and stripped Keras model to a quantized TFLite model.

TensorFlow
converter = tf.lite.TFLiteConverter.from_keras_model([1])
converter.optimizations = [[2]]
tflite_quant_model = converter.convert()
with open('quantized_model.tflite', 'wb') as f:
    f.write([3])
Drag options to blanks, or click blank then click option'
Amodel_for_export
Btf.lite.Optimize.DEFAULT
Ctflite_quant_model
Dmodel_for_pruning
Attempts:
3 left
💡 Hint
Common Mistakes
Using the pruned model with wrappers causes conversion errors.
Not setting optimization disables quantization.
Writing the wrong variable to file causes empty or invalid files.

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