Keras, How to get the output of each layer?

后端 未结 10 1851
借酒劲吻你
借酒劲吻你 2020-11-22 07:34

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_si         


        
10条回答
  •  心在旅途
    2020-11-22 08:08

    I wrote this function for myself (in Jupyter) and it was inspired by indraforyou's answer. It will plot all the layer outputs automatically. Your images must have a (x, y, 1) shape where 1 stands for 1 channel. You just call plot_layer_outputs(...) to plot.

    %matplotlib inline
    import matplotlib.pyplot as plt
    from keras import backend as K
    
    def get_layer_outputs():
        test_image = YOUR IMAGE GOES HERE!!!
        outputs    = [layer.output for layer in model.layers]          # all layer outputs
        comp_graph = [K.function([model.input]+ [K.learning_phase()], [output]) for output in outputs]  # evaluation functions
    
        # Testing
        layer_outputs_list = [op([test_image, 1.]) for op in comp_graph]
        layer_outputs = []
    
        for layer_output in layer_outputs_list:
            print(layer_output[0][0].shape, end='\n-------------------\n')
            layer_outputs.append(layer_output[0][0])
    
        return layer_outputs
    
    def plot_layer_outputs(layer_number):    
        layer_outputs = get_layer_outputs()
    
        x_max = layer_outputs[layer_number].shape[0]
        y_max = layer_outputs[layer_number].shape[1]
        n     = layer_outputs[layer_number].shape[2]
    
        L = []
        for i in range(n):
            L.append(np.zeros((x_max, y_max)))
    
        for i in range(n):
            for x in range(x_max):
                for y in range(y_max):
                    L[i][x][y] = layer_outputs[layer_number][x][y][i]
    
    
        for img in L:
            plt.figure()
            plt.imshow(img, interpolation='nearest')
    

提交回复
热议问题