Model optimization helps make machine learning models smaller and faster. This is useful to run models on devices like phones or tablets.
Model optimization (quantization, pruning) in TensorFlow
import tensorflow_model_optimization as tfmot # For pruning pruning_params = { 'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay( initial_sparsity=0.0, final_sparsity=0.5, begin_step=0, end_step=end_step ) } model = tfmot.sparsity.keras.prune_low_magnitude(model, **pruning_params) # For quantization aware training quantize_model = tfmot.quantization.keras.quantize_model quantized_model = quantize_model(model)
Pruning removes less important connections to make the model sparse.
Quantization reduces the precision of numbers to make the model smaller and faster.
import tensorflow_model_optimization as tfmot # Pruning example pruning_params = { 'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay( initial_sparsity=0.0, final_sparsity=0.3, begin_step=0, end_step=1000 ) } pruned_model = tfmot.sparsity.keras.prune_low_magnitude(model, **pruning_params)
import tensorflow_model_optimization as tfmot # Quantization aware training example quantize_model = tfmot.quantization.keras.quantize_model quantized_model = quantize_model(model)
This program trains a simple model on MNIST data, then applies pruning to reduce model size. It shows accuracy before and after pruning.
import tensorflow as tf import tensorflow_model_optimization as tfmot # Load example data mnist = tf.keras.datasets.mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train, x_test = x_train / 255.0, x_test / 255.0 # Simple model model = tf.keras.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10) ]) model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) # Train original model model.fit(x_train, y_train, epochs=1, verbose=0) # Evaluate original model loss, acc = model.evaluate(x_test, y_test, verbose=0) # Pruning setup batch_size = 128 epochs = 2 validation_split = 0.1 num_images = x_train.shape[0] * (1 - validation_split) end_step = int(num_images / batch_size) * epochs pruning_params = { 'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay( initial_sparsity=0.0, final_sparsity=0.5, begin_step=0, end_step=end_step ) } # Apply pruning pruned_model = tfmot.sparsity.keras.prune_low_magnitude(model, **pruning_params) pruned_model.compile(optimizer='adam', loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) callbacks = [tfmot.sparsity.keras.UpdatePruningStep()] # Train pruned model pruned_model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_split=validation_split, callbacks=callbacks, verbose=0) # Evaluate pruned model loss_pruned, acc_pruned = pruned_model.evaluate(x_test, y_test, verbose=0) print(f"Original model accuracy: {acc:.4f}") print(f"Pruned model accuracy: {acc_pruned:.4f}")
Pruning usually requires retraining the model to keep accuracy.
Quantization can be done after training or during training (quantization aware training).
Always test your optimized model to check if accuracy is still good enough.
Model optimization makes models smaller and faster for devices with limited resources.
Pruning removes less important parts of the model to reduce size.
Quantization reduces number precision to speed up the model.
Practice
model pruning in TensorFlow model optimization?Solution
Step 1: Understand pruning concept
Pruning means removing parts of the model that contribute less, usually weights with small values.Step 2: Identify pruning effect
This reduces model size and speeds up inference by making the model simpler.Final Answer:
Remove less important weights to reduce model size -> Option AQuick Check:
Pruning = Remove less important weights [OK]
- Confusing pruning with quantization
- Thinking pruning adds layers
- Believing pruning changes batch size
Solution
Step 1: Recognize quantization syntax
Post-training quantization in TensorFlow Lite uses the converter.optimizations property set to [tf.lite.Optimize.DEFAULT].Step 2: Eliminate unrelated options
Other options relate to training or model layers, not quantization.Final Answer:
converter.optimizations = [tf.lite.Optimize.DEFAULT] -> Option AQuick Check:
Quantization uses converter.optimizations = [tf.lite.Optimize.DEFAULT] [OK]
- Confusing training code with quantization setup
- Using model.compile for quantization
- Applying quantization inside model.fit
Solution
Step 1: Understand pruning effect on shape
Pruning removes weights but does not change the model architecture or output shape.Step 2: Identify output shape of Dense layer
A Dense layer with 10 units outputs shape (None, 10) regardless of pruning.Final Answer:
(None, 10) -> Option BQuick Check:
Pruning keeps output shape same = (None, 10) [OK]
- Thinking pruning changes output dimensions
- Confusing input shape with output shape
- Assuming pruning adds extra dimensions
Solution
Step 1: Understand pruning wrappers
Pruning adds wrappers around layers that must be stripped before saving to reduce size.Step 2: Identify saving step
If wrappers are not stripped, the saved model keeps extra pruning info, so size doesn't reduce.Final Answer:
Model was not stripped of pruning wrappers before saving -> Option CQuick Check:
Strip pruning wrappers before saving = smaller model [OK]
- Assuming pruning always reduces size without stripping
- Confusing pruning with quantization effects
- Ignoring model saving format impact
Solution
Step 1: Identify optimization goals
For mobile deployment, reducing size and speeding inference are key, while keeping accuracy.Step 2: Choose suitable techniques
Pruning removes unnecessary weights, quantization reduces number precision, both reduce size and speed up inference.Step 3: Eliminate wrong options
Increasing epochs doesn't optimize size; dropout and batch norm are for training regularization; float64 increases size.Final Answer:
Apply pruning during training and then post-training quantization -> Option DQuick Check:
Pruning + quantization = smaller, faster model [OK]
- Ignoring quantization after pruning
- Confusing training tricks with optimization
- Using higher precision increases size
Ready to prove it?
Pass the test and this pattern moves unknown
