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/

相關文章
相關標籤/搜索