gpt4 book ai didi

tensorflow - 使用 tf.contrib.graph_editor 克隆网络

转载 作者:行者123 更新时间:2023-12-04 02:23:09 39 4
gpt4 key购买 nike

我有一个像这样构建网络的功能。

def build_network(inputs):
# Some arbitrary set of variables and ops here. For example...
out = tf.contrib.layers.fully_connected(inputs, 123)
(...)
return out

然后我用它来构建这样的网络。
inputs = tf.placeholder(...)
outputs = build_network(inputs)

如果我想构建更多具有相同结构但独立变量的网络,我只需要在其他变量范围和可选的其他输入下再次调用 build_network 。

我的问题是:如果此 build_network 不再可用,但原始网络的输入和输出可用,我该怎么做?换句话说:我怎样才能将整个子图从输出克隆到输入到另一个变量范围内,它有自己独立的变量集但结构相同?

我的理解是 tf.contrib.graph_editor 尤其是 graph_editor.copy 正是我需要做这些事情的工具。但是,我找不到任何使用它们的好例子。有什么建议?

最佳答案

回应我自己,我找到了一种复制子图的方法。

from tensorflow.contrib import graph_editor as ge

# From the example above.
inputs = [tf.placeholder(...), ...]
outputs = build_network(inputs)

sgv = ge.make_view(ge.get_within_boundary_ops(
tf.get_default_graph(),
[t.op for t in outputs],
[t.op for t in inputs]))

# This could be any new inputs. In this example I build new identical placeholders.
new_inputs = {p: tf.placeholder(dtype=p.dtype, shape=p.shape) for p in inputs}
new_sgv, info = ge.copy_with_input_replacements(sgv, new_inputs, dst_scope='copy')

new_inputs = [info.transformed(t) for t in inputs]
new_outputs = [info.transformed(t) for t in outputs]

但是,现在我在尝试使用网络副本时遇到了一个新问题。副本中的新变量未初始化,尝试运行 tf.global_variables_initializer() 也无济于事。

原因是因为它们的 tf.Variable 从未构建过,所以它们不是 GlobalKeys.GLOBAL_VARIABLES 集合的一部分。我可以轻松找到与这些变量对应的操作以及它们在原始和副本之间的映射,但我无法从中构建 tf.Variable。

我发现了一些进行初始化的 hacky 解决方法,但它仅适用于集合中的 vars。
init_ops = []
for v in tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES):
if v.op in sgv.ops:
init_ops.append(info.transformed(v.initializer))

...

session.run([tf.global_variables_initializer()] + init_ops)

有没有更好的方法来做到这一点?理想情况下,允许为复制的变量创建 tf.Variables 以将它们添加到全局变量集合中。或者,如果这是不可能的,至少是一种获得初始化操作的可靠方法,而无需找到原始网络的 tf.Variable 对象。

关于tensorflow - 使用 tf.contrib.graph_editor 克隆网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45896284/

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