如何在Keras的预训练CNN模型中更改图层的输出?

时间:2020-06-26 20:15:31

标签: python image tensorflow keras conv-neural-network

我正在Keras中运行VGG16进行图像分类,如下所示:

model = VGG16()
image = load_img('mug.jpg', target_size=(224, 224))
image = img_to_array(image)
image = image.reshape((1, image.shape[0], image.shape[1], image.shape[2]))
image = preprocess_input(image)
yhat = model.predict(image)
label = decode_predictions(that)
label = label[0][0]

# print the output
print('%s (%.2f%%)' % (label[1], label[2]*100))

现在,我想查看第一层的输出并对其进行更改/为其添加噪声,并查看分类如何变化。我不确定如何执行此操作,并且找不到与我的查询匹配的任何合适资源。

我是Keras的新手,因此,对此方面的任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:2)

任何层的输出都可以通过

获得
model.layers[index].output

因此您可以这样做

outputlayer1 = model.layers[0].output
outputlayer1 += noise

以后进行向前传递,您可以遍历各层并进行向前传递。有关前向传递,请参阅此链接https://keras.io/api/layers/base_layer/

中的调用函数