东方耀AI技术分享

标题: 08、TensorFlow图的执行阶段及代码案例_笔记 [打印本页]

作者: 东方耀    时间: 2018-9-11 17:56
标题: 08、TensorFlow图的执行阶段及代码案例_笔记



08、TensorFlow图的执行阶段及代码案例_笔记

  1. # -*- coding: utf-8 -*-
  2. __author__ = 'dongfangyao'
  3. __date__ = '2018/9/10 下午7:33'
  4. __product__ = 'PyCharm'
  5. __filename__ = 'tf02'

  6. import os
  7. import tensorflow as tf
  8. # 这是默认的显示等级,显示所有信息
  9. # os.environ["TF_CPP_MIN_LOG_LEVEL"] = '1'
  10. # 只显示 warning 和 Error
  11. os.environ["TF_CPP_MIN_LOG_LEVEL"] = '2'
  12. # 只显示 Error
  13. # os.environ["TF_CPP_MIN_LOG_LEVEL"] = '3'


  14. # 1、定义常量矩阵a b

  15. a = tf.constant([[1, 2], [3, 4]], dtype=tf.int32)

  16. print(type(a))

  17. b = tf.constant([5, 6, 7, 8], dtype=tf.int32, shape=[2, 2])


  18. # 2、以a b 作为输入 进行矩阵的乘法操作

  19. c = tf.matmul(a, b)

  20. print(type(c))
  21. # print(c)

  22. print('变量a是否在默认图中:{}'.format(a.graph is tf.get_default_graph()))

  23. # 使用新的 构建的图 而不是默认图
  24. graph1 = tf.Graph()

  25. with graph1.as_default():
  26.     # 此时在这个代码块中,使用的就是新定义的图graph1
  27.     d = tf.constant(5.0, name='d')
  28.     print('变量d是否在新图graph1中:{}'.format(d.graph is graph1))

  29. print('变量d是否在默认图中:{}'.format(d.graph is tf.get_default_graph()))

  30. graph2 = tf.Graph()

  31. with graph2.as_default():
  32.     e = tf.constant(3.0, name='e')
  33.     print('变量e是否在新图graph2中:{}'.format(e.graph is graph2))

  34. # 注意:不能使用两个图中的变量进行操作
  35. # f = tf.add(d, e)

  36. # 3、以c和a作为输入 进行矩阵的相加操作

  37. g = tf.add(a, c, name='add')
  38. print(type(g))
  39. print(g)

  40. # 增加的操作 复杂点
  41. h = tf.subtract(b, a, name='b-a')
  42. i = tf.matmul(h, c, name='h_cheng_c')
  43. j = tf.add(g, i, name='g_jia_i')


  44. # 4、会话的创建、启动、关闭(默认情况下,创建的session属于默认图)
  45. # sess = tf.Session(graph=tf.get_default_graph())
  46. sess = tf.Session()
  47. # print(sess)

  48. # 调用sess的run方法执行矩阵的乘法,得到c的结果值(所以需要将c作为参数传递进去)
  49. # 不需要考虑图中间的运算,在运行的时候只需要关注最终结果对应的对象以及所需要的输入数据值
  50. # 会自动的根据图中的依赖关系触发所有相关的op操作的执行

  51. # 如果op之间没有依赖关系,TensorFlow底层会自动的并行的执行op(前提是有资源)
  52. # result = sess.run(j)
  53. # print('type:{}, value:\n{}'.format(type(result), result))

  54. # 如果还需要得到c的结果
  55. # result2 = sess.run(c)
  56. # print(result2)
  57. # 如果传递的fetches是一个列表(顺序没有任何关系),那么返回值是一个list集合
  58. result3 = sess.run([j, c])
  59. print('type:{}, value:\n{}'.format(type(result3), result3))

  60. # 会话的关闭
  61. sess.close()

  62. # 当一个会话关闭后,不能再使用了,所以下面的代码错误
  63. # RuntimeError: Attempted to use a closed Session.
  64. # result4 = sess.run(c)
  65. # print(result4)

  66. with tf.Session() as sess2:
  67.     print(sess2)
  68.     # 获取张量c的结果:通过Session的run方法
  69.     print('sess2 run:\n{}'.format(sess2.run(c)))
  70.     # 获取张量c的结果:通过张量对象的eval方法 与通过Session的run方法 一致
  71.     print('c eval:\n{}'.format(c.eval()))



  72. # 交互式会话构建
  73. # sess3 = tf.InteractiveSession()
  74. # print(j.eval())





复制代码








欢迎光临 东方耀AI技术分享 (http://www.ai111.vip/) Powered by Discuz! X3.4