短篇小说:我正在构建一个自动编码器,并希望在训练过程中存储重建的图像。我做了一个自定义回调,将图像写入摘要。唯一剩下的就是在callback.on_epoch_end(...)
内部调用我的重建层。如何访问回调内部的命名层并运行计算?
层定义:
decode = layers.Conv2D(1, (5, 5), name='wwae_decode', activation='sigmoid', padding='same')(conv3)
回调定义:
class TensorBoardImage(tf.keras.callbacks.Callback):
def __init__(self, tag, logdir):
super().__init__()
self.tag = tag
self.logdir = logdir
def on_epoch_end(self, epoch, logs={}):
img_stack = self.validation_data[0][:3]
# TODO: run img_stack through 'wwae_decode' layer first
# img_stack = self?model?get_layer('wwae_decode').evaluate(img_stack) # ????
single_image = merge_axis(img_stack, target_axis=2)
summary_str = []
single_image = (255 * single_image).astype('uint8')
summary_str.append(tf.Summary.Value(tag=self.tag, image=make_image(single_image)))
# multiple summaries can be appended
writer = tf.summary.FileWriter(self.logdir)
writer.add_summary(tf.Summary(value=summary_str), epoch)
return
如果这是模型中的最后一层(即输出层(,那么您只需在回调中调用模型实例predict
方法:
# ...
img_stack = self.validation_data[0][:3]
preds_img_stack = self.model.predict(img_stack)
# ...
或者,您可以通过定义后端函数直接计算图层的输出:
from keras import backend as K
func = K.function(model.inputs + [K.learning_phase()], [model.get_layer('wwae_decode').output])
# ...
img_stack = self.validation_data[0][:3]
preds_img_stack = func([img_stack, 0])[0]
# ...
有关更多信息,我建议您阅读 Keras 常见问题解答中的相关部分:如何获取中间层的输出?