A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

数据流图如下所示

什么是数据流图(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'


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马