使用 TFLiteConverter 将 Keras 模型转换为量化的 tflite 版本导致 NOTYPE 错误

Ale*_*der 2 quantization keras tensorflow tensorflow-lite google-coral

在转换和执行 keras 模型的 8 位量化时,我遇到了图像数据集没有发生的奇怪错误。

import tensorflow.python.keras.backend as K
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.models import load_model
import numpy as np

x_train = np.array([[0.6171875  0.59791666],[0.6171875  0.59791666],[0.6171875  0.59791666]])
y_train = np.array([[0.6171875  0.59791666],[0.6171875  0.59791666],[0.6171875  0.59791666]])


def representative_dataset_gen():
    for i in range(1):
        # Get sample input data as a numpy array in a method of your choosing.
        sample = np.array([0.5,0.6])
        sample = np.expand_dims(sample, axis=0)
        yield [sample]



model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(2,)),
  tf.keras.layers.Dense(12, activation='relu'),
  tf.keras.layers.Dense(2, activation='softmax')
])


model.compile(optimizer='adam',
              loss='categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=1)

converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter.inference_input_type = tf.float32
converter.inference_output_type = tf.float32
converter.representative_dataset = representative_dataset_gen

tflite_quant_model = converter.convert()

Run Code Online (Sandbox Code Playgroud)

这导致错误

ValueError: Cannot set tensor: Got value of type NOTYPE but expected type FLOAT32 for input 1, name: dense_1_input

这个过程曾经在使用图像数据时起作用,但现在发生了。尝试了不同的 TF 版本,包括每晚 TF2.1。

Ale*_*der 5

显然,问题与输入张量的数据类型有关,默认情况下是 Float64 而不是预期的 Float32。由于 tflite 不了解 Float64,因此将其视为令人困惑的 NOTYPE。

支持的 TF Lite 类型

转换为 float32 解决了这个问题

sample = sample.astype(np.float32)