Keras, How to get the output of each layer?

后端 未结 10 1845
借酒劲吻你
借酒劲吻你 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')
    
    0 讨论(0)
  • 2020-11-22 08:08

    From: https://github.com/philipperemy/keras-visualize-activations/blob/master/read_activations.py

    import keras.backend as K
    
    def get_activations(model, model_inputs, print_shape_only=False, layer_name=None):
        print('----- activations -----')
        activations = []
        inp = model.input
    
        model_multi_inputs_cond = True
        if not isinstance(inp, list):
            # only one input! let's wrap it in a list.
            inp = [inp]
            model_multi_inputs_cond = False
    
        outputs = [layer.output for layer in model.layers if
                   layer.name == layer_name or layer_name is None]  # all layer outputs
    
        funcs = [K.function(inp + [K.learning_phase()], [out]) for out in outputs]  # evaluation functions
    
        if model_multi_inputs_cond:
            list_inputs = []
            list_inputs.extend(model_inputs)
            list_inputs.append(0.)
        else:
            list_inputs = [model_inputs, 0.]
    
        # Learning phase. 0 = Test mode (no dropout or batch normalization)
        # layer_outputs = [func([model_inputs, 0.])[0] for func in funcs]
        layer_outputs = [func(list_inputs)[0] for func in funcs]
        for layer_activations in layer_outputs:
            activations.append(layer_activations)
            if print_shape_only:
                print(layer_activations.shape)
            else:
                print(layer_activations)
        return activations
    
    0 讨论(0)
  • 2020-11-22 08:12

    From https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer

    One simple way is to create a new Model that will output the layers that you are interested in:

    from keras.models import Model
    
    model = ...  # include here your original model
    
    layer_name = 'my_layer'
    intermediate_layer_model = Model(inputs=model.input,
                                     outputs=model.get_layer(layer_name).output)
    intermediate_output = intermediate_layer_model.predict(data)
    

    Alternatively, you can build a Keras function that will return the output of a certain layer given a certain input, for example:

    from keras import backend as K
    
    # with a Sequential model
    get_3rd_layer_output = K.function([model.layers[0].input],
                                      [model.layers[3].output])
    layer_output = get_3rd_layer_output([x])[0]
    
    0 讨论(0)
  • 2020-11-22 08:13

    In case you have one of the following cases:

    • error: InvalidArgumentError: input_X:Y is both fed and fetched
    • case of multiple inputs

    You need to do the following changes:

    • add filter out for input layers in outputs variable
    • minnor change on functors loop

    Minimum example:

    from keras.engine.input_layer import InputLayer
    inp = model.input
    outputs = [layer.output for layer in model.layers if not isinstance(layer, InputLayer)]
    functors = [K.function(inp + [K.learning_phase()], [x]) for x in outputs]
    layer_outputs = [fun([x1, x2, xn, 1]) for fun in functors]
    
    0 讨论(0)
提交回复
热议问题