如何获得Keras模型所有层的输出?

时间:2019-10-03 19:43:06

标签: python tensorflow keras

我有一个Keras功能模型,定义为:

    # Construct DNN
    spec_input = keras.layers.Input(shape=(1, ctx, fft), name='spec')
    x = keras.layers.Flatten(data_format)(spec_input)

    for layer in range(len(args.dnn_struct)):
        x = Dense(args.dnn_struct[layer])(x)
        x = BatchNormalization()(x)
        x = keras.layers.ReLU()(x)

    out = Dense(fft, activation="sigmoid", name=f'spp')(x)
    model = Model(inputs=spec_input, outputs=out)

我想获取给定输入的模型中每一层的输出,而Keras, How to get the output of each layer?中给出的答案不适用于功能模型。我目前正在使用Tensorflow 1.14

当我尝试使用

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)

我得到了错误

Traceback (most recent call last):
  File "/home/xyz/anaconda3/envs/tf/lib/python3.7/site-packages/tensorflow/python/client/session.py", line 1446, in __init__
    session._session, options_ptr)
tensorflow.python.framework.errors_impl.InvalidArgumentError: spec:0 is both fed and fetched.

1 个答案:

答案 0 :(得分:1)

更新:您无法获取所有层的输出,因为“所有层”都包含Input-错误消息是不言自明的。使用:

outputs = get_all_outputs(model, input_data, 1)


以下适用于任何模型ModelSequential

def get_all_outputs(model, input_data, learning_phase=1):
    outputs = [layer.output for layer in model.layers[1:]] # exclude Input
    layers_fn = K.function([model.input, K.learning_phase()], outputs)
    return layers_fn([input_data, learning_phase])

层级解决方案:

def get_layer_outputs(model, layer_name, input_data, learning_phase=1):
    outputs   = [layer.output for layer in model.layers if layer_name in layer.name]
    layers_fn = K.function([model.input, K.learning_phase()], outputs)
    return layers_fn([input_data, learning_phase])

# or, for passing in a layer directly
def get_layer_outputs(model, layer, input_data, learning_phase=1):
    layer_fn = K.function([model.input, K.learning_phase()], layer.output)
    return layer_fn([input_data, learning_phase])