计算模型-图、数据模型-张量、运算模型-会话

计算模型-图
计算模型使用图来隔离数据,tf有一个默认的图,如果不创建图,就会使用默认的图。

import tensorflow as tf
a=tf.constant([1.0,2.0])
print(a.graph is tf.get_default_graph())

输出:True
说明a这个常量在默认的图里。


import tensorflow as tf
import numpy as np
print("default_graph:",tf.get_default_graph())
c=tf.constant(value=1)
print("default_graph:",c.graph)

# 新建图1
new_graph1=tf.Graph()
print("new_graph1:",new_graph1)
with new_graph1.as_default():
  # 新建图1上下文
  d=tf.constant(value=2)
  print("new_graph1:",d.graph)


# 新建图2
new_graph2=tf.Graph()
print("new_graph2:",new_graph2)

# e还是默认的图
e=tf.constant(value=15)
print("default_graph:",e.graph)

数据模型-张量

tensorflow里面的数据都可以用张量来表示,简单理解张量为多维数组,但在tensorflow里张量不是用数组实现,它只是对运算结果的引用。
import tensorflow as tf
import numpy as np
a=tf.constant([1.,2.])
b=tf.constant([3.,4.])
result=a+b
print(result)

result是一个张量,它不是数组,输出的结果如下

 Tensor("add:0", shape=(2,), dtype=float32)

add:0 表示计算接口add输出的第一个结果
shape=(2,) 表示一维数组,数组长度为2
dtype 为数据类型

张量主要用来保存中间计算结果,还可以用来获取计算结果。

运行模型-会话

TensorFlow把计算放在GPU,CPU上,输入数据图,结果计算好了再返回。与外部计算资源的交互就是一个会话。
为什么要封装成图,我认为就是为了性能考虑,避免tersorflow与外部计算资料的过多上下文切换,导致性能下降。

import tensorflow as tf
import numpy as np
a=tf.constant([1.,2.])
b=tf.constant([3.,4.])
result=a+b
sess=tf.Session()
with sess.as_default():
  x=sess.run(result)
  print(x)

print(result.eval(session=sess))

输出结果
[4. 6.]
[4. 6.]

原文地址:https://www.cnblogs.com/50614090/p/9972247.html