Sub topic 10
Checking Accuracy After Quantization and Conversion
Assume you know Python, tensors, image preprocessing, and basic image classification. You should also know how to run a model with PyTorch or TensorFlow. This chapter uses TensorFlow Lite, but the validation method also applies to ONNX and other deployment formats.
Quantization changes numerical values. Conversion can also change operators, layouts, or preprocessing assumptions. A model that runs successfully is not necessarily an accurate model. Compare the deployed model with the original model on the same test examples.
Build a repeatable comparison
Use a held-out validation set that represents real inputs. Do not validate only on the training data. Keep these details identical between models:
- Image files and labels.
- Resize and crop rules.
- Color channel order, such as RGB or BGR.
- Normalization range and mean and standard deviation.
- Class ordering.
- Output interpretation.
The float model is the reference. Run the same examples through the float model and the converted model, then compare predictions and task metrics.
For classification, measure top-1 accuracy, top-5 accuracy, and a confusion matrix. Also record how often the float and edge models choose different top-1 classes. A small output difference is acceptable when the predicted class remains the same. A class change near the decision boundary may be harmless, while a systematic class change indicates a problem.
For object detection, compare precision, recall, and mean average precision. Match predicted boxes to reference boxes with an intersection-over-union threshold. For segmentation, compare intersection over union or mean pixel accuracy. Use task-level metrics rather than only comparing raw tensors.
Compare an integer model with its float baseline
The following example evaluates a quantized TensorFlow Lite classifier. It assumes images.npy contains preprocessed images with the model's expected input shape and labels.npy contains integer class IDs. The float and quantized models must receive equivalent inputs. If the quantized model expects uint8, quantize the inputs with the input tensor's scale and zero point.
import numpy as np
import tensorflow as tf
def evaluate_tflite(path, images, labels):
interpreter = tf.lite.Interpreter(model_path=path)
interpreter.allocate_tensors()
input_info = interpreter.get_input_details()[0]
output_info = interpreter.get_output_details()[0]
scale, zero_point = input_info["quantization"]
predictions = []
for image in images:
if input_info["dtype"] == np.uint8:
image = np.round(image / scale + zero_point)
image = np.clip(image, 0, 255).astype(np.uint8)
else:
image = image.astype(input_info["dtype"])
interpreter.set_tensor(input_info["index"], image[None, ...])
interpreter.invoke()
output = interpreter.get_tensor(output_info["index"])
output_scale, output_zero = output_info["quantization"]
if output_scale:
output = (output.astype(np.float32) - output_zero) * output_scale
predictions.append(int(output.argmax()))
predictions = np.array(predictions)
return np.mean(predictions == labels), predictions
images = np.load("images.npy").astype(np.float32)
labels = np.load("labels.npy").astype(np.int64)
float_accuracy, float_predictions = evaluate_tflite(
"model_float.tflite", images, labels
)
int8_accuracy, int8_predictions = evaluate_tflite(
"model_int8.tflite", images, labels
)
changed = np.mean(float_predictions != int8_predictions)
print(f"float accuracy: {float_accuracy:.4f}")
print(f"int8 accuracy: {int8_accuracy:.4f}")
print(f"changed top-1 predictions: {changed:.4f}")The input quantization formula is:
quantized = round(real_value / scale + zero_point)
The dequantization formula reverses it:
real_value = (quantized - zero_point) * scale
Never assume that every tensor uses the same scale. Read the scale and zero point from the model metadata.
Interpret failures
Set an acceptance threshold before testing. For example, require int8 top-1 accuracy to be within 1 percentage point of the float model. Inspect errors by class, lighting condition, image size, and confidence. If only a few classes fail, inspect their activation ranges and calibration examples.
Post-training quantization usually works well when calibration data resembles production data. Use quantization-aware training when the accuracy loss remains too large, sensitive layers saturate, or the model contains operations that are difficult to quantize. Quantization-aware training simulates low-precision effects during training so the model can adapt.
Also test the converted model on multiple device runtimes. Different delegates can use different kernels or fall back to CPU, so numerical results and speed may vary.
Exercise
The float model has 90% accuracy and the int8 model has 78%. What should you check first?
Show answer
Check that input preprocessing, quantization parameters, label ordering, output decoding, and calibration data match the float evaluation before changing the model.