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

时间:2020-07-09 05:31:37

标签: python tensorflow keras tpu google-coral

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

运行代码时
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_compiler对其进行编译。在这种情况下,edgetpu_compiler抱怨说我的模型没有被量化,即使我运行的代码与第一个模型相同。

有人可以向我解释为什么会发生这种错误吗?如果模型的结构不同,是否可以不量化?

1 个答案:

答案 0 :(得分:0)

如果您每晚使用tf或更高版本,则MLIR转换器可能处于打开状态,编译器尚不支持。如果您尝试通过添加以下内容将其关闭,则可能会导致一些奇怪的错误:

converter.experimental_new_converter = False

这可能只是造成您问题的原因!