如何在Tensorflow中训练期间打印渐变?

问题描述 投票:3回答:1

为了调试Tensorflow模型,我需要查看渐变是否发生变化或者是否存在任何nans。简单地在Tensorflow中打印变量不起作用,因为你看到的只有:

 <tf.Variable 'Model/embedding:0' shape=(8182, 100) dtype=float32_ref>

我试图使用tf.Print类,但不能使它工作,我想知道它是否可以实际使用这种方式。在我的模型中,我有一个训练循环,打印每个时期的损失值:

def run_epoch(session, model, eval_op=None, verbose=False):
    costs = 0.0
    iters = 0
    state = session.run(model.initial_state)
    fetches = {
            "cost": model.cost,
            "final_state": model.final_state,
    }
    if eval_op is not None:
        fetches["eval_op"] = eval_op

    for step in range(model.input.epoch_size):
        feed_dict = {}
        for i, (c, h) in enumerate(model.initial_state):
            feed_dict[c] = state[i].c
            feed_dict[h] = state[i].h

        vals = session.run(fetches, feed_dict)
        cost = vals["cost"]
        state = vals["final_state"]

        costs += cost
        iters += model.input.num_steps

    print("Loss:", costs)

    return costs

print(model.gradients[0][1])插入此函数将无法正常工作,因此我尝试在丢失打印后立即使用以下代码:

grads = model.gradients[0][1]
x = tf.Print(grads, [grads])
session.run(x)

但是我收到以下错误消息:

ValueError: Fetch argument <tf.Tensor 'mul:0' shape=(8182, 100) dtype=float32> cannot be interpreted as a Tensor. (Tensor Tensor("mul:0", shape=(8182, 100), dtype=float32) is not an element of this graph.)

这是有道理的,因为tf.Print确实不是图的一部分。因此,我尝试在实际图形中使用损失计算后使用tf.Print,但是这样做并没有那么好,我仍然得到了Tensor("Train/Model/mul:0", shape=(8182, 100), dtype=float32)

如何在Tensorflow中的训练循环内打印渐变变量?

python variables tensorflow machine-learning tensorflow-gradient
1个回答
4
投票

根据我的经验,看到张量流中的梯度流的最佳方法不是使用tf.Print,而是使用张量板。这是我在another problem中使用的示例代码,其中渐变是学习中的关键问题:

for g, v in grads_and_vars:
  tf.summary.histogram(v.name, v)
  tf.summary.histogram(v.name + '_grad', g)

merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('train_log_layer', tf.get_default_graph())

...

_, summary = sess.run([train_op, merged], feed_dict={I: 2*np.random.rand(1, 1)-1})
if i % 10 == 0:
  writer.add_summary(summary, global_step=i)

这将显示随时间推移的渐变分布。顺便说一下,为了检查NaN,在tensorflow中有一个专用函数:tf.is_nan。通常,您不需要检查渐变是否为NaN:当它发生时,变量也会爆炸,这将在张量板中清晰可见。

© www.soinside.com 2019 - 2024. All rights reserved.