2

I need to use VGG pretrained model for feature extraction from an image. Also I need to get the output from the 1st and 5th layer of the VGG pretrained model. Is it really possible to do so?

If yes, can anyone provide the working code?

Edit: I downloaded the pretrained model as

model = VGG16()

Then I predicted it with an image as:

model.predict(image)

Now I want to get the output of the intermediate layers(The 1st convolutional and 5th convolutional layer) as:

x=model.layers[5].output

but it yields a empty matrix when I convert the tensor. What is the problem in the code?

N.B: I need an output matrix not a tensor

Hamsa
  • 476
  • 5
  • 23
  • yes it is possible. – WiseDev Jul 03 '19 at 08:58
  • Can you provide a code for the same. – Hamsa Jul 03 '19 at 09:01
  • I forgot how it was exactly. assign something like model.output and model.input to specific parts of your networks and then propagate data. But I'm sure this question is a duplicate – WiseDev Jul 03 '19 at 09:03
  • @BlueRineS have edited the question according to my problem. I followed [keras-how-to-get-the-output-of-each-layer](https://stackoverflow.com/questions/41711190/keras-how-to-get-the-output-of-each-layer) but it is not the answer I need. I see they are not predicting from their model. – Hamsa Jul 03 '19 at 10:06
  • Actually I need a matrix not a tensor. – Hamsa Jul 03 '19 at 10:13
  • Maybe try the model.output code before you call predict() ? – WiseDev Jul 03 '19 at 10:33
  • It doesn't help either, produces output ```Tensor("block1_conv1/Relu:0", shape=(?, 224, 224, 64), dtype=float32)``` I want the matrix as an output – Hamsa Jul 03 '19 at 10:55
  • Then convert the tensor to a numpy array. `from keras import backend as K; K.tf.get_value(tensor)` – WiseDev Jul 03 '19 at 10:56
  • It doesn't help either. You can test yourself. – Hamsa Jul 03 '19 at 11:25
  • what does it output? – WiseDev Jul 03 '19 at 11:48

1 Answers1

4

Create a new model taking the layers you want.

newModel = Model(model.inputs, 
                 [model.layers[5].output, model.layers[i].output])

Predict from the new model:

layer5, layerI = newModel.predict(imageS)
Daniel Möller
  • 84,878
  • 18
  • 192
  • 214