张量流变量打印为NaN

时间:2018-01-25 11:46:55

标签: python tensorflow

import tensorflow as tf
import numpy as np

x = tf.constant(0, name='x')
n = tf.constant(0, name='n')
y = tf.Variable(x/n, name='y')

model = tf.global_variables_initializer()

with tf.Session() as session:
    session.run(model)
    for i in range(5):
        x = x + np.random.randint(1000)
        n = n + 1 
        print(session.run(x))
        print(session.run(n))
        print(session.run(y))

我试图打印由np.random.randint(1000)生成的随机数的滚动平均值。这是输出:

378
1
nan
1242
2
nan
2020
3
nan
2453
4
nan
2563
5
nan

如您所见,print(session.run(x))按预期工作,print(session(n))也是如此。但是,print(session.run(y))nan!为什么呢?

1 个答案:

答案 0 :(得分:2)

你得到nan因为你试图打印0/0。 首先x和n应该是变量,因为它们会改变它们的值。 不应该是因为它是手术的结果。

您的代码应如下所示:

x = tf.Variable(0, name='x')
n = tf.Variable(0, name='n')
y = x/n

model = tf.global_variables_initializer()

with tf.Session() as session:
    session.run(model)
    for i in range(5):
        ops = [
          tf.assign_add(x, np.random.randint(1000)),
          tf.assign_add(n, 1)]
        session.run(ops)
        print(session.run(x))
        print(session.run(n))
        print(session.run(y))