tensorflow - 如何使用 Keras 在 TensorBoard 中显示自定义图像?

标签 tensorflow keras deep-learning tensorboard

我正在 Keras 中解决分割问题,我想在每个训练周期结束时显示分割结果。

我想要类似于Tensorflow: How to Display Custom Images in Tensorboard (e.g. Matplotlib Plots)的东西,但是使用 Keras。我知道 Keras 有 TensorBoard回调,但似乎仅限于此目的。

我知道这会破坏 Keras 后端抽象,但无论如何我对使用 TensorFlow 后端很感兴趣。

是否可以使用 Keras + TensorFlow 来实现这一目标?

最佳答案

因此,以下解决方案对我来说效果很好:

import tensorflow as tf

def make_image(tensor):
    """
    Convert an numpy representation image to Image protobuf.
    Copied from https://github.com/lanpa/tensorboard-pytorch/
    """
    from PIL import Image
    height, width, channel = tensor.shape
    image = Image.fromarray(tensor)
    import io
    output = io.BytesIO()
    image.save(output, format='PNG')
    image_string = output.getvalue()
    output.close()
    return tf.Summary.Image(height=height,
                         width=width,
                         colorspace=channel,
                         encoded_image_string=image_string)

class TensorBoardImage(keras.callbacks.Callback):
    def __init__(self, tag):
        super().__init__() 
        self.tag = tag

    def on_epoch_end(self, epoch, logs={}):
        # Load image
        img = data.astronaut()
        # Do something to the image
        img = (255 * skimage.util.random_noise(img)).astype('uint8')

        image = make_image(img)
        summary = tf.Summary(value=[tf.Summary.Value(tag=self.tag, image=image)])
        writer = tf.summary.FileWriter('./logs')
        writer.add_summary(summary, epoch)
        writer.close()

        return

tbi_callback = TensorBoardImage('Image Example')

只需将回调传递给 fitfit_generator

请注意,您还可以使用回调中的model 运行一些操作。例如,您可以在某些图像上运行模型来检查其性能。

screen

关于tensorflow - 如何使用 Keras 在 TensorBoard 中显示自定义图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43784921/

相关文章:

python - 如何处理 CNN 训练 Keras 的数千张图像

tensorflow - 如何在使用 Keras 或 Tensorflow 训练深度神经网络期间添加更多数据

python - 在学习期间将数据添加到自动编码器中的解码器

python - 是否可以将 NumPy 函数映射到 tf.data.dataset?

tensorflow - 如何使用pipenv在m1 mac上安装tensorflow

python - 在 Keras 中加载模型权重时出现问题

python - 从 Google Drive Colab 下载数据

python - 如何在 Keras 中正确设置 RNN 以进行序列到序列建模?

machine-learning - ValueError : Error when checking input: expected lstm_1_input to have shape (None, 296, 2048) 但得到形状为 (296, 2048, 1) 的数组

同一环境中的 Tensorflow 和 Torch