View matplotlib plots on Tensorboard

Introduction

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.

Method

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

View matplotlib plots on Tensorboard
Use matplotlib on Ubuntu 12 & Python
Set matplotlib font on ubuntu
View PDF on Jupyter Notebook
matplotlib: Insert comment on timeline graph
Steps to install matplotlib on Mac
Draw Japanese with matplotlib on Ubuntu
View disk usage on personal Linux
How to run matplotlib on heroku
Run Matplotlib on a Docker container
Paste the matplotlib figure on excel
Notes on using matplotlib on the server