【问题标题】:TensorFlow returns the same value when using numpy random functionTensorFlow 在使用 numpy 随机函数时返回相同的值
【发布时间】:2018-10-02 09:55:01
【问题描述】:

我正在使用带有 numpy random 函数的 Tensorflow,但输出是相同的值。如何生成不同的值?你可能会推荐使用原生 tf 随机函数,但我需要使用 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)

【问题讨论】:

  • 我刚刚运行了你的代码,它打印了 10 个不同的随机数。有什么问题?
  • Numpy 部分会生成随机数,但 Tensorflow 部分不会。

标签: numpy tensorflow random


【解决方案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)

【讨论】:

    【解决方案2】:

    您需要使用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

    【讨论】:

    • 感谢您的回答,但在我的问题中,我无法使用 feed_dict。
    • 是什么阻止您使用它们?
    • 我原来的问题比给出例子更复杂。这是关于数据增强的。
    猜你喜欢
    • 2018-09-23
    • 1970-01-01
    • 2015-02-24
    • 2021-11-11
    • 2013-01-31
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-24
    相关资源
    最近更新 更多