gpt4 book ai didi

python - Tensorflow:将现有图多次复制到新图中

转载 作者:行者123 更新时间:2023-12-01 08:48:59 25 4
gpt4 key购买 nike

我想将现有的 tensorflow 图粘贴到新图中。

假设我创建一个图计算y = tanh(x @ w)

import tensorflow as tf
import numpy as np

def some_function(x):
w = tf.Variable(initial_value=np.random.randn(4, 5), dtype=tf.float32)
return tf.tanh(x @ w)

x = tf.placeholder(shape=(None, 4), dtype = tf.float32)
y = some_function(x)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
val_x = np.random.randn(3, 4)
val_y, = sess.run([y], feed_dict={x: val_x})
太棒了。现在假设我丢失了生成该图的代码,但我仍然可以访问变量( xy )。现在我想获取该图(使用 w 的当前值),并将其复制两次到一个新图中(两条路径应共享相同的 w ),以便我现在计算 d = tf.reduce_sum((tanh(x1 @ w)-tanh(x2 @ w))**2)通过添加行:

# Starting with access to tensors: x, y
<SOMETHING HERE>
d = tf.reduce_sum((y1-y2)**2)
val_x1 = np.random.randn(3, 4)
val_x2 = np.random.randn(3, 4)
val_d = sess.run([d], feed_dict = {x1: val_x1, x2: val_x2})

我该填写什么<SOMETHING HERE>使这项工作有效? (显然,无需重新创建第一个图)

最佳答案

Graph Editor模块来帮助完成此类操作。它的主要缺点是在修改图形时无法运行 session 。但是,您可以检查 session 、修改图表并根据需要将其恢复。

您想要的问题是您基本上需要复制子图,除非您不想复制变量。因此,您可以简单地排除变量类型(主要是 VariableVariableV2 以及可能的 VarHandleOp,尽管我添加了在 TensorFlow code 中找到的更多变量类型。 )。您可以使用如下函数来做到这一点:

import tensorflow as tf

# Receives the outputs to recalculate and the input replacements
def replicate_subgraph(outputs, mappings):
# Types of operation that should not be replicated
# Taken from tensorflow/python/training/device_setter.py
NON_REPLICABLE = {'Variable', 'VariableV2', 'AutoReloadVariable',
'MutableHashTable', 'MutableHashTableV2',
'MutableHashTableOfTensors', 'MutableHashTableOfTensorsV2',
'MutableDenseHashTable', 'MutableDenseHashTableV2',
'VarHandleOp', 'BoostedTreesEnsembleResourceHandleOp'}
# Find subgraph ops
ops = tf.contrib.graph_editor.get_backward_walk_ops(outputs, stop_at_ts=mappings.keys())
# Exclude non-replicable operations
ops_replicate = [op for op in ops if op.type not in NON_REPLICABLE]
# Make subgraph viewitems
sgv = tf.contrib.graph_editor.make_view(*ops_replicate)
# Make the copy
_, info = tf.contrib.graph_editor.copy_with_input_replacements(sgv, mappings)
# Return new outputs
return info.transformed(outputs)

举一个与您类似的示例(我对其进行了一些编辑,因此很容易看出输出是正确的,因为第二个值是第一个值的十倍)。

import tensorflow as tf

def some_function(x):
w = tf.Variable(initial_value=tf.random_normal((5,)), dtype=tf.float32)
return 2 * (x * w)

x1 = tf.placeholder(shape=(), dtype=tf.float32, name='X1')
x2 = tf.placeholder(shape=(), dtype=tf.float32, name='X2')
y1 = some_function(x1)
y2, = replicate_subgraph([y1], {x1: x2})
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(*sess.run([y1, y2], feed_dict={x1: 1, x2: 10}), sep='\n')

输出:

[ 2.3356955   2.277849    0.58513653  2.0919807  -0.15102367]
[23.356955 22.77849 5.851365 20.919807 -1.5102367]
<小时/>

编辑:

这是使用 tf.make_template 的另一个解决方案。这要求您实际拥有该函数的代码,但这是支持子图重用的更干净且“更官方”的方式。

import tensorflow as tf

def some_function(x):
w = tf.get_variable('W', (5,), initializer=tf.random_normal_initializer())
# Or if the variable is only local and not trainable
# w = tf.Variable(initial_value=tf.random_normal(5,), dtype=tf.float32, trainable=False)
return 2 * (x * w)

x1 = tf.placeholder(shape=(), dtype=tf.float32, name='X1')
x2 = tf.placeholder(shape=(), dtype=tf.float32, name='X2')
some_function_tpl = tf.make_template('some_function', some_function)
y1 = some_function_tpl(x1)
y2 = some_function_tpl(x2)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
print(*sess.run([y1, y2], feed_dict={x1: 1, x2: 10}), sep='\n')

关于python - Tensorflow:将现有图多次复制到新图中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53209495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com