TensorBoard: How to plot histogram for gradients?

Rob Romijnders picture Rob Romijnders · Apr 4, 2016 · Viewed 15.2k times · Source

TensorBoard had the function to plot histograms of Tensors at session-time. I want a histogram for the gradients during training.

tf.gradients(yvars,xvars) returns a list a gradients.

However, tf.histogram_summary('name',Tensor) accepts only Tensors, not lists of Tensors.

For the time being, I made a work-around. I flatten all Tensors to a column vector and concatenate them:

for l in xrange(listlength): col_vec = tf.reshape(grads[l],[-1,1]) g = tf.concat(0,[g,col_vec]) grad_hist = tf.histogram_summary("name", g)

What would be a better way to plot the histogram for the gradient?

It seems a common thing to do, so I hope TensorFlow would have a dedicated function for this.

Answer

DankMasterDan picture DankMasterDan · Mar 8, 2018

Another solution (based on this quora answer) is to access the gradients directly from the optimizer you are already using.

optimizer = tf.train.AdamOptimizer(..)
grads = optimizer.compute_gradients(loss)
grad_summ_op = tf.summary.merge([tf.summary.histogram("%s-grad" % g[1].name, g[0]) for g in grads])
grad_vals = sess.run(fetches=grad_summ_op, feed_dict = feed_dict)
writer['train'].add_summary(grad_vals)