TensorFlow Tutorial: Practical TensorFlow lesson for quick learners - Part 1(译)

这篇教程分为两部分,第一部分用例子解释基础概念,第二部分构建线性回归模型。python

Part-1: TensorFlow基础

TensorFlow是一个数据流通过的图,数据表示为n维向量,图由数据和操做组成。linux

  • 节点:数学操做
  • 边:数据

TensorFlow跟其余编程语言不一样之处在于不论你想建立什么都必须先建立一幅蓝图,默认初始化是不包含任何变量的。编程

 

sankit@sankit:~$ python
Python 2.7.6 (default, Oct 26 2016, 20:30:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 
>>> import tensorflow as tf

  

(i) Graph in TensorFlow:

图是TensorFlow的基石,每个计算,操做,变量都存储在图中,你能够这样使用图:数组

graph = tf.get_default_graph()

 

你能够获取图的所有操做:编程语言

graph.get_operations()  

 

 目前它是空的
 
for op in graph.get_operations(): 
    print(op.name)

 你能够打印出它们的名字,固然在咱们没有添加操做以前,它仍是空的。工具

 固然你能够建立多幅图,但这是以后的事情了。
 

(ii) TensorFlow Session:

图用于定义操做,可是操做必须在会话中执行,它们之间是独立建立的,你能够把图想象为蓝图,把会话想象为建筑工地。this

图只定义了操做,但并无变量,更没有值,只有咱们在会话中运行图,这一切才有意义。spa

你能够像这样建立会话:code

sess=tf.Session()
... your code ...
... your code ...
sess.close()

 

记得必定要关闭会话,或者你能够像这样使用:orm

with tf.Session() as sess:
    sess.run(f)

 

这样会话就自动关闭了,固然咱们也推荐你这样使用。

iii). Tensors in TensorFlow:

 TF使用张量表示数据就像在numpy中使用多维数组同样。

a) 常量:

常量不能改变,像这样定义:

a=tf.constant(1.0)
a
<tf.Tensor'Const:0' shape=() dtype=float32>
 print(a)
Tensor("Const:0", shape=(), dtype=float32)

  

它不能像Python同样打印或者访问,除非你在会话中使用:

with tf.Session() as sess:
    print(sess.run(a))

  

 这将打印1.0

b) 变量:

>>>b = tf.Variable(2.0,name="test_var")
>>>b
<tensorflow.python.ops.variables.Variable object at 0x7f37ebda1990>

  

变量就像常量同样能够设置不一样的值,可是变量经过init op来用做初始化,分别初始化全部变量会显得很麻烦,因此TensorFlow提供了init op

0.11 版本
>>>init_op = tf.initialize_all_variables()
 
0.12 以后的版本
>>>init_op = tf.global_variables_initializer()

 

 如今咱们能够访问变量了
with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(b))

  

这将输出2

如今咱们来打印图的操做:

graph = tf.get_default_graph()
for op in graph.get_operations(): 
    print(op.name)

  

输出:

Const
test_var/initial_value
test_var
test_var/Assign
test_var/read
init

 就像你看到的,由于咱们使用了常量a,因此图中加入了Const.一样由于咱们定义了变量b,因此test_var开头的操做被加入到图中,你可使用名叫TensorBoard的工具来可视化一张图或者训练过程。

c)占位符: 

 等待被初始化或者fed的向量,喂给占位符的叫作feed_dict

>>>a = tf.placeholder("float")
>>>b = tf.placeholder("float")
>>>y = tf.multiply(a, b)
 // Earlier this used to be tf.mul which has changed with Tensorflow 1.0
 
//Typically we load feed_dict from somewhere else, 
 //may be reading from a training data folder. etc
 //For simplicity, we have put values in feed_dict here
>>>feed_dict ={a:2,b:3}
>>>with tf.Session() as sess:
       print(sess.run(y,feed_dict))

  

iv) TensorFlow设施

TensorFlow内建的的能力很是强大,为你提供了运行在GPU或者CPU集群的选择

 

 

 

 reference:https://cv-tricks.com/artificial-intelligence/deep-learning/deep-learning-frameworks/tensorflow/tensorflow-tutorial/

相关文章
相关标签/搜索