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

时间:2019-09-28 21:21:52

标签: keras python-3.6 autoencoder tensorflow2.0

我建立了一个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中的说明,在Keras, How to get the output of each layer?中也做了很多说明。

我尝试了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(),则代码会很好用,但是我需要确保隐藏层的输出是在未受噪声污染的输入上进行评估的(例如,在“测试”模式下) -不是“培训”模式。

我知道我的另一种选择是从原始的降噪自动编码器创建模型,但是没有人能指出我为什么正式记录的仿函数创建方法失败了吗?

1 个答案:

答案 0 :(得分:1)

首先,请确保您的软件包是最新的,因为您的脚本可以正常工作。其次,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()
相关问题