TensorFlow入門知識

----------歡迎加入學習交流QQ羣:657341423

安裝TensorFlow

Windows安裝TensorFlow可以下載TensorFlow安裝包,下載鏈接。安裝包下載後,在CMD窗口下使用pip安裝即可

TensorFlow安裝成功後,我們介紹TensorFlow的相關概念,它分爲三部分:計算模型、數據模型和運行模型。

計算模型-計算圖

Tensorflow是一個通過計算圖的形式來表述計算的編程系統,計算圖也叫數據流圖,可以把計算圖看做是一種有向圖,Tensorflow中的每一個計算都是計算圖上的一個節點,而節點之間的邊描述了計算之間的依賴關係。
在這裏插入圖片描述

在TensorFlow程序中,系統會維護一個默認的計算圖,通過tf.get_default_graph()函數可以獲取當前默認的計算圖:

import tensorflow as tf
a = tf.constant([1.0, 2.0], name='a')
b = tf.constant([2.0, 3.0], name='b')
print(a)
print(a.graph == tf.get_default_graph())
# 輸出
Tensor("a:0", shape=(2,), dtype=float32)
True

tf.constant代表定義一個計算節點,如果該節點沒有指定某個計算圖,則默認放在TensorFlow的默認計算圖,即tf.get_default_graph()函數所得的計算圖。
除了默認計算圖之外,TensorFlow支持創建新的計算圖,不同計算圖的資源不會共享,自定義計算圖如下:

import tensorflow as tf
g1 = tf.Graph()
with g1.as_default():
    # 在計算圖g1裏定義tf的變量
    v = tf.get_variable(
        'v',shape=[1],initializer=tf.zeros_initializer
    )
# 讀取計算圖g1的變量v
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')))

TensorFlow的變量和計算是兩個不同的概念,在此需要區分清楚。計算圖Graph通過tf.Graph.device()函數來制定運行計算圖的設備, 下圖定義的程序可以將加法計算跑在GPU上:

g = tf.Graph()
# 指定計算運行的設備
with g.device('/gpu:0'):
    result = a + b

此外,在一個計算圖中,可以集合來管理不同類別的資源,通過tf.add_to_collection()函數將資源加入一個collection中,然後通過tf.get_collection獲取一個集合裏面的所有資源。資源可以指變量、運算節點(張量)等TensorFlow所需的資源。常用的集合列表如下:
在這裏插入圖片描述

數據模型-張量

上面講述了 tf.constant代表定義一個計算節點,定義方式如下:

import tensorflow as tf
a = tf.constant([1.0, 2.0], name='a')
print(a)
# 輸出
Tensor("a:0", shape=(2,), dtype=float32)

準確地來說,計算節點就是一個張量,當輸出a的時候,其結構是張量的結構,輸出內容包含三個屬性:名字、維度和類型。

  • 名字是張量的標識符,如“a:0”,a爲計算圖裏面節點的名稱,0代表該節點輸出的一個結果,一個節點可能會有多個輸出結果。
  • 維度描述張量的數據屬性,如(2,),代表一個一維數組,數組長度爲2。如a = tf.constant([[1.0, 2.0],[1.0, 2.0],[1.0, 2.0]], name='a'),輸出Tensor("a:0", shape=(3, 2), dtype=float32),這是二維數組,長度爲3。
  • 類型是數據類型,如字符串、布爾型、整型等。如果在運算的時候,如果張量的數據類型不一致,會提示報錯。如:
 import tensorflow as tf
a = tf.constant([[1.0],[1.0],[1.0]], name='a')
b = tf.constant([[1],[1],[1]], name='b')
print(a+b)
# 輸出
TypeError: Input 'y' of 'Add' Op has type int32 that does not match type float32 of argument 'x'.

運行模型-會話

會話擁有並管理TensorFlow程序運行時的所有資源,張量只不過是定義計算方式,如果要讓計算方式運行,需要TensorFlow的會話來執行。使用如下:

import tensorflow as tf
a = tf.constant([[1.0,2],[1.0,2],[1.0,2]], name='a')
b = tf.constant([[1.0,2],[1.0,2],[1.0,2]], name='b')
sess = tf.Session()
result = sess.run(a+b)
print(result)
sess.close()
# 輸出
[[2. 4.]
 [2. 4.]
 [2. 4.]]

由於[1.0,2]的1.0和2是不同的數據類型,前者是浮點型,後者是整型,因此TensorFlow將計算結果皆以浮點型表示。除了這種方式,還可以使用python的with模塊實現,這樣不用調用sess.close()關閉會話。
我們知道張量和變量是存在於計算圖裏,不同的計算圖需要創建相應的會話執行,在創建會話的時候,若無指定的計算圖,則在默認的計算圖裏創建會話。如下所示:

import tensorflow as tf
# 定義g1計算圖
g1 = tf.Graph()
with g1.as_default():
    a = tf.constant([[1.0,2],[1.0,2],[1.0,2]], name='a')
    b = tf.constant([[1.0,2],[1.0,2],[1.0,2]], name='b')
# 在g1計算圖裏創建會話
with tf.Session(graph=g1) as sess:
    # 下面的兩者均可計算a+b
    print((a+b).eval())
    print(sess.run(a+b))
 # 輸出:
 # 第一次print
 [[2. 4.]
 [2. 4.]
 [2. 4.]]
 # 第二次print
[[2. 4.]
 [2. 4.]
 [2. 4.]]

在創建會話的時候,我們可以通過ConfigProto來設置會話,如下所示:

import tensorflow as tf
config = tf.ConfigProto(allow_soft_placement=True,
                        log_device_placement=True, )
c = tf.constant([[1.0, 2], [1.0, 2], [1.0, 2]], name='c')
d = tf.constant([[1.0, 2], [1.0, 2], [1.0, 2]], name='d')
with tf.Session(config=config) as sess:
    # 下面的兩者均可計算c+d
    print((c + d).eval())
    print(sess.run(c + d))

allow_soft_placement是將GPU的運算放到CPU上運算。 log_device_placement是設置日誌功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章