【问题标题】:Keras, How to get the output of each layer?Keras,如何获得每一层的输出?
【发布时间】:2017-06-02 08:17:57
【问题描述】:

我已经用 CNN 训练了一个二元分类模型,这是我的代码

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))

在这里,我想像 TensorFlow 一样获取每一层的输出,我该怎么做?

【问题讨论】:

    标签: python tensorflow deep-learning keras


    【解决方案1】:

    您可以使用以下命令轻松获取任何层的输出:model.layers[index].output

    所有层都使用这个:

    from keras import backend as K
    
    inp = model.input                                           # input placeholder
    outputs = [layer.output for layer in model.layers]          # all layer outputs
    functors = [K.function([inp, K.learning_phase()], [out]) for out in outputs]    # evaluation functions
    
    # Testing
    test = np.random.random(input_shape)[np.newaxis,...]
    layer_outs = [func([test, 1.]) for func in functors]
    print layer_outs
    

    注意:要模拟 Dropout,在 layer_outs 中使用 learning_phase 作为 1.,否则使用 0.

    编辑:(基于 cmets)

    K.function 创建 theano/tensorflow 张量函数,稍后用于在给定输入的情况下从符号图中获取输出。

    现在需要K.learning_phase() 作为输入,因为许多 Keras 层(例如 Dropout/Batchnomalization)依赖它来改变训练和测试期间的行为。

    因此,如果您删除代码中的 dropout 层,您可以简单地使用:

    from keras import backend as K
    
    inp = model.input                                           # input placeholder
    outputs = [layer.output for layer in model.layers]          # all layer outputs
    functors = [K.function([inp], [out]) for out in outputs]    # evaluation functions
    
    # Testing
    test = np.random.random(input_shape)[np.newaxis,...]
    layer_outs = [func([test]) for func in functors]
    print layer_outs
    

    编辑 2:更优化

    我刚刚意识到,之前的答案并没有优化,因为对于每个函数评估,数据将被传输到 CPU->GPU 内存,并且还需要对较低层进行张量计算。

    相反,这是一种更好的方法,因为您不需要多个函数,而是一个函数为您提供所有输出的列表:

    from keras import backend as K
    
    inp = model.input                                           # input placeholder
    outputs = [layer.output for layer in model.layers]          # all layer outputs
    functor = K.function([inp, K.learning_phase()], outputs )   # evaluation function
    
    # Testing
    test = np.random.random(input_shape)[np.newaxis,...]
    layer_outs = functor([test, 1.])
    print layer_outs
    

    【讨论】:

    • 先生,您的回答很好,您的代码中K.function([inp]+ [K.learning_phase()], [out]) 是什么意思?
    • 优秀答案,np.random.random(input_shape)[np.newaxis,...]也可以写成np.random.random(input_shape)[np.newaxis,:]
    • @StavBodik 模型使用K.function here 构建预测函数,并在预测循环here 中使用它。预测批量大小的循环(如果未设置,则默认为 32),但这是为了减轻对 GPU 内存的限制。所以我不确定你为什么观察model.predict 更快。
    • 我得到了这个:InvalidArgumentError: S_input_39:0 既被输入又被提取。 ...有想法的人吗?
    • 错误:ValueError:函数的输入张量必须来自tf.keras.Input。已接收:0(缺少前一层元数据)。简单模型:inputs = tf.keras.layers.Input(shape=input_shape) x = tf.keras.layers.Dense(256, activation=None)(inputs) model = tf.keras.Model(inputs=inputs, outputs= X)。 tf 版本 2.5.0.只有第一种方法有效。
    【解决方案2】:

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

    一种简单的方法是创建一个新模型,该模型将输出您感兴趣的层:

    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)
    

    或者,您可以构建一个 Keras 函数,该函数将在给定特定输入的情况下返回特定层的输出,例如:

    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]
    

    【讨论】:

    • 如果可以的话,我会给你两个^,当你有一堆输入时,这种方式会方便得多。
    • 从上面的代码中可以很清楚地看到,但只是为了仔细检查我的理解:从现有模型创建模型后(假设它已经训练过),不需要在新模型上调用 set_weights 。对吗?
    • layer_output = get_3rd_layer_output([X, 0])[0]layer_output = get_3rd_layer_output([X, 1])[0] 的区别是什么?文档中提到了训练模式和测试模式
    • 对不起,你能解释一下这个模型到底是做什么的吗?你也必须训练它吗?我无法想象任何图表。您添加另一个模型的输入层,然后添加另一个模型的随机中间层作为输出,并将输入提供给它?为什么这样做而不是提供原始模型并直接访问它所在的任何中间层?为什么要创建这个特别奇怪的模型?不会影响输出吗?它不会尝试学习或需要训练,或者该层会从原始模型中带来自己的权重吗?
    【解决方案3】:

    基于这个线程的所有好的答案,我编写了一个库来获取每一层的输出。它抽象了所有的复杂性,并被设计为尽可能用户友好:

    https://github.com/philipperemy/keract

    它处理几乎所有的边缘情况。

    希望对你有帮助!

    【讨论】:

      【解决方案4】:

      对我来说,以下看起来很简单:

      model.layers[idx].output
      

      上面是张量对象,因此您可以使用可应用于张量对象的操作对其进行修改。

      例如获取形状model.layers[idx].output.get_shape()

      idx是层的索引,你可以从model.summary()找到它

      【讨论】:

      • 这个答案有什么问题?为什么这没有被评为最佳答案?
      • 它返回一个张量对象,而不是一个数据框。 tf 对象使用起来很奇怪。
      • 发帖人说他们想得到每一层的输出。给定一些数据,如何从model.layers[idx].output获取层输出?
      【解决方案5】:

      此答案基于:https://stackoverflow.com/a/59557567/2585501

      打印单层的输出:

      from tensorflow.keras import backend as K
      layerIndex = 1
      func = K.function([model.get_layer(index=0).input], model.get_layer(index=layerIndex).output)
      layerOutput = func([input_data])  # input_data is a numpy array
      print(layerOutput)
      

      打印每一层的输出:

      from tensorflow.keras import backend as K
      for layerIndex, layer in enumerate(model.layers):
          func = K.function([model.get_layer(index=0).input], layer.output)
          layerOutput = func([input_data])  # input_data is a numpy array
          print(layerOutput)
      

      【讨论】:

        【解决方案6】:

        我为自己(在 Jupyter 中)编写了这个函数,它的灵感来自 indraforyou 的回答。它将自动绘制所有图层输出。您的图像必须具有 (x, y, 1) 形状,其中 1 代表 1 个通道。您只需调用 plot_layer_outputs(...) 即可进行绘图。

        %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')
        

        【讨论】:

        • 如果模型有多个输入怎么办?如何指定输入?
        • 在这一行:layer_outputs_list = [op([test_image, 1.])。 1. 需要为 0 吗?似乎 1 代表训练,0 代表测试?不是吗?
        • 这对我不起作用。我使用了彩色图像,它给了我错误:InvalidArgumentError: input_2:0 is fed and fetched.
        【解决方案7】:

        发件人: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
        

        【讨论】:

        • 链接已弃用。
        【解决方案8】:

        想将此作为评论(但没有足够高的代表)添加到@indraforyou 的答案中,以纠正@mathtick 评论中提到的问题。为避免InvalidArgumentError: input_X:Y is both fed and fetched. 异常,只需将outputs = [layer.output for layer in model.layers] 行替换为outputs = [layer.output for layer in model.layers][1:],即

        改编 indraforyou 的最小工作示例:

        from keras import backend as K 
        inp = model.input                                           # input placeholder
        outputs = [layer.output for layer in model.layers][1:]        # all layer outputs except first (input) layer
        functor = K.function([inp, K.learning_phase()], outputs )   # evaluation function
        
        # Testing
        test = np.random.random(input_shape)[np.newaxis,...]
        layer_outs = functor([test, 1.])
        print layer_outs
        

        附言我尝试尝试诸如outputs = [layer.output for layer in model.layers[1:]] 之类的东西没有奏效。

        【讨论】:

        • 这并不完全正确。仅当输入层是第一个定义时。
        • 谢谢,这对我有用,我只是想检查一下我理解为什么,根据 Mpizos 的评论:我的模型只有 3 层(词嵌入 - BiLSTM - CRF),所以我想我有排除 layer[0] 因为它只是嵌入并且不应该有激活,对吧?
        • @MpizosDimitris 是的,这是正确的,但在@indraforyou(我正在修改)提供的示例中,情况就是这样。 @KMunro,如果我理解正确,那么您不关心第一层输出的原因是因为它只是词嵌入的输出,它只是以张量形式嵌入的词本身(这只是输入到keras 模型的“网络”部分)。您的词嵌入层相当于此处提供的示例中的输入层。
        【解决方案9】:

        以前的解决方案对我不起作用。我处理了这个问题,如下所示。

        layer_outputs = []
        for i in range(1, len(model.layers)):
            tmp_model = Model(model.layers[0].input, model.layers[i].output)
            tmp_output = tmp_model.predict(img)[0]
            layer_outputs.append(tmp_output)
        

        【讨论】:

        • 这里的“模型”是什么?
        • 正是我想要的! +1
        【解决方案10】:

        假设你有:

        1- Keras 预训练 model

        2- 输入x 作为图像或图像集。图像的分辨率应与输入层的尺寸兼容。例如 80*80*3 用于 3 通道 (RGB) 图像。

        3- 输出名称layer 以获得激活。例如,“flatten_2”图层。这应该包含在layer_names 变量中,表示给定model 的图层名称。

        4- batch_size 是一个可选参数。

        然后你可以很容易地使用get_activation 函数来激活输出layer 对于给定的输入x 和预训练的model

        import six
        import numpy as np
        import keras.backend as k
        from numpy import float32
        def get_activations(x, model, layer, batch_size=128):
        """
        Return the output of the specified layer for input `x`. `layer` is specified by layer index (between 0 and
        `nb_layers - 1`) or by name. The number of layers can be determined by counting the results returned by
        calling `layer_names`.
        :param x: Input for computing the activations.
        :type x: `np.ndarray`. Example: x.shape = (80, 80, 3)
        :param model: pre-trained Keras model. Including weights.
        :type model: keras.engine.sequential.Sequential. Example: model.input_shape = (None, 80, 80, 3)
        :param layer: Layer for computing the activations
        :type layer: `int` or `str`. Example: layer = 'flatten_2'
        :param batch_size: Size of batches.
        :type batch_size: `int`
        :return: The output of `layer`, where the first dimension is the batch size corresponding to `x`.
        :rtype: `np.ndarray`. Example: activations.shape = (1, 2000)
        """
        
            layer_names = [layer.name for layer in model.layers]
            if isinstance(layer, six.string_types):
                if layer not in layer_names:
                    raise ValueError('Layer name %s is not part of the graph.' % layer)
                layer_name = layer
            elif isinstance(layer, int):
                if layer < 0 or layer >= len(layer_names):
                    raise ValueError('Layer index %d is outside of range (0 to %d included).'
                                     % (layer, len(layer_names) - 1))
                layer_name = layer_names[layer]
            else:
                raise TypeError('Layer must be of type `str` or `int`.')
        
            layer_output = model.get_layer(layer_name).output
            layer_input = model.input
            output_func = k.function([layer_input], [layer_output])
        
            # Apply preprocessing
            if x.shape == k.int_shape(model.input)[1:]:
                x_preproc = np.expand_dims(x, 0)
            else:
                x_preproc = x
            assert len(x_preproc.shape) == 4
        
            # Determine shape of expected output and prepare array
            output_shape = output_func([x_preproc[0][None, ...]])[0].shape
            activations = np.zeros((x_preproc.shape[0],) + output_shape[1:], dtype=float32)
        
            # Get activations with batching
            for batch_index in range(int(np.ceil(x_preproc.shape[0] / float(batch_size)))):
                begin, end = batch_index * batch_size, min((batch_index + 1) * batch_size, x_preproc.shape[0])
                activations[begin:end] = output_func([x_preproc[begin:end]])[0]
        
            return activations
        

        【讨论】:

          【解决方案11】:

          如果您有以下情况之一:

          • 错误:InvalidArgumentError: input_X:Y is both fed and fetched
          • 多个输入的情况

          您需要进行以下更改:

          • outputs变量中的输入层添加过滤器
          • functors 循环的微小变化

          最小示例:

          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]
          

          【讨论】:

          • [x1, x2, xn, 1] 是什么意思?我的 x1 没有定义,我想了解您在那里定义的内容。
          • @HashRocketSyntax x1x2 是模型的输入。如前所述,如果您的模型有 2 个输入。
          【解决方案12】:

          嗯,其他答案都非常完整,但是有一个非常基本的方法来“看到”,而不是“得到”形状。

          只需做一个model.summary()。它将打印所有图层及其输出形状。 “无”值表示可变维度,第一个维度将是批量大小。

          【讨论】:

          • 这是关于层的输出(给定基础层的输入)而不是层。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2019-03-28
          • 1970-01-01
          • 2020-03-08
          • 2020-12-27
          • 1970-01-01
          • 2021-12-24
          • 2019-03-18
          相关资源
          最近更新 更多