我正在 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')
只需将回调传递给 fit
或 fit_generator
。
请注意,您还可以使用回调中的model
运行一些操作。例如,您可以在某些图像上运行模型来检查其性能。
关于tensorflow - 如何使用 Keras 在 TensorBoard 中显示自定义图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43784921/