训练后的“模型未量化”量化取决于模型结构?

2024-04-26 01:06:58 发布

您现在位置:Python中文网/ 问答频道 /正文

训练后的量化似乎适用于某些模型结构,而不适用于其他模型结构。例如,当我使用

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation='relu'),
    keras.layers.Dense(10)
])

# Train the digit classification model
model.compile(optimizer='adam',
              loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(train_images, train_labels, epochs=2)

岗位培训量化为:

converter = tf.lite.TFLiteConverter.from_keras_model(model)
# This enables quantization
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_types = [tf.int8]
# This ensures that if any ops can't be quantized, the converter throws an error
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
# These set the input and output tensors to uint8 (added in r2.3)
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
# And this sets the representative dataset so we can quantize the activations
converter.representative_dataset = representative_data_gen


tflite_model = converter.convert()

with open('my_mnist_quant.tflite', 'wb') as f:
    f.write(tflite_model)
    

! edgetpu_compiler my_mnist_quant.tflite命令工作得非常好,创建的tflite模型的性能与我在服务器上培训的模型相当

但是,当我将模型更改为

model = keras.Sequential([
  keras.layers.InputLayer(input_shape=(28, 28)),
  keras.layers.Reshape(target_shape=(28, 28, 1)),
  keras.layers.Conv2D(64, kernel_size=3, activation='relu', input_shape=(28,28,1)),
  keras.layers.Flatten(),
  keras.layers.Dense(10, activation='softmax')
])

我所做的只是在我的模型中添加一个卷积层和一些重塑层。然而,当我用这个模型运行量化时,一切都很好,直到我尝试用edgetpu_编译器编译它。在这种情况下,edgetpu_编译器抱怨说我的模型没有量化,尽管我运行的代码与第一个模型完全相同

有人能解释一下为什么会发生这种错误吗?当一个模型是一个不同的结构时,它不能被量化吗


Tags: the模型targetinputmodellayerstflite
1条回答
网友
1楼 · 发布于 2024-04-26 01:06:58

如果您使用的是tf nightly或更新版本,则MLIR转换器可能已打开,但编译器尚不支持此功能。这可能会导致一些奇怪的错误,如果您尝试通过添加以下内容来关闭它:

converter.experimental_new_converter = False

这可能就是你问题的原因

相关问题 更多 >