【Tensorflow】tf.Graph()函数

本文介绍TensorFlow作为谷歌研发的第二代人工智能学习系统的背景及其应用领域,并深入讲解tf.Graph()函数的重要性和使用方法,包括如何声明、保存和从PB文件加载Graph。

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

TensorFlow是谷歌基于DistBelief进行研发的第二代人工智能学习系统,其命名来源于本身的运行原理。Tensor(张量)意味着N维数组,Flow(流)意味着基于数据流图的计算,TensorFlow为张量从流图的一端流动到另一端计算过程。TensorFlow是将复杂的数据结构传输至人工智能神经网中进行分析和处理过程的系统。

TensorFlow可被用于语音识别图像识别等多项机器深度学习领域,对2011年开发的深度学习基础架构DistBelief进行了各方面的改进,它可在小到一部智能手机、大到数千台数据中心服务器的各种设备上运行。TensorFlow将完全开源,任何人都可以用。

原生接口文章

  1. 【Tensorflow】tf.placeholder函数
  2. 【TensorFlow】tf.nn.conv2d是怎样实现卷积的
  3. 【TensorFlow】tf.nn.max_pool实现池化操作
  4. 【Tensorflow】tf.nn.relu函数
  5. 【Tensorflow】tf.reshape 函数
  6. 【Tensorflow】tf.nn.dropout函数
  7. 【Tensorflow】tf.argmax函数
  8. 【Tensorflow】tf.cast 类型转换 函数
  9. 【Tensorflow】tf.train.AdamOptimizer函数
  10. 【Tensorflow】tf.Graph()函数
  11. 【TensorFlow】tf.nn.softmax_cross_entropy_with_logits的用法
  12. 【Tensorflow】tf.dynamic_partition 函数 分拆数组
     原生接口实例

  1. 【Tensorflow】实现简单的卷积神经网络CNN实际代码
  2. 【Tensorflow 实战】实现欧式距离
         slim接口文章

  1. 【Tensorflow】tensorflow.contrib.slim 包
  2. 【Tensorflow slim】 slim.arg_scope的用法
  3. 【Tensorflow slim】slim.data包
  4. 【Tensorflow slim】slim evaluation 函数
  5. 【Tensorflow slim】slim layers包
  6. 【Tensorflow slim】slim learning包
  7. 【Tensorflow slim】slim losses包
  8. 【Tensorflow slim】slim nets包
  9. 【Tensorflow slim】slim variables包
  10. 【Tensorflow slim】slim metrics包
        slim 实例

  1. 【Tensorflow slim 实战】写MobileNet
  2. 【Tensorflow slim 实战】写Inception-V4 Inception-ResNet-v2结构
         kera 接口文章

  1. 【Tensorflow keras】Keras:基于Theano和TensorFlow的深度学习库
  2. 【Tensorflow keras】轻量级深度学习框架 Keras简介
         tensorflow使用过程中的辅助接口或通过tensorflow实现的批量操作接口

  1. 将非RGB图片转换为RGB图片
  2. 【opencv】python3 将图片生成视频文件
  3. 【opencv】selective_search函数

=========================================================================



tf.Graph() 函数非常重要,注意提现在两个方面

1. 它可以通过tensorboard用图形化界面展示出来流程结构

2. 它可以整合一段代码为一个整体存在于一个图中


声明情况大体有三种

1. tensor:通过张量本身直接出graph

# -*- coding: utf-8 -*-  
import tensorflow as tf

c = tf.constant(4.0)

sess = tf.Session()
sess.run(tf.global_variables_initializer())
c_out = sess.run(c)
print(c_out)
print(c.graph == tf.get_default_graph())
print(c.graph)
print(tf.get_default_graph())
输出

4.0
True
<tensorflow.python.framework.ops.Graph object at 0x7f382f9ef110>
<tensorflow.python.framework.ops.Graph object at 0x7f382f9ef110>

2.通过声明一个默认的,然后定义张量内容,在后面可以调用或保存

# -*- coding: utf-8 -*-  
import tensorflow as tf

g = tf.Graph()
with g.as_default():
    c = tf.constant(4.0)

sess = tf.Session(graph=g)
c_out = sess.run(c)
print(c_out)
print(g)
print(tf.get_default_graph())

输出

4.0
<tensorflow.python.framework.ops.Graph object at 0x7f65f1cb2fd0>
<tensorflow.python.framework.ops.Graph object at 0x7f65de447c90>

3.通过多个声明,在后面通过变量名来分别调用

# -*- coding: utf-8 -*-  
import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    c1 = tf.constant(4.0)

g2 = tf.Graph()
with g2.as_default():
    c2 = tf.constant(20.0)

with tf.Session(graph=g1) as sess1:
    print(sess1.run(c1))
with tf.Session(graph=g2) as sess2:
    print(sess2.run(c2))

输出

4.0
20.0

对graph的操作大体有三种

1.保存

# -*- coding: utf-8 -*-  
import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    # 需要加上名称,在读取pb文件的时候,是通过name和下标来取得对应的tensor的
    c1 = tf.constant(4.0, name='c1')

g2 = tf.Graph()
with g2.as_default():
    c2 = tf.constant(20.0)

with tf.Session(graph=g1) as sess1:
    print(sess1.run(c1))
with tf.Session(graph=g2) as sess2:
    print(sess2.run(c2))

# g1的图定义,包含pb的path, pb文件名,是否是文本默认False
tf.train.write_graph(g1.as_graph_def(),'.','graph.pb',False)

输出

4.0
20.0
并且在当前文件夹下面生成graph.pb文件

2.从pb文件中调用

# -*- coding: utf-8 -*-  
import tensorflow as tf
from tensorflow.python.platform import gfile

#load graph
with gfile.FastGFile("./graph.pb",'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    tf.import_graph_def(graph_def, name='')

sess = tf.Session()
c1_tensor = sess.graph.get_tensor_by_name("c1:0")
c1 = sess.run(c1_tensor)
print(c1)

输出

4.0

3.穿插调用

# -*- coding: utf-8 -*-  
import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    # 声明的变量有名称是一个好的习惯,方便以后使用
    c1 = tf.constant(4.0, name="c1")

g2 = tf.Graph()
with g2.as_default():
    c2 = tf.constant(20.0, name="c2")

with tf.Session(graph=g2) as sess1:
    # 通过名称和下标来得到相应的值
    c1_list = tf.import_graph_def(g1.as_graph_def(), return_elements = ["c1:0"], name = '')
    print(sess1.run(c1_list[0]+c2))

输出

24.0

当然还有很多比较好的地方,比如graph中自带的名称函数,通过with写的内容丰富的代码块,这里就不讲了

<think>嗯,用户遇到了TensorFlow版本兼容的问题。错误信息显示他们正在使用TensorFlow v1的API,但可能在v2环境中运行。首先,我需要确认错误的具体原因。根据日志,`graph_util.convert_variables_to_constants`属性不存在,这说明该模块在v2中可能已被弃用或移动。 接下来,应该回忆一下TensorFlow v1到v2的主要变化。v2默认启用了Eager Execution,而v1的许多API如`graph_util`相关函数可能被移到了`compat.v1`模块下,或者需要启用v1兼容模式。此外,错误提示建议迁移到v2,所以用户可能需要更新代码以适应v2的API。 用户提到的代码中使用了`convert_variables_to_constants`,这在v1中属于`graph_util`,但在v2中可能需要通过`tf.compat.v1.graph_util`来访问。另外,用户是否已经尝试过使用兼容性模块?或者是否有未正确导入的情况? 另外,用户可能没有禁用v2的行为,比如Eager Execution,导致旧代码无法运行。建议用户检查是否在代码开头启用了v1兼容模式,例如使用`tf.compat.v1.disable_eager_execution()`。 此外,用户提到的迁移指南链接是关键资源,可能需要引导他们按照步骤迁移代码。可能还需要建议他们使用`tf_upgrade_v2`工具来自动转换部分代码。同时,错误追踪显示问题出现在`convertonnx.py`的第22行,所以具体查看该行代码是否有其他v1特有的函数需要替换。 最后,用户可能是在尝试将模型转换为ONNX格式,所以除了修复TensorFlow代码,还需要确保使用的转换工具(如tf2onnx)支持TensorFlow v2。如果工具依赖v1代码,可能需要寻找替代方法或更新工具版本。</think>你遇到的错误是由于TensorFlow版本兼容性问题导致的。我来分步骤解释问题原因和解决方案: ======================== 👉 错误原因分析 ======================== 1. **API版本冲突** 错误信息`AttributeError: module 'tensorflow...graph_util' has no attribute 'convert_variables_to_constants'`表明你正在使用TensorFlow v2的环境,但代码中调用了TensorFlow v1的API。 2. **弃用函数定位** `graph_util.convert_variables_to_constants()`是TensorFlow v1的图操作API,在TensorFlow v2中已被移除或重构。 ======================== 🛠️ 解决方案步骤 ======================== 1. **启用TensorFlow v1兼容模式** 在代码开头添加以下两行(临时方案): ```python import tensorflow.compat.v1 as tf tf.disable_v2_behavior() ``` 2. **修改函数导入方式** 将原来的`graph_util.convert_variables_to_constants`改为: ```python from tensorflow.python.framework import graph_util frozen_graph = graph_util.convert_variables_to_constants(...) ``` 3. **推荐长期方案:迁移到TensorFlow v2** ```python # 新的v2 API实现冻结图操作 from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2 frozen_func = convert_variables_to_constants_v2(model.get_concrete_function()) frozen_graph = frozen_func.graph ``` 4. **其他注意事项** - 如果使用`tf.Session()`,需要改为v2的`tf.compat.v1.Session()` - 检查所有`tf.placeholder`等v1特性是否已替换为`tf.function` - 建议运行官方迁移工具: ```bash tf_upgrade_v2 --infile your_script.py --outfile migrated_script.py ``` ======================== 📚 附加建议 ======================== 1. **版本检查** 通过`print(tf.__version__)`确认当前环境版本,建议使用v2.8+版本 2. **ONNX转换优化** 如果是为转换为ONNX格式,推荐直接使用TensorFlow v2的SavedModel格式: ```python tf.saved_model.save(model, "saved_model_dir") ``` 然后使用`tf2onnx`工具转换: ```bash python -m tf2onnx.convert --saved-model saved_model_dir --output model.onnx ``` 建议优先参考官方迁移指南:[TensorFlow迁移文档](https://www.tensorflow.org/guide/migrate)
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值