TensorFlow入门:计算图和梯度流
背景:
边缘:输入或者输出参数
节点:是指的中间的操作过程
之后创建一个Graph,再然后在session中运行。我们也可以将训练的结果保存为一个Graph,然后将这个流图给到第三方去运行,同时第三方不必知道训练的过程
梯度流就是一个逐级求导的过程
代码演示:
#coding=utf-8
import tensorflow as tf
import numpy as np
import cv2 as cv
from tensorflow.python.platform import gfile
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def graphs_demo():
# 创建3个常量
a = tf.constant(4.0)
b = tf.constant(5.0)
c = tf.constant(6.0)
# 在default的流图中计算result=a*b+c
result = tf.add(tf.multiply(a, b), c)
# 创建流图g1和g2
g1 = tf.Graph()
g2 = tf.Graph()
# 在流图g1中计算result1
with g1.as_default():
a = tf.constant([3, 4])
b = tf.constant([7, 8])
result1 = tf.add(a, b, name="result_01")
# 在流图g2中计算result2
with g2.as_default():
a = tf.constant([.3, .4])
b = tf.constant([.7, .8])
result2 = tf.add(a, b, name="result_01")
# 创建一个针对g1的session,并在session中运行result1
with tf.Session(graph=g1) as sess:
print("g1 = ", sess.run(result1))
# 创建一个针对g2的session,并在session中运行result2
with tf.Session(graph=g2) as sess:
print("g2 = ", sess.run(result2))
# 创建一个针对default的session,并在session中运行result
with tf.Session() as sess:
ret = sess.run(result)
print("result : ", ret)
"""
这个比较有意思
1.将g1的训练模型保存在当前目录,并命名为"graph1.pb",结果是序列化文件可以跨平台使用的
2.通过gfile将训练模型读取到f中
3.创建一个空的流图
4.从f中将训练模型导入到新定义的流图中
"""
tf.train.write_graph(g1.as_graph_def(), ".", "graph1.pb", False)
with gfile.FastGFile("./graph1.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
# 创建一个会话
sess = tf.Session()
# 通过名称获取张量
result1_tensor = sess.graph.get_tensor_by_name("result_01:0")
# 运行这个训练模型,你将得到和之前在g1中相同的结果
ret1 = sess.run(result1_tensor)
print(ret1)
graphs_demo()
结果如下:
('g1 = ', array([10, 12], dtype=int32))
('g2 = ', array([1. , 1.2], dtype=float32))
('result : ', 26.0)
[10 12]