2

I'm using Keras' pre-trained VGG16 model, and I want to to visualise the output of each layer. However, layer.output returns a tensor object - how can I convert it something that allows me to get the image outputs?

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

Also, when I try to access specific node's output, it returns a tensor:

layer1.get_output_at(0)

Any help is greatly appreciated. Thank you.

matchifang
  • 5,190
  • 12
  • 47
  • 76

1 Answers1

2

You need to evaluate the tensor, which is probably best done by configuring the model to return them when you run predict.

e.g.

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:
   ...

Also check out this blog post, which walks through a possibly similar exercise to what you're attempting: https://blog.keras.io/how-convolutional-neural-networks-see-the-world.html

matchifang
  • 5,190
  • 12
  • 47
  • 76
Mark McDonald
  • 7,571
  • 6
  • 46
  • 53
  • Thank you so much for your answer - I only had to change input=Input(shape=(224,224,3)) to input=model.input or it raises an error. Hope you don't mind if I change that in your answer as well. Again, thank you :) – matchifang Feb 01 '17 at 14:39