避免在张量流中复制图形(LSTM 模型)
Avoiding duplicating graph in tensorflow (LSTM model)
我有以下简化代码(实际上是展开的 LSTM 模型):
def func(a, b):
with tf.variable_scope('name'):
res = tf.add(a, b)
print(res.name)
return res
func(tf.constant(10), tf.constant(20))
每当我 运行 最后一行时,它似乎改变了图形。但我不希望图表发生变化。实际上我的代码是不同的,是一个神经网络模型,但是它太大了,所以我添加了上面的代码。我想在不更改模型图的情况下调用 func
但它发生了变化。我在 TensorFlow
中阅读了有关变量范围的内容,但我似乎根本不了解它。
您应该查看 tf.nn.dynamic_rnn
的源代码,特别是 python/ops/rnn.py
- it's solving the same problem. In order not blow up the graph, it's using tf.while_loop
to reuse the same graph ops for new data. But this approach adds several restrictions, namely the shape of tensors that are passing through in a loop must be invariant. See the examples in tf.while_loop
文档中的 _dynamic_rnn_loop
函数:
i0 = tf.constant(0)
m0 = tf.ones([2, 2])
c = lambda i, m: i < 10
b = lambda i, m: [i+1, tf.concat([m, m], axis=0)]
tf.while_loop(
c, b, loop_vars=[i0, m0],
shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])])
我有以下简化代码(实际上是展开的 LSTM 模型):
def func(a, b):
with tf.variable_scope('name'):
res = tf.add(a, b)
print(res.name)
return res
func(tf.constant(10), tf.constant(20))
每当我 运行 最后一行时,它似乎改变了图形。但我不希望图表发生变化。实际上我的代码是不同的,是一个神经网络模型,但是它太大了,所以我添加了上面的代码。我想在不更改模型图的情况下调用 func
但它发生了变化。我在 TensorFlow
中阅读了有关变量范围的内容,但我似乎根本不了解它。
您应该查看 tf.nn.dynamic_rnn
的源代码,特别是 python/ops/rnn.py
- it's solving the same problem. In order not blow up the graph, it's using tf.while_loop
to reuse the same graph ops for new data. But this approach adds several restrictions, namely the shape of tensors that are passing through in a loop must be invariant. See the examples in tf.while_loop
文档中的 _dynamic_rnn_loop
函数:
i0 = tf.constant(0)
m0 = tf.ones([2, 2])
c = lambda i, m: i < 10
b = lambda i, m: [i+1, tf.concat([m, m], axis=0)]
tf.while_loop(
c, b, loop_vars=[i0, m0],
shape_invariants=[i0.get_shape(), tf.TensorShape([None, 2])])