Package: tensorflow-plot
TensorFlow Plot (tfplot)ATensorFlowutility for providing matplotlib-basedplotoperations
—TensorBoard❤️Matplotlib.🚧 Under Construction —  API might change!It allows us to drawanymatplotlibplots or figures into images,
as a part of TensorFlow computation graph.
Especially, we can easily any plot and see the result image
as an image summary inTensorBoard.Quick OverviewThere are two main ways of usingtfplot: (i) Use as TF op, and (ii) Manually add summary protos.Usage: DecoratorYou can directly declare a Tensor factory by usingtfplot.autowrapas a decorator.
In the body of the wrapped function you can add any logic for drawing plots. Example:@tfplot.autowrap(figsize=(2,2))defplot_scatter(x:np.ndarray,y:np.ndarray,*,ax,color='red'):ax.scatter(x,y,color=color)x=tf.constant([1,2,3],dtype=tf.float32)# tf.Tensory=tf.constant([1,4,9],dtype=tf.float32)# tf.Tensorplot_op=plot_scatter(x,y)# tf.Tensor shape=(?, ?, 4) dtype=uint8Usage: Wrap as TF opsWe canwrapanypure python function for plotting as a Tensorflow op, such as:(i) A python function that creates and return a matplotlibFigure(see below)(ii) A python function that hasfigoraxkeyword parameters (will be auto-injected);
e.g.seaborn.heatmap(iii) A method instance ofmatplotlibAxes;
e.g.Axes.scatterExample of (i): You can define a python function that takesnumpy.ndarrayvalues as input (as an argument of Tensor input),
and draw a plot as a return value ofmatplotlib.figure.Figure.
The resulting TensorFlow plot op will be a RGBA image tensor of shape[height, width, 4]containing the resulting plot.deffigure_heatmap(heatmap,cmap='jet'):# draw a heatmap with a colorbarfig,ax=tfplot.subplots(figsize=(4,3))# DON'T USE plt.subplots() !!!!im=ax.imshow(heatmap,cmap=cmap)fig.colorbar(im)returnfigheatmap_tensor=...# tf.Tensor shape=(16, 16) dtype=float32# (a) wrap function as a Tensor factoryplot_op=tfplot.autowrap(figure_heatmap)(heatmap_tensor)# tf.Tensor shape=(?, ?, 4) dtype=uint8# (b) direct invocation similar to tf.py_funcplot_op=tfplot.plot(figure_heatmap,[heatmap_tensor],cmap='jet')# (c) or just directly add an image summary with the plottfplot.summary.plot("heatmap_summary",figure_heatmap,[heatmap_tensor])Example of (ii):importtfplotimportseaborn.apionlyassnstf_heatmap=tfplot.autowrap(sns.heatmap,figsize=(4,4),batch=True)# function: Tensor -> Tensorplot_op=tf_heatmap(attention_maps)# tf.Tensor shape=(?, 400, 400, 4) dtype=uint8tf.summary.image("attention_maps",plot_op)Please take a look at thethe showcaseorexamples directoryfor more examples and use cases.The full documentationincluding API docs can be found atreadthedocs.Usage: Manually add summary protosimporttensorboardastbfig,ax=...# Get RGB image manually or by executing plot ops.embedding_plot=sess.run(plot_op)# ndarray [H, W, 3] uint8embedding_plot=tfplot.figure_to_array(fig)# ndarray [H, W, 3] uint8summary_pb=tb.summary.image_pb('plot_embedding',[embedding_plot])summary_writer.write_add_summary(summary_pb,global_step=global_step)Installationpip install tensorflow-plotTo grab the latest development version:pip install git+https://github.com/wookayin/tensorflow-plot.git@masterNoteSome comments on SpeedMatplotlib operations can beveryslow as Matplotlib runs in python rather than native code,
so please watch out for runtime speed.
There is still a room for improvement, which will be addressed in the near future.Moreover, it might be also a good idea to draw plots from the main code (rather than having a TF op) and add them as image summaries.
Please use this library at your best discernment.Thread-safety issuePlease useobject-orientedmatplotlib APIs (e.g.Figure,AxesSubplot)
instead ofpyplotAPIs (i.e.matplotlib.pyplotorplt.XXX())
when creating and drawing plots.
This is becausepyplotAPIs are notthread-safe,
while the TensorFlow plot operations are usually executed in multi-threaded manners.For example, avoid any use ofpyplot(orplt):# DON'T DO LIKE THIS !!!deffigure_heatmap(heatmap):fig=plt.figure()# <--- NO!plt.imshow(heatmap)returnfigand do it like:deffigure_heatmap(heatmap):fig=matplotlib.figure.Figure()# or just `fig = tfplot.Figure()`ax=fig.add_subplot(1,1,1)# ax: AxesSubplot# or, just `fig, ax = tfplot.subplots()`ax.imshow(heatmap)returnfig# fig: FigureFor example,tfplot.subplots()is a good replacement forplt.subplots()to use inside plot functions.
Alternatively, you can just take advantage of automatic injection offigand/orax.TensorFlow compatibilityCurrently,tfplotis compatible with TensorFlow 1.x series.
Support for eager execution and TF 2.0 will be coming soon!LicenseMIT License© Jongwook Choi