Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

python - Operations on random variables not working properly in Tensorflow

I create two Tensors (namely: x1, y2) which initialized with uniform distribution, But when I print out the result they were not what I expected.

This is my code:

x1 = tf.random_uniform([1], 0, 10, tf.int32)
y1 = tf.random_uniform([1], 0, 10, tf.int32)

subtraction = x1 - y1

with tf.Session() as sess:

    print(sess.run(x1))
    print(sess.run(y1))
    print(sess.run(subtraction))

This is the result:

[6]

[2]

[0]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your code, x1 and y1 are random number generators. They take different values each time they are called. So when you call subtraction, which in turns call your number generators x1 and y1, there is no reason to obtain results that are consistent with previous calls.

To achieve what you are looking for, store the values in a Variable:

import tensorflow as tf

x1 = tf.Variable(tf.random_uniform([1], 0, 10, tf.int32))
y1 = tf.Variable(tf.random_uniform([1], 0, 10, tf.int32))

subtraction = x1 - y1

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(x1))
    print(sess.run(y1))
    print(sess.run(subtraction))

Alternatively, if you don't need persistence between iterations and can call all the operators relying on your number generators at once, pack them into the same call to sess.run:

import tensorflow as tf

x1 = tf.random_uniform([1], 0, 10, tf.int32)
y1 = tf.random_uniform([1], 0, 10, tf.int32)

subtraction = x1 - y1

with tf.Session() as sess:
    print(sess.run([x1, y1, subtraction]))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...