python - 在 TensorFlow Lite 中运行 Keras 模型时的不同预测
问题描述
使用预训练的 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),('n0209399'Irish'1 , 0.040120784), ('n02111500', 'Great_Pyrenees', 0.03408164)]]
TensorFlow Lite:[[('n07753275', 'pineapple', 0.94529104), ('n03379051', 'football_helmet', 0.033994876), ('n03891332', 'parking_meter', 0.011431991), ('n04522168', 'vase 0.0029440755), ('n02094114', 'Norfolk_terrier', 0.0022089847)]]
解决方案
from_keras_model_file
TensorFlow 1.10中有一个错误。它已在 8 月 9 日的夜间版本中修复。
nightly 可以通过安装pip install tf-nightly
。此外,它将在 TensorFlow 1.11 中修复。
推荐阅读
- javascript - Javascript Promise Chaining - 它被接受了吗?
- c# - IMAP 帐户的 MailItem.Save 异常,“无法执行操作,因为邮件已更改”
- angular - 我想在我的下拉菜单中进行两种方式绑定
- sql - Sql在firebird数据库中选择不同
- c++ - PeekMessageW 函数实际上是在发送消息吗?
- react-native - 反应本机 PanResponder 慢
- maven - 无法将动态值从 eclipse 传递到 POM
- javascript - JS:检查浏览器是否支持焦点选项
- debugging - PhpStorm Xdebug 已连接但未停止
- javascript - 在 vue 组件中使用 bootstrap-daterangepicker