Tensorflow学习之基本概念

人工智能机器学习

浏览数:492

2019-7-21

栖迟于一丘的《Tensorflow学习之旅》系列文章目录

  tensorflow版本为1.2.1,python版本3.6.1,win10

  1. 计算图

  tensorflow可以看作tensor和flow的集合,tensor即张量,flow是计算模型,二者组成了计算图,tensorflow上的计算就是计算图上的节点,边表示计算表关系。可以通过一个简单的例子查看:

    import tensorflow as tf

    with tf.name_scope("input1"):
        input1 = tf.constant([1.0, 2.0], name="input1")

    with tf.name_scope("input2"):
        input2 = tf.constant([2.0, 3.0], name="input2")

    output = tf.add_n([input1, input2], name="add")

    writer = tf.summary.FileWriter("C:/Users/Administrator/Desktop/test/log/example.log", tf.get_default_graph())

    writer.close()

  上面定义了两个向量并相加,将日志存入指定文件夹。运行后使用tensorboard可视化结果。

  浏览器访问 http://localhost:6006/#graphs

  这就是tensorflow最基本的计算图模式。

  1. 使用计算图

  上面使用的是默认的计算图生成方式,如果需要多个计算图运算,可以tf.Graph()方法生成。

import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    v = tf.get_variable("v", [1], initializer = tf.zeros_initializer()) # 图g1的变量初始值为0

g2 = tf.Graph()
with g2.as_default():
    v = tf.get_variable("v", [1], initializer = tf.ones_initializer())  # 图g2的变量初始值为1

#分别读取g1和g2中的v值,这里的Session定义的是会话    
with tf.Session(graph = g1) as sess:
    tf.global_variables_initializer().run()
    with tf.variable_scope("", reuse=True):
        print(sess.run(tf.get_variable("v")))

with tf.Session(graph = g2) as sess:
    tf.global_variables_initializer().run()
    with tf.variable_scope("", reuse=True):
        print(sess.run(tf.get_variable("v")))
  1. 张量

  张量可以理解为多维数组,定义为一阶就是标量,二阶就是二维数组,较为灵活。

import tensorflow as tf
a = tf.constant([1.0, 2.0], name="a")
b = tf.constant([2.0, 3.0], name="b")
result = a + b
print result
sess = tf.InteractiveSession ()
print(result.eval())
sess.close()

  输出

Tensor(“add:0”, shape=(2,), dtype=float32) [ 3. 5.]

4.会话

  上面的计算都用到了会话(Session),实际上就是定义一个计算过程。

# 创建一个会话。
sess = tf.Session()

# 使用会话得到之前计算的结果。
print(sess.run(result))

# 关闭会话使得本次运行中使用到的资源可以被释放。
sess.close()

用于构建会话的方式不止这一种。

1.使用with statement 来创建会话
with tf.Session() as sess:
    print(sess.run(result))

2.指定默认会话
sess = tf.Session()
with sess.as_default():
     print(result.eval())
     #print(sess.run(result)) 
     #print(result.eval(session=sess))

3.使用tf.InteractiveSession构建会话
sess = tf.InteractiveSession ()
print(result.eval())
sess.close()

4.通过ConfigProto配置会话
config=tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)
sess1 = tf.InteractiveSession(config=config)
sess2 = tf.Session(config=config)

  以上就是tensorflow的基本使用概念。

作者:栖迟于一丘