development

Keras, 각 레이어의 출력을 얻는 방법은 무엇입니까?

big-blog 2020. 8. 13. 07:44
반응형

Keras, 각 레이어의 출력을 얻는 방법은 무엇입니까?


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처럼 각 레이어의 출력을 얻고 싶습니다. 어떻게 할 수 있습니까?


다음을 사용하여 모든 레이어의 출력을 쉽게 얻을 수 있습니다. 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

참고 : 드롭 아웃의 사용을 시뮬레이션 learning_phase으로 1.layer_outs다른 사용0.

편집 : (댓글에 따라)

K.function 입력이 주어지면 나중에 기호 그래프에서 출력을 얻는 데 사용되는 theano / tensorflow 텐서 함수를 생성합니다.

이제 K.learning_phase()Dropout / Batchnomalization과 같은 많은 Keras 레이어가 학습 및 테스트 시간 동안 동작을 변경하는 데 의존하므로 입력으로 필요합니다.

따라서 코드에서 드롭 아웃 레이어를 제거하면 다음을 사용할 수 있습니다.

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

에서 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]

이 함수를 Jupyter에서 직접 작성했으며 indraforyou 의 답변 에서 영감을 얻었습니다 . 모든 레이어 출력을 자동으로 플로팅합니다. 이미지는 1이 1 채널을 나타내는 (x, y, 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')

다음은 나에게 매우 간단 해 보입니다.

model.layers[idx].output

위는 텐서 객체이므로 텐서 객체에 적용 할 수있는 작업을 사용하여 수정할 수 있습니다.

예를 들어, 모양을 얻으려면 model.layers[idx].output.get_shape()

idx 레이어의 인덱스이며 다음에서 찾을 수 있습니다. model.summary()


이 스레드의 모든 좋은 답변을 바탕으로 각 레이어의 출력을 가져 오는 라이브러리를 작성했습니다. 모든 복잡성을 추상화하고 가능한 한 사용자 친화적으로 설계되었습니다.

https://github.com/philipperemy/keract

거의 모든 엣지 케이스를 처리합니다.

도움이 되었기를 바랍니다.


출처 : 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

@mathtick의 의견에 언급 된 문제를 해결하기 위해 @indraforyou의 답변에 이것을 주석으로 추가하고 싶었습니다 (하지만 충분한 담당자는 없습니다.). 방지하기 위해 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:]]가 작동하지 않았습니다.


글쎄요, 다른 답변은 매우 완전합니다. 그러나 모양을 "얻는"것이 아니라 "보는"아주 기본적인 방법이 있습니다.

그냥 model.summary(). 모든 레이어와 출력 모양을 인쇄합니다. "없음"값은 가변 차원을 나타내며 첫 번째 차원은 배치 크기가됩니다.


다음이 있다고 가정합니다.

1- Keras pre-trained model.

2- Input x as image or set of images. The resolution of image should be compatible with dimension of the input layer. For example 80*80*3 for 3-channels (RGB) image.

3- The name of the output layer to get the activation. For example, "flatten_2" layer. This should be include in the layer_names variable, represents name of layers of the given model.

4- batch_size is an optional argument.

Then you can easily use get_activation function to get the activation of the output layer for a given input x and pre-trained 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

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]

참고URL : https://stackoverflow.com/questions/41711190/keras-how-to-get-the-output-of-each-layer

반응형