如何使用 learning_phase 在 TF 2.3 Eager 中获得中间输出?

How to get intermediate outputs in TF 2.3 Eager with learning_phase?

下面的示例适用于 2.2; K.function 在 2.3 中发生了显着变化,now building 在 Eager execution 中发生了 Model,因此我们传递了 Model(inputs=[learning_phase,...])

我确实有一个解决方法,但它很老套,而且比 K.function 复杂得多;如果 none 可以展示一个简单的方法,我会 post 我的。


from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
from tensorflow.python.keras import backend as K
import numpy as np

ipt = Input((16,))
x   = Dense(16)(ipt)
out = Dense(16)(x)
model = Model(ipt, out)
model.compile('sgd', 'mse')

outs_fn = K.function([model.input, K.symbolic_learning_phase()],
                     [model.layers[1].output])  # error
x = np.random.randn(32, 16)
print(outs_fn([x, True]))
>>> ValueError: Input tensors to a Functional must come from `tf.keras.Input`. 
Received: Tensor("keras_learning_phase:0", shape=(), dtype=bool) 
(missing previous layer metadata).

为了在急切模式下获取中间层的输出,没有必要构建 K.function 并使用学习阶段。相反,我们可以建立一个模型来实现:

partial_model = Model(model.inputs, model.layers[1].output)

x = np.random.rand(...)
output_train = partial_model([x], training=True)   # runs the model in training mode
output_test = partial_model([x], training=False)   # runs the model in test mode

或者,如果您坚持使用 K.function 并想在急切模式下切换学习阶段,您可以使用 tensorflow.python.keras.backend 中的 eager_learning_phase_scope(请注意,此模块是tensorflow.keras.backend 并包含内部功能,例如提到的功能,在未来的版本中可能会更改):

from tensorflow.python.keras.backend import eager_learning_phase_scope

fn = K.function([model.input], [model.layers[1].output])

# run in test mode, i.e. 0 means test
with eager_learning_phase_scope(value=0):
    output_test = fn([x])

# run in training mode, i.e. 1 means training
with eager_learning_phase_scope(value=1):
    output_train = fn([x])

另一种解决方法:

import tensorflow as tf

tf.compat.v1.disable_eager_execution()