首页 > 解决方案 > 为什么小批量输出到 Mobilenet 与单次输出不同?

问题描述

我正在尝试检查小批量输出是否等于将小批量的所有元素一一给出,以评估 Mobilenet 的特征向量。

看下面的代码:

model = tf.keras.models.Sequential(
    (
        hub.KerasLayer("https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4", 
            output_shape=[1280],
            trainable=False
        ),
    )
)

images =  tf.random.uniform(shape=(20, 224, 224, 3))
features = model.predict(images)

for i in range(20):
    image = tf.reshape(images[i, ...], (1, 224, 224, 3))
    image_feature = model.predict(image)

    self.assertTrue((image_feature == features[i, ...]).all())

assertTrue 在我的测试中失败。它是否应该为所有图像提供相同的特征向量,无论它们是作为小批量还是一张一张地提供?

标签: pythontensorflow2.0tensorflow-hub

解决方案


我想这与模型使用的(BN 层的)均值和方差有关。如果使用来自训练阶段的移动均值和方差(它们应该是,IMO),则单个输出应该与小批量输出完全相同。差异 <= 10e-4 仍然足够大,可以给出不一致的预测。


推荐阅读