如何从 keras 中的张量对象中获取输出?

How can I get the output out of a tensor object in keras?

我正在使用 Keras 的预训练 VGG16 模型,我想可视化每一层的输出。但是,layer.output returns 一个张量对象 - 我怎样才能将它转换为允许我获得图像输出的东西?

model = VGG16(weights='imagenet', include_top=True)
img_path = 'elephant.jpg'
img = image.load_img(img_path, target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)

features = model.predict(x)

layer1 = model.layers[1] #I want the output of the second layer
layer1.output  #returns a tensor object

此外,当我尝试访问特定节点的输出时,它 returns 张量:

layer1.get_output_at(0)

非常感谢任何帮助。谢谢。

您需要评估张量,这可能最好通过在您 运行 预测时将模型配置为 return 它们来完成。

例如

layer_outputs = [layer.output for layer in model.layers]
viz_model = Model(input=model.input, output=layer_outputs)
...
features = viz_model.predict(x)
for feature_map in features:
   ...

另请查看此博客 post,其中介绍了可能与您正在尝试的内容类似的练习:https://blog.keras.io/how-convolutional-neural-networks-see-the-world.html