【发布时间】:2020-03-30 14:29:59
【问题描述】:
我知道如何加载保存的 TensorFlow 模型,但我如何知道输入和输出张量名称。
我可以使用 tf.import_graph_def 加载 protobuf 文件,然后使用函数 get_tensor_by_name 加载张量,但我如何知道任何预训练模型的张量名称。我需要检查他们的文档还是有其他方法。
【问题讨论】:
标签: tensorflow
我知道如何加载保存的 TensorFlow 模型,但我如何知道输入和输出张量名称。
我可以使用 tf.import_graph_def 加载 protobuf 文件,然后使用函数 get_tensor_by_name 加载张量,但我如何知道任何预训练模型的张量名称。我需要检查他们的文档还是有其他方法。
【问题讨论】:
标签: tensorflow
假设输入和输出张量是占位符,这样的事情应该对你有帮助:
X = np.ones((1,3), dtype=np.float32)
tf.reset_default_graph()
model_saver = tf.train.Saver(defer_build=True)
input_pl = tf.placeholder(tf.float32, shape=[1,3], name="Input")
w = tf.Variable(tf.random_normal([3,3], stddev=0.01), name="Weight")
b = tf.Variable(tf.zeros([3]), name="Bias")
output = tf.add(tf.matmul(input_pl, w), b)
model_saver.build()
sess = tf.Session()
sess.run(tf.global_variables_initializer())
model_saver.save(sess, "./model.ckpt")
现在,图表已构建并保存,我们可以看到如下占位符名称:
model_loader = tf.train.Saver()
sess = tf.Session()
model_loader.restore(sess, "./model.ckpt")
placeholders = [x for x in tf.get_default_graph().get_operations() if x.type == "Placeholder"]
# [<tf.Operation 'Input' type=Placeholder>]
【讨论】:
您可以检查图中每个操作的名称和输入列表,以查找张量的名称。
with tf.gfile.GFile(input_model_filepath, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def)
for op in graph.get_operations():
print(op.name, [inp for inp in op.inputs])
【讨论】:
仅针对输入的解决方案:
# read pb into graph_def
with tf.gfile.GFile(input_model_filepath, "rb") as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
# import graph_def
with tf.Graph().as_default() as graph:
tf.import_graph_def(graph_def)
# print operations
for op in graph.get_operations():
if op.type == "Placeholder":
print(op.name)
【讨论】: