TensorFlow:生成一个随机常数


问题内容

在我的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)其值取自正态分布。


问题答案:

tf.constant()运算需要花费numpy的阵列(或其它隐式转换为一个numpy的阵列),并返回一个tf.Tensor其值是相同的数组。它并
没有 接受tf.Tensor作为其参数。

另一方面,tf.random_normal()optf.Tensor每次运行时都会根据给定的分布返回其值是随机生成的。由于它返回a
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