8

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

4

1 回答 1

17

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

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

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

  1. 使用 NumPy 生成随机值并将其放入 a 中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`
    
于 2016-02-26T21:24:57.540 回答