在Tensorflow / Keras中查看隐藏层输出的最简单方法是?

问题描述

我正在研究GAN,正在尝试诊断模式崩溃的原因。我希望能够“深入了解”,并查看最后一个minibatch的网络各层的输出情况。我看到您可以执行类似model.layers[5].output的操作,但是会生成一个形状为[None,64,64,512]的张量,它看起来像一个空张量,而不是前一次运行的实际输出。我唯一的另一个想法是重新编译一个模型,该模型会在我感兴趣的那一层之后丢失所有的层,然后再进行一次小批量生产,但这似乎是一种效率极低的方法。我想知道是否有更简单的方法。我想在训练过程中对图层输出进行一些统计,以查看可能出问题的地方。

解决方法

我这样做是为了训练自己的GAN。我使用的方法扩展到GAN的生成器(G)和鉴别器(D)。

想法是制作一个模型,其输入与D或G相同,但要根据您所需要的模型中的每一层进行输出。

对我来说,我发现检查激活很有用。在Keras中,使用某种模型model(对于您和我来说都是D或G)

activation_layers = []
activation_names = []

# obtain the layers in a given model,but skip the first 6
# as these generally are the input / non-convolutional layers
model_layers = [layer for layer in sub_model.layers][6:]
# print the names of what we are looking at.
print("MODEL LAYERS:",model_layers)

for layer in model_layers:
    # check if the layer is an activation
    if isinstance(layer,(Activation,LeakyReLU)):
        # append the output of this layer for later
        activation_layers.append(layer.output)
        # name it with a signature of its output for clarity
        activation_names.append(layer.name + str(layer.output_shape[1]))

# now create a model which outputs every activation
activation_model = Model(inputs=model.inputs,outputs=activation_layers)
# this outputs a list of layers when given an input,so for G
noise = np.random.normal(size=(1,32,1)) # random image shape (change for yourself)
model_activations = model.predict(noise)

现在其余的都是特定于模型的。这是检查给定模型中各层输出的基本方法。

请注意,可以在训练之前,之中或之后进行。它还不需要重新编译。

在这种情况下,激活图的绘制相对简单,正如您提到的,您可能需要做一些特定的事情。不过,我必须链接这个美丽的示例here