I wanted a way to display maplotlib plots on Tensorboard, so I thought about it.
Since images can be displayed on Tensorboard, why not display the plot as an image? I thought.
So, I will summarize the method.
Please note that the log output is done via tensorboardX
.
First, switch the backend to ʻAgg to get the plot as an image with matplotlib. Note that the backend switch must be done before ʻimport matplotlib.pyplot
.
import matplotlib as mpl
mpl.use('Agg')
The image data of the plot can be obtained by the following method.
import matplot.pyplot as plt
import numpy as np
fig = plt.figure() #Plt when displaying repeatedly.figure(0)It is better to specify the figure with etc.
#Some kind of plot
fig.canvas.draw() #Draw on Canvas
plot_image = fig.canvas.renderer._renderer #Get plot as image data
#tensorboardX is like channel first, so match it
plot_image_array = np.array(plot_image).transpose(2, 0, 1)
After that, just output the log with tensorboard X
.
from tensorboardX import SummaryWriter
summary_writer = SummaryWriter(logdir='hoge') #Initialization of writer
summary_writer.add_image('plot', plot_image_array) #Add image
that's all.
Please let me know if there is any other good way.
Recommended Posts