tensorflow学习进击:一步一个脚印我爱编程

tensorflow 1. 人生只若如hello

2018-03-13  本文已影响36人  YuanLulu

这里的例子包含在:https://github.com/aymericdamien/TensorFlow-Examples/tree/master/examples/1_Introduction

官方的入门讲解在:http://www.tensorfly.cn/tfdoc/get_started/basic_usage.html

使用 TensorFlow, 你必须明白 TensorFlow:
对于程序员来说,“hello world”形式的例子几乎是一种学习新技术的仪式。
tensorflow版的"开机仪式"代码如下:
import tensorflow as tf

#定义一个常量操作节点,
hello = tf.constant("hello, TensorFlow2018!")

#获取一个会话
sess = tf.Session()

#启动会话运行hello节点
print(sess.run(hello))
# 任务完成, 关闭会话.
sess.close()

#输出内容为:b'hello, TensorFlow2018!'

下面这个例子牵涉到的概念更全面:

import tensorflow as tf 

#定义两个常量操作
#构造函数返回的值就是常量节点(Constant op)的输出
a = tf.constant(2)
b = tf.constant(3)

#启动默认的计算图
with tf.Session() as sess:
    print("a = 2, b = 3")
    print("常量相加:{}".format(sess.run(a+b)))
    print("常量相乘:{}".format(sess.run(a*b)))

#使用变量输出值作为计算图的输入
a = tf.placeholder(tf.int16)
b = tf.placeholder(tf.int16)

#定义一些操作
add = tf.add(a, b)
mul = tf.multiply(a, b)

#启动默认的计算图
with tf.Session() as sess:
    print("变量相加:{}".format(sess.run(add, feed_dict={a:2, b:3})))
    print("变量相乘:{}".format(sess.run(mul, feed_dict={a:2, b:3})))


#创建一个1X2的常量矩阵,该op会作为一个节点被加入到默认的计算图
#构造器返回的值代表这个op的输出
matrix1 = tf.constant([[3., 3.]])

#创建一个2X1的常量矩阵
matrix2 = tf.constant([[2.], [2.]])

#创建一个矩阵乘法op,它的输入为matrix1和matrix2
#返回的值product表示乘法的结果
product = tf.matmul(matrix1, matrix2)

#为了运行mutmul op我们运行会话的run()方法,使用product作为输入,product代表mutmul op的输出
#这表明我们想要matmul op的输出

#op的所有输入都会由会话自动运行。这些输入一般都是并行运行的

#对'run(product)'的调用回引起这3个op的执行:2个constants和一个matmul
#op的输出值返回给result,这是一个numpy数组对象
with tf.Session() as sess:
    result = sess.run(product)
    print("矩阵常量相称:{}".format(result))

输出内容为:

a = 2, b = 3
常量相加:5
常量相乘:6
变量相加:5
变量相乘:6
矩阵常量相称:[[ 12.]]

知识总结

tensorflow的基本概念就是数据流图,使用tensorflow的步骤就是:
  1. 构建数据流图
  2. 运行数据流图
数据流图由两种基础构建组成:

下面借用http://www.tensorfly.cn/的一段描述.

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

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


image
运行数据流图需要在会话(session)中进行,常用的创建方式是:

with tf.Session() as sess或者sess = tf.Session()

运行数据流图过程会执行各种操作,借用studyAi网站的一副图片:


image

如果机器上有超过一个可用的 GPU, 除第一个外的其它 GPU 默认是不参与计算的. 为了让 TensorFlow 使用这些 GPU, 你必须将 op 明确指派给它们执行. with...Device 语句用来指派特定的 CPU 或 GPU 执行操作:

with tf.Session() as sess:
  with tf.device("/gpu:1"):
    matrix1 = tf.constant([[3., 3.]])
    matrix2 = tf.constant([[2.],[2.]])
    product = tf.matmul(matrix1, matrix2)
    ...

设备用字符串进行标识. 目前支持的设备包括:

与数据相关的op由三种:

使用Variable的使用必须先经过初始化 (init) op 初始化

init_op = tf.global_variables_initializer()
with tf.Session() as sess:
  # 运行 'init' op
  sess.run(init_op)
注意不要使用tf.initialize_all_variables()了。否则会有警告,这个接口正在被抛弃
上一篇下一篇

猜你喜欢

热点阅读