Complete the code to apply post-training quantization to a TensorFlow model.
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [[1]]
tflite_model = converter.convert()Using tf.lite.Optimize.DEFAULT enables default optimizations including quantization.
Complete the code to prune a Keras model during training using TensorFlow Model Optimization Toolkit.
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)The prune_low_magnitude function expects a pruning_schedule argument to control pruning behavior.
Fix the error in the code to correctly strip pruning wrappers after training.
model_for_export = tfmot.sparsity.keras.strip_pruning([1])After pruning, the model wrapped with pruning layers is model_for_pruning. This must be stripped before export.
Fill both blanks to create a pruning callback and apply it during model training.
callbacks = [tfmot.sparsity.keras.UpdatePruningStep(), tfmot.sparsity.keras.[1](log_dir='logs')] model_for_pruning.fit(x_train, y_train, epochs=5, callbacks=[2])
The PruningSummaries callback logs pruning summaries during training and must be included in callbacks.
Fill all three blanks to convert a pruned and stripped Keras model to a quantized TFLite model.
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])
First, use the stripped model model_for_export to create the converter. Then set optimization to tf.lite.Optimize.DEFAULT for quantization. Finally, write the converted model tflite_quant_model to file.
