【问题标题】:TensorFlow: generating a random constantTensorFlow:生成随机常数
【发布时间】:2016-06-10 06:09:21
【问题描述】:

在 ipython 中,我导入了 tensorflow as tfnumpy as np 并创建了一个 TensorFlow InteractiveSession。 当我使用 numpy 输入运行或初始化一些正态分布时,一切运行正常:

some_test = tf.constant(np.random.normal(loc=0.0, scale=1.0, size=(2, 2)))
session.run(some_test)

返回:

array([[-0.04152317,  0.19786302],
       [-0.68232622, -0.23439092]])

正如预期的那样。

...但是当我使用 Tensorflow 正态分布函数时:

some_test = tf.constant(tf.random_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32))
session.run(some_test)

...它会引发类型错误:

(...)
TypeError: List of Tensors when single Tensor expected

我在这里缺少什么?

输出:

sess.run(tf.random_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32))

单独返回与 np.random.normal 生成的完全相同的内容 -> 形状为 (2, 2) 的矩阵,其值取自正态分布。

【问题讨论】:

    标签: python numpy initialization tensorflow interactive-session


    【解决方案1】:

    tf.constant() 操作接受一个 numpy 数组(或可以隐式转换为 numpy 数组的东西),并返回一个值与该数组相同的 tf.Tensor。它确实接受 tf.Tensor 作为其参数。

    另一方面,tf.random_normal() 操作返回一个tf.Tensor,其值是在每次运行时根据给定分布随机生成的。由于它返回一个tf.Tensor,它不能用作tf.constant() 的参数。这解释了TypeError(这与tf.InteractiveSession 的使用无关,因为它在您构建图形时发生)。

    我假设您希望您的图表包含一个张量,该张量 (i) 在首次使用时随机生成,并且 (ii) 此后保持不变。有两种方法可以做到这一点:

    1. 使用 NumPy 生成随机值并将其放入 tf.constant(),就像您在问题中所做的那样:

      some_test = tf.constant(
          np.random.normal(loc=0.0, scale=1.0, size=(2, 2)).astype(np.float32))
      
    2. (可能更快,因为它可以使用 GPU 生成随机数)使用 TensorFlow 生成随机值并将其放入 tf.Variable

      some_test = tf.Variable(
          tf.random_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32)
      sess.run(some_test.initializer)  # Must run this before using `some_test`
      

    【讨论】:

    • 感谢您的解释!因此,当我想要 GPU 加速又名“纯”张量流来获得随机“常数”时,我必须使用 tf.Variable?!
    • 是的,这违反直觉,不是吗? :) 问题在于,在 TF 中,“是变量”和“可初始化”的概念结合在同一个类型中——我们偶尔讨论过更好的初始化方法(例如,C 中的一些静态初始化等价物)像语言),但还没有确定设计。 (可以想象这样的东西对常量折叠等优化有多大用处。)
    • 感谢@mrry 的回复。如果我试图做同样的事情,但我不想让some_test 保持不变,我会做与选项 2 相同的事情,但不包括 sess.run(some_test.initializer)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 2023-01-03
    • 2011-10-24
    相关资源
    最近更新 更多