问题描述
我正在对 SSD 模型应用量化。附上要点。加载模型时添加了一个名为“AnchorBoxes”的自定义对象。当我不进行量化时,这很好用。但是当我应用量化时,无法识别这个自定义对象。
我尝试了解决方法。
def apply_quantization_to_conv2D(layer):
#print(layer)
if isinstance(layer,tf.keras.layers.Conv2D):
return tfmot.quantization.keras.quantize_annotate_layer(layer)
return layer
# Use `tf.keras.models.clone_model` to apply `apply_quantization_to_dense`
# to the layers of the model.
annotated_model = tf.keras.models.clone_model(
model,clone_function=apply_quantization_to_conv2D,)
#annotated_model.save('quantize_ready_model_20_01_Conv2D.h5',include_optimizer=True)
annotated_model.summary()
# Now that the Dense layers are annotated,# `quantize_apply` actually makes the model quantization aware.
#quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)
我在上面的代码中注释了这行 quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)
,因为它抛出了错误 ValueError: UnkNown layer: AnchorBoxes
相反,我在对 Conv2D 层应用量化后保存了模型,如下所示
def apply_quantization_to_conv2D(layer):
#print(layer)
if isinstance(layer,)
annotated_model.summary()
annotated_model.save('quantize_ready_model_20_01_Conv2D_1.h5',include_optimizer=True)
# Now that the Dense layers are annotated,# `quantize_apply` actually makes the model quantization aware.
#quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)
#quant_aware_model.compile(optimizer=adam,loss=ssd_loss.compute_loss)
#quant_aware_model.summary()
然后我加载模型,希望加载的量化模型如下所示将附加 custom_objects。
with tfmot.quantization.keras.quantize_scope():
loaded_model = tf.keras.models.load_model('./quantize_ready_model_20_01_Conv2D_1.h5',custom_objects={'AnchorBoxes': AnchorBoxes})
最后,我将 quantize_apply
应用于具有量化层的新 loaded_model
。
quant_aware_model = tfmot.quantization.keras.quantize_apply(loaded_model)
再次导致相同的错误
ValueError: UnkNown layer: AnchorBoxes
系统信息
TensorFlow 版本(从源代码或二进制安装):TF 2.0.0
TensorFlow 模型优化版本(从源代码或二进制文件安装):0.5.0
描述预期行为
当我运行 quantize_apply(model) 时,模型应该能够感知量化
解决方法
在下面的代码中传递像 AnchorBoxes': AnchorBoxes
这样的自定义层后,问题得到解决。
with quantize_scope(
{'DefaultDenseQuantizeConfig': DefaultDenseQuantizeConfig,'AnchorBoxes': AnchorBoxes}):
# Use `quantize_apply` to actually make the model quantization aware.
quant_aware_model = tfmot.quantization.keras.quantize_apply(annotated_model)