Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AI and Deep Learning by (50.2k points)

I have trained a binary classification model with CNN, and here is my code

model = Sequential()

model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1],border_mode='valid',input_shape=input_shape))

model.add(Activation('relu'))

model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1]))

model.add(Activation('relu'))

model.add(MaxPooling2D(pool_size=pool_size))

# (16, 16, 32)

model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))

model.add(Activation('relu'))

model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1]))

model.add(Activation('relu'))

model.add(MaxPooling2D(pool_size=pool_size))

# (8, 8, 64) = (2048)

model.add(Flatten())

model.add(Dense(1024))

model.add(Activation('relu'))

model.add(Dropout(0.5))

model.add(Dense(2))  # define a binary classification problem

model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy,optimizer='adadelta',

metrics=['accuracy'])

model.fit(x_train,y_train,batch_size=batch_size,nb_epoch=nb_epoch,verbose=1,validation_data=(x_test, y_test))

And here, I wanna get the output of each layer just like TensorFlow, how can I do that?

1 Answer

0 votes
by (108k points)
edited by

You can easily get the output of any layer in Keras by using the following syntax:

Model.layers[index].output

For all layers refer the following piece of code:

from keras import backend as K

input1 = model.input               # input placeholder

output1 = [layer.output for layer in model.layers]# all layer outputs

fun = K.function([input1, K.learning_phase()],output1)# evaluation function

# Testing

t = np.random.random(input_shape)[np.newaxis,...]

layer_outputs = fun([t, 1.])

print layer_outputs// printing the outputs of layers

K.function creates theano/TensorFlow tensor functions which are later used to get the output from the symbolic graph given the input. The model builds the predict function using K.function.

Now K.learning_phase() is required as an input as many Keras layers like Dropout/Batchnomalization depend on it to change behavior during training and test time.

 You can take reference from the following link:

the output of an intermediate layer in Keras.

If you wish to learn more about AI, visit Artificial Intelligence Tutorial and Artificial Intelligence Course by Intellipaat. 

Watch this video to know more about Keras:

Browse Categories

...