【问题标题】:Converting Keras model with TFLiteConverter to quantized tflite version results in NOTYPE error使用 TFLiteConverter 将 Keras 模型转换为量化的 tflite 版本会导致 NOTYPE 错误
【发布时间】:2020-01-22 09:02:45
【问题描述】:

在转换和执行 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()

这会导致错误

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

此过程过去在使用图像数据时有效,但现在发生了这种情况。尝试了不同的 TF 版本,包括 nightly TF2.1。

【问题讨论】:

    标签: tensorflow keras quantization google-coral tensorflow-lite


    【解决方案1】:

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

    Supported TF Lite Types

    强制转换为 float32 可以解决问题

    sample = sample.astype(np.float32)

    【讨论】:

    • 非常感谢你救了我的命。为什么 tensorflow 没有说不支持 FLOAT64,它会在互联网上的任何地方被提升为 NOTYPE T.T. 再次感谢
    猜你喜欢
    • 1970-01-01
    • 2020-09-15
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多