dan*_*451 7 python numpy initialization interactive-session tensorflow
在我的IPython进口tensorflow as tf
和numpy 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)
Run Code Online (Sandbox Code Playgroud)
返回:
array([[-0.04152317, 0.19786302],
[-0.68232622, -0.23439092]])
Run Code Online (Sandbox Code Playgroud)
正如预期的那样.
...但是当我使用Tensorflow正态分布函数时:
some_test = tf.constant(tf.random_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32))
session.run(some_test)
Run Code Online (Sandbox Code Playgroud)
...它引发了一个类型错误说:
(...)
TypeError: List of Tensors when single Tensor expected
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么?
输出:
sess.run(tf.random_normal([2, 2], mean=0.0, stddev=1.0, dtype=tf.float32))
Run Code Online (Sandbox Code Playgroud)
单独返回np.random.normal
生成的完全相同的东西- >一个形状矩阵,(2, 2)
其值取自正态分布.
mrr*_*rry 13
该tf.constant()
运算需要花费numpy的阵列(或其它隐式转换为一个numpy的阵列),并返回一个tf.Tensor
其值是相同的数组.它并没有接受tf.Tensor
作为其参数.
另一方面,tf.random_normal()
op返回a,tf.Tensor
其值在每次运行时根据给定的分布随机生成.由于它返回a tf.Tensor
,因此不能用作参数tf.constant()
.这解释了TypeError
(与使用无关tf.InteractiveSession
,因为它在构建图形时发生).
我假设您希望图表包含一个张量,(i)在第一次使用时随机生成,(ii)此后不变.有两种方法可以做到这一点:
使用NumPy生成随机值并将其放入tf.constant()
,如您在问题中所做的那样:
some_test = tf.constant(
np.random.normal(loc=0.0, scale=1.0, size=(2, 2)).astype(np.float32))
Run Code Online (Sandbox Code Playgroud)(可能更快,因为它可以使用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`
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
11893 次 |
最近记录: |