首页 > 解决方案 > 如何在 Keras 的预训练 CNN 模型中更改层的输出?

问题描述

我在 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 的新手,所以在这方面的任何帮助将不胜感激。谢谢你!

标签: pythonimagetensorflowkerasconv-neural-network

解决方案


任何层的输出都可以通过

model.layers[index].output

所以在你的情况下你可以做

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

稍后要进行前向传递,您可以遍历图层并进行前向传递。对于前向传递,请参阅此链接中的调用函数https://keras.io/api/layers/base_layer/


推荐阅读