使用numpy随机函数时,TensorFlow返回相同的值

时间:2018-04-22 05:09:32

标签: numpy tensorflow random

我使用Tensorflow和numpy随机函数,但输出值相同。如何生成不同的值?您可能建议使用本机随机函数,但我需要使用numpy随机函数。

import tensorflow as tf
import random


def get_rand():
    return random.randint(0,5)

a = get_rand()
tfprint = tf.Print(a, [a])

for i in range(10):
    print(print(get_rand()))

with tf.Session() as sess:
    for i in range(10):
        sess.run(tfprint)

2 个答案:

答案 0 :(得分:1)

使用tf.py_func,将Numpy函数转换为Tensorflow函数。

import tensorflow as tf
import random


def get_rand():
    return random.randint(0,5)

a = tf.py_func(get_rand, [], tf.int64)
tfprint = tf.Print(a, [a])

for i in range(10):
    print(get_rand())

with tf.Session() as sess:
    for i in range(10):
        sess.run(tfprint)

答案 1 :(得分:0)

您需要使用placeholdersfeed_dict变量

来提供数据
import tensorflow as tf
import random


def get_rand():
    return random.randint(0,5)

a = tf.placeholder(tf.int32)
tfprint = tf.Print(a, [a])


with tf.Session() as sess:
    for i in range(10):
        sess.run(tfprint, feed_dict={a: get_rand()})

您可以阅读有关占位符here

的更多信息