【问题标题】:Different predictions when running Keras model in TensorFlow Lite在 TensorFlow Lite 中运行 Keras 模型时的不同预测
【发布时间】:2018-08-22 12:05:13
【问题描述】:

使用预训练的 Keras 图像分类器试用 TensorFlow Lite,在将 H5 转换为 tflite 格式后,我的预测结果变得更糟。这是预期的行为(例如权重量化)、错误还是我在使用解释器时忘记了什么?

示例

from imagesoup import ImageSoup
from tensorflow.keras.applications.resnet50 import ResNet50, preprocess_input, decode_predictions
from tensorflow.keras.preprocessing.image import load_img, img_to_array

# Load an example image.
ImageSoup().search('terrier', n_images=1)[0].to_file('image.jpg')
i = load_img('image.jpg', target_size=(224, 224))
x = img_to_array(i)
x = x[None, ...]
x = preprocess_input(x)

# Classify image with Keras.
model = ResNet50()
y = model.predict(x)
print("Keras:", decode_predictions(y))

# Convert Keras model to TensorFlow Lite.
model.save(f'{model.name}.h5')
converter = tf.contrib.lite.TocoConverter.from_keras_model_file
tflite_model = converter(f'{model.name}.h5').convert()
with open(f'{model.name}.tflite', 'wb') as f:
    f.write(tflite_model)

# Classify image with TensorFlow Lite.
f = tf.contrib.lite.Interpreter(f'{model.name}.tflite')
f.allocate_tensors()
i = f.get_input_details()[0]
o = f.get_output_details()[0]
f.set_tensor(i['index'], x)
f.invoke()
y = f.get_tensor(o['index'])
print("TensorFlow Lite:", decode_predictions(y))

Keras: [[('n02098105', 'soft-coated_wheaten_terrier', 0.70274395), ('n02091635', 'otterhound', 0.0885325), ('n02090721', 'Irish_wolfhound', 0.06422518), ('n02093991', 'Irish_terrier', 0.040120784), ('n02111500', 'Great_Pyrenees', 0.03408164)]]

TensorFlow Lite: [[('n07753275', '菠萝', 0.94529104), ('n03379051', 'football_helmet', 0.033994876), ('n03891332', 'parking_meter', 0.011431991), ('n04522168', '花瓶', 0.0029440755), ('n02094114', 'Norfolk_terrier', 0.0022089847)]]

【问题讨论】:

  • 在 1.10 中 from_keras_model_file 中有一个错误。您可以尝试使用 tf-nightly 版本 (pip install tf-nightly) 运行它吗?
  • 酷。从 1.11.0.dev20180825 开始,现在似乎可以按预期工作。什么是错误?我可以在接受的答案中链接到问题吗?
  • 话虽如此,班级分数仍然略有不同,但至少排名现在是一样的。
  • 我添加了一个附有提交的答案。随意使用它作为接受的答案。

标签: python tensorflow keras tensorflow-lite


【解决方案1】:

TensorFlow 1.10 中的 from_keras_model_file 存在错误。它已在 8 月 9 日的夜间版本this commit 中修复。

nightly 可以通过pip install tf-nightly 安装。此外,它将在 TensorFlow 1.11 中修复。

【讨论】:

    【解决方案2】:

    您是否确保将学习阶段设置为 0,以避免在预测阶段出现 Dropout 和其他非确定性层?

    https://www.tensorflow.org/api_docs/python/tf/keras/backend/learning_phase

    【讨论】:

    • 是的,K.set_learning_phase(0) 没有区别。 Keras 模型的分类正确,而 tflite 模型的分类错误。
    猜你喜欢
    • 1970-01-01
    • 2019-05-14
    • 2018-01-23
    • 1970-01-01
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    相关资源
    最近更新 更多