我有张量流模型,我有.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")
Run Code Online (Sandbox Code Playgroud)
现在在另一个文件中,我有以下代码要恢复
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)
Run Code Online (Sandbox Code Playgroud)
但是,当我打印所有变量时,我不会在任何地方看到"v1:0"和"v2:0"作为变量名称.如何在不查看创建模型的代码的情况下识别占位符的张量名称?
mrry的答案很好。第二种解决方案确实有帮助。但是,占位符的操作名称会在不同的TensorFlow版本中更改。这是我在.meta
文件的Graphdef部分中找到正确的占位符op名称的方法:
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))
Run Code Online (Sandbox Code Playgroud)
在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
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
显然,在我的tensorflow版本(1.6)中,正确的占位符op名称为Placeholder
。现在返回到mrry的解决方案。使用[x for x in tf.get_default_graph().get_operations() if x.type == "Placeholder"]
让所有的占位符OPS的列表。
因此,仅需使用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})
Run Code Online (Sandbox Code Playgroud)
张量v1:0
和v2:0
是从tf.placeholder()
操作创建的,而只有tf.Variable
对象被添加到"variables"
(或"trainable_variables"
) 集合中。没有可tf.placeholder()
添加操作的通用集合,因此您的选项是:
将操作添加tf.placeholder()
到集合中(tf.add_to_collection()
在构造原始图时使用。您可能需要添加更多元数据才能建议如何使用占位符。
用于[x for x in tf.get_default_graph().get_operations() if x.type == "PlaceholderV2"]
在导入元图后获取占位符操作列表。
归档时间: |
|
查看次数: |
7867 次 |
最近记录: |