3

I am beginning to build CNN models using Keras.

I have built a CNN with a fairly accurate results using the following architecture.

classifier = Sequential()


classifier.add(Convolution2D(32, (3,3), input_shape = (64, 64, 3), activation='relu'))


classifier.add(MaxPool2D(pool_size = (2,2)))

classifier.add(Convolution2D(32, (3,3), activation='relu'))
classifier.add(MaxPool2D(pool_size = (2,2)))

classifier.add(Convolution2D(32, (3,3), activation='relu'))
classifier.add(MaxPool2D(pool_size = (2,2)))

classifier.add(Convolution2D(32, (3,3), activation='relu'))
classifier.add(MaxPool2D(pool_size = (2,2)))

classifier.add(Flatten())

classifier.add(Dense(units=128, activation='relu'))
classifier.add(Dropout(rate = 0.25))
classifier.add(Dense(units=128, activation='relu'))
classifier.add(Dropout(rate = 0.25))


classifier.add(Dense(units=1, activation='sigmoid'))
classifier.compile(optimizer = 'sgd', loss = 'binary_crossentropy', metrics=['accuracy'])

What I want to do is to run my images through the model, but only the convolutional steps. I am interested in the output of the Flattening process (i.e. get the features from the convolutional steps).

Can someone help me how I can get it in Keras?

Thanks in advance

1 Answer 1

1

Here is one solution. If you are interested in the output of layer 'max_pooling2d_4' (You can get the layer name by classifier.summary(), but I suggest you to put names for each layer by e.g. classifier.add(MaxPool2D(pool_size=(2,2), name='pool1'))):

layer_dict = dict([(layer.name, layer) for layer in classifier.layers])

# input tensor
input_tensor = classifier.input

# output tensor of the given layer
layer_output = layer_dict['max_pooling2d_4'].output

# get the output with respect to the input
func = K.function([input_tensor], [layer_output])

# test image: [64, 64, 3]
image = np.ones((64,64,3))

# get activation for the test image
activation = func([image[np.newaxis, :, :, :]])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.