gpt4 book ai didi

Tensorflow 从元图中打印所有占位符变量名称

转载 作者:行者123 更新时间:2023-12-03 00:42:48 27 4
gpt4 key购买 nike

我有一个 tensorflow 模型,其中有 .meta 和检查点文件。我试图打印模型所需的所有占位符,而不查看构建模型的代码,以便我可以在不知道模型是如何创建的情况下构建输入 feed_dict 。作为引用,这里是模型构建代码(在另一个文件中)

def save():
import tensorflow as tf
v1 = tf.placeholder(tf.float32, name="v1")
v2 = tf.placeholder(tf.float32, name="v2")
v3 = tf.multiply(v1, v2)
vx = tf.Variable(10.0, name="vx")
v4 = tf.add(v3, vx, name="v4")
saver = tf.train.Saver()
sess = tf.Session()
sess.run(tf.initialize_all_variables())
sess.run(vx.assign(tf.add(vx, vx)))
result = sess.run(v4, feed_dict={v1:12.0, v2:3.3})
print(result)
saver.save(sess, "./model_ex1")

现在在另一个文件中,我有以下代码要恢复

def restore():
import tensorflow as tf
saver = tf.train.import_meta_graph("./model_ex1.meta")
print(tf.get_default_graph().get_all_collection_keys())
for v in tf.get_default_graph().get_collection("variables"):
print(v)
for v in tf.get_default_graph().get_collection("trainable_variables"):
print(v)
sess = tf.Session()
saver.restore(sess, "./model_ex1")
result = sess.run("v4:0", feed_dict={"v1:0": 12.0, "v2:0": 4.0})
print(result)

但是,当我按上述方式打印所有变量时,我在任何地方都看不到“v1:0”和“v2:0”作为变量名称。如何在不查看创建模型的代码的情况下识别张量名称占位符具有哪些内容?

最佳答案

mrry's answer是很棒的。第二个解决方案确实有帮助。但Placeholder的op名称在不同的TensorFlow版本中会发生变化。以下是我在 .meta 文件的 Graphdef 部分查找正确占位符操作名称的方法:

saver = tf.train.import_meta_graph('some_path/model.ckpt.meta')
imported_graph = tf.get_default_graph()
graph_op = imported_graph.get_operations()
with open('output.txt', 'w') as f:
for i in graph_op:
f.write(str(i))

output.txt文件中,我们可以轻松找到占位符的正确操作名称和其他属性。这是我的输出文件的一部分:

name: "input/input_image"
op: "Placeholder"
attr {
key: "dtype"
value {
type: DT_FLOAT
}
}
attr {
key: "shape"
value {
shape {
dim {
size: -1
}
dim {
size: 112
}
dim {
size: 112
}
dim {
size: 3
}
}
}
}

显然,在我的tensorflow版本(1.6)中,正确的占位符操作名称是Placeholder。现在回到 mrry 的解决方案。使用 [x for x in tf.get_default_graph().get_operations() if x.type == "Placeholder"] 获取所有占位符操作的列表。

因此,仅使用ckpt文件即可轻松方便地进行推理操作,而无需重建模型。例如:

input_x = ... # prepare the model input

saver = tf.train.import_meta_graph('some_path/model.ckpt.meta')
graph_x = tf.get_default_graph().get_tensor_by_name('input/input_image:0')
graph_y = tf.get_default_graph().get_tensor_by_name('layer19/softmax:0')
sess = tf.Session()
saver.restore(sess, 'some_path/model.ckpt')

output_y = sess.run(graph_y, feed_dict={graph_x: input_x})

关于Tensorflow 从元图中打印所有占位符变量名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44251328/

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