7

我在 tensorflow 上使用带有 python 3 和 keras 的 ubuntu,我正在尝试使用来自预训练的 keras 模型的迁移学习来创建一个模型,如下所述

我正在使用以下代码

import numpy as np
from keras.applications import vgg16, inception_v3, resnet50, mobilenet
from keras import Model

a = np.random.rand(1, 224, 224, 3) + 0.001
a = mobilenet.preprocess_input(a)

mobilenet_model = mobilenet.MobileNet(weights='imagenet')

mobilenet_model.summary()
inputLayer = mobilenet_model.input

m = Model(input=inputLayer, outputs=mobilenet_model.get_layer("conv_pw_13_relu")(inputLayer))
m.set_weights(mobilenet_model.get_weights()[:len(m.get_weights())])
p = m.predict(a)
print(np.std(p), np.mean(p))
print(p.shape)

我正在使用的层的输出始终是一个零数组,我是否应该将权重加载到我正在创建的 p 以使预训练模型实际工作?

4

2 回答 2

13

Keras 中的层和这些层的输出之间存在差异。您可以将层视为表示计算,将输出视为这些计算的结果。当您实例化一个Model对象时,它期望计算的结果作为它的输出,而不是计算本身,因此会出现错误。要修复它,您可以将图层的输出传递给Model构造函数:

import numpy as np
from keras.applications import vgg16, inception_v3, resnet50, mobilenet
from keras import Model

a = np.random.rand(24, 224, 224, 3)
a = mobilenet.preprocess_input(a)

mobilenet_model = mobilenet.MobileNet(weights='imagenet')

mobilenet_model.summary()

model_output = mobilenet_model.get_layer("conv_pw_13_relu").output
m = Model(inputs=mobilenet_model.input, outputs=model_output)
print(m.predict(a))
于 2018-08-21T13:18:32.367 回答
2

为了访问 Keras 模型中中间层的输出,Keras 提供了不同的方式。

在您的情况下,您可以像这样输出所需的图层

model_out = mobilenet_model.get_layer("layer_you_want").output
m = Model(input=inputLayer, outputs=model_out)

有关此方法和其他可用方法的更多详细信息,请查看文档

于 2018-08-21T13:17:22.840 回答