tensorflow不知代码情况下获取graph的placeholder和output

本文介绍了一种使用TensorFlow 1.6版本从.meta文件中查找正确占位符操作名称的方法,并提供了如何仅使用ckpt文件进行模型推断而无需重建模型的详细步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Here is my way to find out the correct placeholder op name in the Graphdef part of the .meta file:

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))

In the output.txt file, we can easily find out the placeholder’s correct op names and other attrs. Here is part of my output file:

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
}
}
}
}
Obviously, in my tensorflow version(1.6), the correct placeholder op name is Placeholder. Now return back to mrry’s solution. Use [x for x in tf.get_default_graph().get_operations() if x.type == “Placeholder”] to get a list of all the placeholder ops.

Thus it’s easy and convenient to perform the inference operation with only the ckpt files without needing to reconstruct the model. For example:

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 1.x代码迁移到TensorFlow 2.x 为了确保TensorFlow 1.x版本的代码能够在TensorFlow 2.x环境中顺利运行并优化其性能,可以采取以下几种方法: #### 使用兼容模式 一种简单的方式是在新项目中引入旧版行为,通过导入`tensorflow.compat.v1`模块来访问v1 API,并禁用v2默认的行为设置。这允许开发者逐步调整现有程序而不必立即重写整个应用程序。 ```python import tensorflow.compat.v1 as tf tf.disable_v2_behavior() ``` 这种方式虽然可以让大部分功能正常运作,但是并不能充分发挥TensorFlow 2.x的优势特性[^4]。 #### 自动转换工具的应用 官方提供了自动化的脚本帮助完成从1.x到2.x的主要改动,比如移除session机制、改变变量初始化方式等。这些更改有助于使模型更好地适应新的框架结构。 #### 手工修改与最佳实践遵循 对于追求更高效率稳定性的场景,则需手动审查源码中的每一处细节,特别是涉及到会话管理(`Session`)的部分以及图构建(Graph Construction),因为这些都是TF2所摒弃的概念;同时也要注意API接口的变化,例如损失函数(loss function)定义形式的不同之处。此外,在TF2里,度量(Metrics)被设计成了类的形式,可以在急切执行(eager execution)环境或是由`@tf.function`装饰器包裹起来的功能内实例化使用[^3]。 #### 更新依赖库支持硬件加速 考虑到某些新型号GPU仅能良好配合较新版软件工作的情况——像NVIDIA GeForce RTX 3090就只能很好地支持TF2及以上版本——因此当目标平台更换了更先进的图形处理单元时,也应当同步升级至相应的深度学习框架版本以获得更好的计算资源利用率[^5]。 #### 示例代码片段展示迁移过程的一部分 这里给出一段简单的例子说明如何把基于placeholder/session风格编写的训练循环转变为更加简洁直观的新样式: **原TensorFlow 1.x风格** ```python # TensorFlow 1.x style with placeholders and sessions input_placeholder = tf.placeholder(tf.float32, shape=[None]) output_placeholder = tf.placeholder(tf.int64, shape=[None]) logits = ... # some operations on input_placeholder loss = tf.reduce_mean( tf.nn.sparse_softmax_cross_entropy_with_logits(labels=output_placeholder, logits=logits)) train_op = optimizer.minimize(loss) with tf.Session() as sess: sess.run(train_op, feed_dict={input_placeholder: inputs_batch, output_placeholder: labels_batch}) ``` **改进后的TensorFlow 2.x风格** ```python # TensorFlow 2.x eager execution or within @tf.function scope inputs_tensor = tf.convert_to_tensor(inputs_batch) labels_tensor = tf.convert_to_tensor(labels_batch) def compute_loss(model, x, y): predictions = model(x) per_example_loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)(y_true=y, y_pred=predictions) return tf.reduce_mean(per_example_loss) optimizer.apply_gradients(zip(gradients_of_trainable_variables, model.trainable_variables)) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值