tensorflow数据流图

数据流图如下所示

什么是数据流图(Data Flow Graph)?

官方的解释为:数据流图用“结点”(nodes)和“线”(edges)的有向图来描述数学计算。“节点” 一般用来表示施加的数学操作,但也可以表示数据输入(feed in)的起点/输出(push out)的终点,或者是读取/写入持久变量(persistent variable)的终点。“线”表示“节点”之间的输入/输出关系。这些数据“线”可以输运“size可动态调整”的多维数据数组,即“张量”(tensor)。张量从图中流过的直观图像是这个工具取名为“Tensorflow”的原因。一旦输入端的所有张量准备好,节点将被分配到各种计算设备完成异步并行地执行运算。

直接打印tensor相加之和,没有得到相加的结果

 定义一个op之后得到一个tensor,tensor包含的是op

import tensorflow as tf
import os

con_a = tf.constant(3)
con_b = tf.constant(4)

con_c = tf.add(con_a,con_b)

print(con_c) #Tensor("Add:0", shape=(), dtype=int32)

返回的结果为Tensor("Add:0", shape=(), dtype=int32),而不是结果预期的数值

需要得到结果的话需要开启会话

如果我们要得到运行结果,需要进行下面开启会话执行op的代码

import tensorflow as tf
import os

con_a = tf.constant(3)
con_b = tf.constant(4)

con_c = tf.add(con_a,con_b)
#开启会话,执行op
with tf.Session() as ss:
    print(ss.run(con_c))

得到的结果为数值7。

会话是什么?

tensorflow底层是c++写的,而我们写的代码是python代码,所谓会话便是连接python和c++的地方。

关于op与tensor

op其实是操作,tensor张量的本质是n维数组。

tensor和session都有grap图属性,通过graph来获取图属性,如果不特殊指定,都在默认的图中执行

import tensorflow as tf

con_a = tf.constant(3)
con_b = tf.constant(4)

con_c = tf.add(con_a,con_b)
print(con_a.graph)
print(con_b.graph)
print(con_c.graph)

g = tf.Graph()
with tf.Session() as ss:
    print(ss.graph)
    
'''
<tensorflow.python.framework.ops.Graph object at 0x000000000239F390>
<tensorflow.python.framework.ops.Graph object at 0x000000000239F390>
<tensorflow.python.framework.ops.Graph object at 0x000000000239F390>
<tensorflow.python.framework.ops.Graph object at 0x000000000239F390>
'''
    

使用get_default_graph()获取默认图的地址

import tensorflow as tf

con_a = tf.constant(3)
con_b = tf.constant(4)

con_c = tf.add(con_a,con_b)
print(con_c.graph)
print(tf.get_default_graph())
g = tf.Graph()
with tf.Session() as ss:
    print(ss.graph)
'''
<tensorflow.python.framework.ops.Graph object at 0x000000000258F390>
<tensorflow.python.framework.ops.Graph object at 0x000000000258F390>
<tensorflow.python.framework.ops.Graph object at 0x000000000258F390>
'''

使用tf.Graph()创建自定义图来运行数据

在这里我们要先创建图,创建完成后在图中定义tensor和op,之后使用with tf.Session(graph=g) as ss来开启graph指定要运行的图。

import tensorflow as tf

# 创建图
g = tf.Graph()
with g.as_default():
    #在创建的图中定义tensor和op
    g_a = tf.constant(5.0)
    print(g_a)
    #Tensor("Const:0", shape=(), dtype=float32)

#开启graph指定要运行的图,如果我们想要得到运行的结果,必须进行下面这段代码
with tf.Session(graph=g) as ss:
    print(ss.run(g_a)) #5.0

在上述代码大体分成两个阶段

1.构建图阶段

2.执行图阶段

关于结果标红问题

代码运行可能出现下面的结果:I T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2

这时候加入下面两句话即可解决这个问题:

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值