尝试TensorFlow Lite与一个预先训练的Keras图像分类器,我得到了更坏的预测后,将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”,“软涂层”wheaten“terrier”,0.70274395),
('n02091635','otterhound',0.0885325),('n02090721',
0.040120784),(“n02111500”,“比利牛斯山脉”,0.03408164)]
TensorFlow Lite:[[(“n07753275”,“菠萝”,0.94529104),(“n03379051”,
“足球头盔”,0.033994876),(“n03891332”,“停车计时器”,
0.011431991),(n04522168,花瓶,0.002940755),(n02094114,诺福克梗,0.0022089847)]