使用 Keras 在去噪自动编码器中获取隐藏层输出

Obtaining hidden layer outputs in a denoising autoencoder using Keras

我构建了一个 Sequential Keras 模型,它包含三层:Gaussian Noise 层、隐藏层以及与输入层维度相同的输出层。为此,我正在使用 Tensorflow 2.0.0-beta1 附带的 Keras 包。因此,我想获得隐藏层的输出,这样我就绕过了 Gaussian Noise 层,因为它只在训练阶段是必需的。

为了实现我的目标,我也遵循了 https://keras.io/getting-started/faq/#how-can-i-obtain-the-output-of-an-intermediate-layer, which are pretty much described in 中的说明。

我尝试了 Keras 官方文档中的以下示例:

from tensorflow import keras
from tensorflow.keras import backend as K

dae = keras.Sequential([
    keras.layers.GaussianNoise( 0.001, input_shape=(10,) ),
    keras.layers.Dense( 80, name="hidden", activation="relu" ),
    keras.layers.Dense( 10 )
])

optimizer = keras.optimizers.Adam()
dae.compile( loss="mse", optimizer=optimizer, metrics=["mae"] )

# Here the fitting process...
# dae.fit( · )

# Attempting to retrieve a decoder functor.
encoder = K.function([dae.input, K.learning_phase()], 
                               [dae.get_layer("hidden").output])

但是,当使用 K.learning_phase() 创建 Keras 后端仿函数时,出现错误:

Traceback (most recent call last):
  File "/anaconda3/lib/python3.6/contextlib.py", line 99, in __exit__
    self.gen.throw(type, value, traceback)
  File "/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/keras/backend.py", line 534, in _scratch_graph
    yield graph
  File "/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/keras/backend.py", line 3670, in __init__
    base_graph=source_graph)
  File "/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/eager/lift_to_graph.py", line 249, in lift_to_graph
    visited_ops = set([x.op for x in sources])
  File "/anaconda3/lib/python3.6/site-packages/tensorflow_core/python/eager/lift_to_graph.py", line 249, in <listcomp>
    visited_ops = set([x.op for x in sources])
AttributeError: 'int' object has no attribute 'op'

如果我不包含 K.learning_phase(),代码会工作得很好,但我需要确保我的隐藏层的输出是在未被噪声污染的输入上进行评估的(即在 "test" 模式 -- 不是 "training" 模式)。

我知道我的另一个选择是从原始的去噪自动编码器创建一个模型,但是谁能告诉我为什么我从官方记录的仿函数创建方法失败了?

首先,确保你的包是最新的,因为你的脚本对我来说工作得很好。其次,encoder 不会获得输出 - 从 # Here is the fitting process...

之后的代码片段继续
x = np.random.randn(32, 10) # toy data
y = np.random.randn(32, 10) # toy labels
dae.fit(x, y) # run one iteration

encoder = K.function([dae.input, K.learning_phase()], [dae.get_layer("hidden").output])
outputs = [encoder([x, int(False)])][0][0] # [0][0] to index into nested list of len 1
print(outputs.shape)
# (32, 80)

但是,从 Tensorflow 2.0.0-rc2 开始,这将 启用急切执行 - 通过以下方式禁用:

tf.compat.v1.disable_eager_execution()