def output_at_layer(input_image, model, layer_num, verbose=False): """ This function is used to visualize activations at any layer in a Convolutional Neural Network model in Keras. It returns the output image for a given input image at the layer_num layer of the model (layer numbers starting at 1). The model should be Sequential type. This function will not mutate the model. Reference: https://github.com/fchollet/keras/issues/431 The idea is to keep the first layer_num layers of a trained model and remove the rest. Then compile the model and use the predict function to get the ouput. Parameters: ----------- input_image: Image in Numpy format from the dataset model: Name to be used with the load_model() function layer_num: Layer number between 1 and len(model.layers) verbose: Prints layer info Returns: -------- output_image: Numpy array of the output at the layer_num layer """ model_temp = Sequential() model_temp.layers = model.layers[:layer_num] # Truncates layers model_temp.compile(loss=model.loss, optimizer=model.optimizer) # Recompiles model_temp output_image = model_temp.predict(np.array([input_image])) # Uses predict to get ouput if verbose: # Print layer and image info layer = model_temp.layers[layer_num-1] print layer try: print layer.W_shape except: pass print "Image dimensions: " + str(output_image.shape) return output_image