导入预训练模型进行推理。以mobilenetv2 Imagenet预训练模型为例:
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
# 加载图片
image = tf.image.decode_image(tf.io.read_file('/path/to/your/image'),channels=3)
image = tf.image.resize(image,(224,224))
image = tf.expand_dims(image, axis=0)
# Keras预测
i = tf.keras.layers.Input([224, 224, 3], dtype = tf.uint8)
x = tf.cast(i, tf.float32)
x = tf.keras.applications.mobilenet.preprocess_input(x)
core = tf.keras.applications.MobileNetV2()
x = core(x)
model = tf.keras.Model(inputs=[i], outputs=[x])
preds = model(image).numpy()
print(tf.keras.applications.mobilenet_v2.decode_predictions(preds, top=5))
# TFHub预测
path = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4"
IMAGE_SHAPE = (224, 224)
tfhub_model = tf.keras.Sequential([
hub.KerasLayer(path, input_shape=IMAGE_SHAPE+(3,), outpu