Home > OS >  How can i make my CNN output a vector of features
How can i make my CNN output a vector of features

Time:03-20

I'm working on a project and i need to make my CNN output like the output of the "Flatten" Layer. No classification just a vector of input photo features, and I'm kind of lost... i know every thing about CNN structure but how can i start doing this with python?

CodePudding user response:

Are you using Keras? If you are, you can take a look here for examples (https://keras.io/api/applications/#extract-features-with-vgg16).

Basically, you do

features = model.predict(x)
np.save(outfile, features) # outfile is your desire output filename

you can load back the file using

features = np.load(outfile)

CodePudding user response:

Another alternative is the following.

Imagine you have a tf Keras model (here I take a small one for the sake of simplicity).

>>> model.summary()

Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_1 (Dense)              (None, 128)               100480
_________________________________________________________________
dense_2 (Dense)              (None, 64)                8256
_________________________________________________________________
dense_3 (Dense)              (None, 32)                2080
_________________________________________________________________
dense_4 (Dense)              (None, 1)                 33
=================================================================
Total params: 110,849
Trainable params: 110,849
Non-trainable params: 0
_________________________________________________________________

Let's say you want a $32$-long feature vector, corresponding to the layer dense_3.

now you can create another object

outputs = model.get_layer('dense_3').output
child_model = tf.keras.Model(inputs = model.inputs, outputs= outputs)

and your child model does what you want. You need to call

features = child_model.predict(image)

Important note: If you print model.layers and child_model.layers you will not be surprised they share the same layers at the same memory addresses. This means training one will set the layers weights of the other.

  • Related