user2552108
user2552108

Reputation: 1150

Keras CNN get output from the Convolutional steps

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

Upvotes: 3

Views: 1411

Answers (1)

hikaru
hikaru

Reputation: 627

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, :, :, :]])

Upvotes: 1

Related Questions