【发布时间】:2020-06-18 09:15:01
【问题描述】:
在文章末尾查看可能的解决方案
我正在尝试从rcmalli 完全量化 keras-vggface 模型以在 NPU 上运行。该模型是 Keras 模型(不是 tf.keras)。
使用 TF 1.15 进行量化时:
print(tf.version.VERSION)
num_calibration_steps=5
converter = tf.lite.TFLiteConverter.from_keras_model_file('path_to_model.h5')
#converter.post_training_quantize = True # This only makes the weight in8 but does not initialize model quantization
def representative_dataset_gen():
for _ in range(num_calibration_steps):
pfad='path_to_image(s)'
img=cv2.imread(pfad)
# Get sample input data as a numpy array in a method of your choosing.
yield [img]
converter.representative_dataset = representative_dataset_gen
tflite_quant_model = converter.convert()
open("quantized_model", "wb").write(tflite_quant_model)
模型已转换,但由于我需要完整的 int8 量化,我添加:
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.int8 # or tf.uint8
converter.inference_output_type = tf.int8 # or tf.uint8
出现此错误信息:
ValueError:无法设置张量:得到 UINT8 类型的值,但输入 0 的预期类型为 FLOAT32,名称:input_1
很明显,模型的输入还是需要float32的。
问题:
- 我是否必须调整输入 dtype 改变的量化方法?或
- 我必须事先将模型的输入层更改为 dtype int8 吗?
- 或者说实际上是在报告模型实际上没有被量化?
如果 1 或 2 是答案,您是否也有一个最佳实践提示给我?
加法:
使用:
h5_path = 'my_model.h5'
model = keras.models.load_model(h5_path)
model.save(os.getcwd() +'/modelTF2')
使用 TF 2.2 将 h5 保存为 pb 然后使用converter=tf.lite.TFLiteConverter.from_saved_model(saved_model_dir)
因为 TF 2.x tflite 采用浮点数,并将它们转换为 uint8s internally 。我认为这可能是一个解决方案。不幸的是,出现了这个错误信息:
tf.lite.TFLiteConverter.from_keras_model 给'str'对象没有属性'call'
显然 TF2.x 无法处理纯 keras 模型。
使用tf.compat.v1.lite.TFLiteConverter.from_keras_model_file() 解决这个错误只是重复上面的错误,因为我们又回到了“TF 1.15”级别。
加法 2
另一种解决方案是将 keras 模型手动传输到 tf.keras。如果没有其他解决方案,我会考虑。
关于 Meghna Natraj 的评论
要重新创建模型(使用 TF 1.13.x):
pip install git+https://github.com/rcmalli/keras-vggface.git
和
from keras_vggface.vggface import VGGFace
pretrained_model = VGGFace(model='resnet50', include_top=False, input_shape=(224, 224, 3), pooling='avg') # pooling: None, avg or max
pretrained_model.summary()
pretrained_model.save("my_model.h5") #using h5 extension
输入层已连接。太糟糕了,这看起来是一个很好/容易解决的问题。
可能的解决方案
使用 TF 1.15.3 似乎可以工作,我之前使用的是 1.15.0。我会检查我是否不小心做了其他不同的事情。
【问题讨论】:
标签: python tensorflow keras quantization tensorflow-lite