Sahand
Sahand

Reputation: 8370

tensorflow variable printing as NaN

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))

I'm trying to print a rolling average for the random number generated by np.random.randint(1000). Here's the output:

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

As you can see, print(session.run(x)) works as expected, as does print(session(n)). However, print(session.run(y)) gives nan! Why?

Upvotes: 0

Views: 480

Answers (1)

Sorin
Sorin

Reputation: 11968

You get nan because you try to print 0/0. First x and n should be variables because they change their values. y shouldn't be because it's the result of an operation.

Your code should look like:

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))

Upvotes: 2

Related Questions