TensorFlow:生成一个随机常数 [英] TensorFlow: generating a random constant
问题描述
在ipython中,我导入了tensorflow as tf
和numpy as np
并创建了一个TensorFlow InteractiveSession
.
当我使用numpy输入运行或初始化一些正态分布时,一切运行正常:
In ipython I imported tensorflow as tf
and numpy as np
and created an TensorFlow InteractiveSession
.
When I am running or initializing some normal distribution with numpy input, everything runs fine:
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正态分布函数时:
...but when I use the Tensorflow normal distribution function:
some_test = tf.constant(tf.random_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32))
session.run(some_test)
...它引发类型错误,提示:
...it raises a Type error saying:
(...)
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)
的矩阵完全相同的东西,其值取自正态分布.
alone returns the exact same thing which np.random.normal
generates -> a matrix of shape (2, 2)
with values taken from a normal distribution.
推荐答案
tf.constant()
op接受一个numpy数组(或可隐式转换为numpy数组的东西),并返回另一方面,tf.random_normal()
op返回一个tf.Tensor
,其值每次运行时都会根据给定的分布随机生成.由于它返回tf.Tensor
,因此不能用作tf.constant()
的参数.解释了TypeError
(与tf.InteractiveSession
的使用无关,因为它是在构建图形时出现的.)
On the other hand, the tf.random_normal()
op returns a tf.Tensor
whose value is generated randomly according to the given distribution each time it runs. Since it returns a tf.Tensor
, it cannot be used as the argument to tf.constant()
. This explains the TypeError
(which is unrelated to the use of tf.InteractiveSession
, since it occurs when you build the graph).
我假设您希望图形包含一个张量,该张量(i)在首次使用时随机生成,并且(ii)此后是常数.有两种方法可以做到这一点:
I'm assuming you want your graph to include a tensor that (i) is randomly generated on its first use, and (ii) constant thereafter. There are two ways to do this:
-
使用NumPy生成随机值,并将其放入
tf.constant()
中,就像您在问题中所做的那样:
Use NumPy to generate the random value and put it in a
tf.constant()
, as you did in your question:
some_test = tf.constant(
np.random.normal(loc=0.0, scale=1.0, size=(2, 2)).astype(np.float32))
(可能更快,因为它可以使用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`
这篇关于TensorFlow:生成一个随机常数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!