简体   繁体   中英

How to call model.evaluate() in keras callback?

Short story: I am building an Autoencoder and would like to store reconstructed images along the way of training. I made a custom callback that writes images to the summary. The only thing that remains is to call my reconstruction layer inside of callback.on_epoch_end(...) . How can I get access to a named layer inside of the callback and run a calculation?

Layer definition:

decode = layers.Conv2D(1, (5, 5), name='wwae_decode', activation='sigmoid', padding='same')(conv3)

Callback definition:

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

If this is the last layer in your model (ie output layer), then you can simply call predict method of the model instance inside the callback:

# ...
img_stack = self.validation_data[0][:3]
preds_img_stack = self.model.predict(img_stack)
# ...

Alternatively, you can directly compute a layer's output by defining a backend function:

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]
# ...

For more information, I suggest you to read the relevant section in Keras FAQ: How can I obtain the output of an intermediate layer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM