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

Easiest way to see the output of a hidden layer in Tensorflow/Keras?

我正在研究 GAN,我正在尝试诊断模式崩溃是如何发生的。我希望能够“深入了解”并查看最后一个小批量网络中各个层的输出是什么样的。我看到你可以做类似 model.layers[5].output 的事情,但这会产生一个形状为 [None, 64, 64, 512] 的张量,它看起来像一个空张量,而不是前一个 [=] 的实际输出15=]。我唯一的另一个想法是重新编译一个模型,该模型在我感兴趣的层之后缺少所有层,然后 运行 通过一个小批量,但这似乎是一种非常低效的方法。我想知道是否有更简单的方法。我想 运行 在训练过程中对层输出进行一些统计,以查看哪里可能出了问题。

我为自己训练的 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,32,1)) # random image shape (change for yourself)
model_activations = model.predict(noise)

现在剩下的就差不多了model-specific。这是检查给定模型中各层输出的基本方法。

请注意,它可以在训练之前、期间或之后完成。它也不需要 re-compiling.

在这种情况下,激活图的绘制相对简单,正如您所提到的,您可能有一些特定的需要做的事情。尽管如此,我还是要link这个漂亮的例子here

我在这里报告一个有用的 2 行代码块,我从 @Homer 的答案中推断出我用来检查神经网络的单层。

ablation_model = Model(inputs=model.inputs, outputs=model.layers[-2].output) 
preds = ablation_model.predict(np.random.normal(size=(20,2)))  # adapt size