预训练模型的层输出意外产生不同的输出

Layer output of a pre-trained model produces different outputs unexpectedly

我有一个 (1, 224, 224, 3) 大小的 numpy 数组,名为 content_image。那就是VGG网络输入的大小。

当我将content_image传输到VGG网络的输入时,如下图所示:

model = vgg19.VGG19(input_tensor=K.variable(content_image), weights='imagenet', include_top=False)

for layer in model .layers:
    if layer.name == 'block5_conv2':
        model_output = layer.output

这似乎产生了 [0, 1]:

规模的产出
[0.06421799 0.07012904 0.         ... 0.         0.05865938
    0.        ]
   [0.21104832 0.27097407 0.         ... 0.         0.
    0.        ] ...

另一方面,当我基于keras documentation(使用VGG19从任意中间层提取特征)应用以下方法时:

from keras.models import Model
base_model = vgg19.VGG19(weights='imagenet'), include_top=False) 
model = Model(inputs=base_model.input, outputs=base_model.get_layer('block5_conv2').output)
model_output = model.predict(content_image)

这种方法似乎产生不同的输出。

[ 82.64436     40.37433    142.94958    ...   0.
     27.992153     0.        ]
   [105.935936    91.84446      0.         ...   0.
     86.96397      0.        ] ...

这两种方法使用具有相同权重的相同网络,并传输相同的 numpy 数组 (content_image) 作为输入,但它们产生不同的输出。我希望它们会产生相同的结果。

我认为如果您在第一种方法中使用 Keras(隐式)创建的会话,您会得到相同的结果:

sess = K.get_session()
with sess.as_default():
    output = model_output.eval()
    print(output)

我认为通过创建一个新会话并使用 init = tf.global_variables_initializer()sess.run(init),您正在更改变量的值。通常,不要创建新会话,而是使用 Keras 创建的会话(除非您有充分的理由不这样做)。