我正在研究一种迁移学习方法,并且在使用 MobileNetV2 时得到了非常不同的结果keras.applications
以及 TensorFlow Hub 上提供的一个。这对我来说似乎很奇怪,因为两个版本都声称here and here从同一检查点提取它们的权重mobilenet_v2_1.0_224。
这是如何重现差异的,你可以找到 Colab Notebookhere:
!pip install tensorflow-gpu==2.1.0
import tensorflow as tf
import numpy as np
import tensorflow_hub as hub
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
def create_model_keras():
image_input = tf.keras.Input(shape=(224, 224, 3))
out = MobileNetV2(input_shape=(224, 224, 3),
include_top=True)(image_input)
model = tf.keras.models.Model(inputs=image_input, outputs=out)
model.compile(optimizer='adam', loss=["categorical_crossentropy"])
return model
def create_model_tf():
image_input = tf.keras.Input(shape=(224, 224 ,3))
out = hub.KerasLayer("https://tfhub.dev/google/tf2-preview/mobilenet_v2/classification/4",
input_shape=(224, 224, 3))(image_input)
model = tf.keras.models.Model(inputs=image_input, outputs=out)
model.compile(optimizer='adam', loss=["categorical_crossentropy"])
return model
当我尝试对随机批次进行预测时,结果不相等:
keras_model = create_model_keras()
tf_model = create_model_tf()
np.random.seed(42)
data = np.random.rand(32,224,224,3)
out_keras = keras_model.predict_on_batch(data)
out_tf = tf_model.predict_on_batch(data)
np.array_equal(out_keras, out_tf)
版本的输出来自keras.applications
总和为 1,但 TensorFlow Hub 的版本不是。而且两个版本的形状也不同:TensorFlow Hub 有 1001 个标签,keras.applications
有 1000 个。
np.sum(out_keras[0]), np.sum(out_tf[0])
prints (1.0000001, -14.166359)
造成这些差异的原因是什么?我错过了什么吗?
编辑 2020年2月18日
正如 Szymon Maszke 指出的,TFHub 版本返回 logits。这就是为什么我添加了一个 Softmax 层create_model_tf
如下:out = tf.keras.layers.Softmax()(x)
arnoegw提到TfHub版本需要将图像标准化为[0,1],而keras版本需要标准化为[-1,1]。当我对测试图像使用以下预处理时:
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
img = tf.keras.preprocessing.image.load_img("/content/panda.jpeg", target_size=(224,224))
img = tf.keras.preprocessing.image.img_to_array(img)
img = preprocess_input(img)
img = tf.io.read_file("/content/panda.jpeg")
img = tf.image.decode_jpeg(img)
img = tf.image.convert_image_dtype(img, tf.float32)
img = tf.image.resize(img, (224,224))
两者都正确预测相同的标签,并且以下条件为真:np.allclose(out_keras, out_tf[:,1:], rtol=0.8)
编辑 2 2020 年 2 月 18 日在我写之前,不可能将格式相互转换。这是由一个错误引起的。