tf 重要用法及概念
tf模型procedure
- 選擇graph(非必須)
>>> graph = tf.Graph()
>>> with graph.as_default():
- 構建graph:batch/label, tf.placeholder()
- 構建graph:NN structures,weight/bias/logits/activations
- 構建graph:loss function
- 構建graph:optimizer
- 構建graph:變數初始化,通常tf.global_variables_initializer()
- session初始化,常用with語句
- run變數,sess.run(init)或init.run()
- batch generating,用loop
- sess.run(loss&optimizer),需要feed_dict喂入9中資料
- assessment,關鍵指標eval()和展示
tf.gfile.GFile()
類似於普通python之open()的命令,將返回一個檔案操作控制代碼。
def read_words(filename):
with tf.gfile.GFile(filename, 'r') as f:
return f.read().replace('\n', '<eos>').split()
tf.convert_to_tensor(data)
將給定的list或array轉換為tf的tensor物件。
>>> data = tf.convert_to_tensor([1,2,3])
<tf.Tensor 'Const:0' shape=(3,) dtype=int32>
tf.size(data)
返回data中全部元素的數量的tensor,注意返回的數量是全部元素,而不是len(data)
>>> tf.size( tf.convert_to_tensor([[1,2,3],[2,3,4]]))
<tf.Tensor 'Size_4:0' shape=() dtype=int32>
>>> sess=tf.Session()
>>> sess.run(tf.size(tf.convert_to_tensor([[1,2,3],[2,3,4]])))
6
tf.reshape(data, shape)
tf下面類似於np.reshape的函式,推斷維度時用-1
>>> sess=tf.Session()
>>> sess.run(tf.reshape([1,2,3,4],[-1,2]))
array([[1, 2],
[3, 4]])
tf.one_hot(indices, length)
根據indices生成one_hot形式的tensor,length為每個one-hot vector的長度,即最後一個axis的長度
>>> sess=tf.Session()
>>> a=tf.one_hot([1,2,4],5)
>>> sess.run(a)
array([[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 0., 1.]], dtype=float32)
>>> b=tf.one_hot([[1,2,5],[3,4,6]],7)
>>> sess.run(b)
array([[[0., 1., 0., 0., 0., 0., 0.],
[0., 0., 1., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 1., 0.]],
[[0., 0., 0., 1., 0., 0., 0.],
[0., 0., 0., 0., 1., 0., 0.],
[0., 0., 0., 0., 0., 0., 1.]]], dtype=float32)
tf.placeholder(dtype,shape)
類似於不需要進行初始化的tf變數,因為有的時候我們在宣告變數的時候無法明確其初始值。其也稱為佔位符。我們只需要明確其型別和形狀即可。形狀表示中可用None進行推斷,推斷時需要注意非None維度的匹配,否則會報錯,None推斷通常是對應於訓練batch中的batch長度。由於佔位符沒有初始值,因此在run的時候,我們需要給其“喂值”,即使用feed_dict.
>>> b = tf.placeholder(tf.float32, [None, 1])
>>> a = np.random.randint(0,5,(6,1))
>>> a
array([[1],
[2],
[3],
[4],
[3],
[0]])
>>> sess = tf.Session()
>>> sess.run(b, feed_dict={b: a})
array([[1.],
[2.],
[3.],
[4.],
[3.],
[0.]], dtype=float32)
tf.constant(value,dtype,shape)
生成一個給定值的張量常量。
>>> tf.constant([[1, 2, 3], [4, 5, 6]],tf.int32,[2,3])
<tf.Tensor 'Const:0' shape=(2, 3) dtype=int32>
>>> c=tf.constant([[1, 2, 3], [4, 5, 6]],tf.int32,[2,3])
>>> tf.Session().run(c)
array([[1, 2, 3],
[4, 5, 6]])
tf.Variable(value,name=None)
tf張量變數,注意由於需要明確初始化數值,因此不需要設定形狀引數,名字可有可無。
>>> a
array([0, 0, 4, 1, 4, 1])
>>> tf.Variable(a)
<tf.Variable 'Variable:0' shape=(6,) dtype=int32_ref>
tf math operations
>>> d = tf.add(b, c, name='d')
>>> a = tf.multiply(d, e, name='a')
>>> c = tf.log(5.0)
tf.reduce_mean(data,axis=0)
等同於np.mean,即tf的求均值函式。這裡的reduce源於functional programming概念中的reduce paradigm,可忽略。
tf.reduce_sum(data,axis=0)
等同於np.sum,即tf的求和函式。這裡的reduce源於functional programming概念中的reduce paradigm,可忽略。
tf.global_variables_initializer()
初始化全部模型引數
>>> init_op = tf.global_variables_initializer()
>>> sess = tf.Session()
>>> sess.run(init_op)
也可以寫為init_op.run()
tf.Session().run(list,feed_dict)
tf張量和模型必須要在Session中run後才會真的進行計算和生成值,因此素有tf深度學習模型中必須有Session()和run()步驟。
tf的session在run的過程中,我們不需要去明確的run每一個操作,因為tf會根據圖的結構自己尋找每步操所所依賴的前提變數或操作,然後自動run這些前提變數或操作。注意,如存在佔位符變數,我們需要在run時喂入資料。
>>> sess = tf.Session()
>>> out = sess.run(a, feed_dict={b: np.arange(0, 10)[:, np.newaxis]})
另外,run將計算list中的全部目標值,返回相應數量的計算結果。
a, c = sess.run([optimiser, cross_entropy],
feed_dict={x: batch_x, y: batch_y})
tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32)
取正態分佈數值
>>> a = tf.random_normal([2,3])
>>> sess = tf.Session()
>>> sess.run(a)
array([[-0.25265786, -1.6633197 , 0.71720666],
[-0.12861042, 0.9900551 , -0.04970803]], dtype=float32)
tf.nn.relu(value)
rectified linear unit activation function,將大於0的數保持不變,小於0的數置為0
>>> sess = tf.Session()
>>> sess.run(tf.nn.relu([-5,1,3]))
array([0, 1, 3])
tf.nn.softmax(logits)
對logits內全部要素進行exp函式加權,注意logits必須為float,可以將其理解為每層layer的net input,即輸入與權重相乘並加如bias後的值。
>>> import numpy as np
>>> aa = tf.nn.softmax([1.0,2.0,3.0])
>>> sess = tf.Session()
>>> sess.run(aa)
array([0.09003057, 0.24472848, 0.66524094], dtype=float32)
>>> a1,a2,a3 = np.exp(1),np.exp(2),np.exp(3)
>>> a4 = a1+a2+a3
>>> a1/a4
0.09003057317038046
>>> a2/a4
0.24472847105479767
>>> a3/a4
0.6652409557748219
tf.clip_by_value(data,min,max)
把data中的每一個元素的值都壓縮在min和max之間。小於min的讓它等於min,大於max的元素的值等於max
>>> sess=tf.Session()
>>> sess.run(tf.clip_by_value([1,3,5,7,9],3,7))
array([3, 3, 5, 7, 7])
tf.nn.softmax_cross_entropy_with_logits(labels,logits)
softmax在深度學習分類問題中通常作為輸出層的activation function,以此將輸出層的net input,即logits轉換為概率輸出。tf的softmax_cross_entropy函式的功能就是在輸出層整合softmax啟用函式以及cross_entropy熵或純度評估函式,從而直接輸出層的logits進行準確度評估。基本的思路就是先對logits進行softmax處理,從而生成各分類的概率評估:
而後根據各分類的概率評估以及各分類的實際值,進行cross entropy計算:
程式碼如下:
>>> labels = [1.0,1.0,0,0]
>>> logits = [1.0,2.0,5.0,3.0]
>>> sess = tf.Session()
>>> sess.run(tf.nn.softmax_cross_entropy_with_logits(labels=labels,logits=logits))
7.370365
>>> softmax_list=[np.exp(logits[i]) for i in range(len(logits))]
>>> softmax_list
[2.718281828459045, 7.38905609893065, 148.4131591025766, 20.085536923187668]
>>> softmax_sum=sum(softmax_list)
>>> softmax_sum
178.60603395315397
>>> softmax=[i/softmax_sum for i in softmax_list]
>>> softmax
[0.015219428864155927, 0.04137069692096015, 0.8309526605439513, 0.11245721367093255]
>>> cross_entropy_list=[-labels[i]*np.log(softmax[i]) for i in range(len(logits))]
>>> sum(cross_entropy_list)
7.370364905207625
可見我們逐項利用logtis計算softmax,而後在用此softmax與真實labels進行cross entropy計算後的得到的值是與直接使用tf中的softmax_cross_entropy_with_logits函式計算出來的值是完全一致的。
tf.train.GradientDescentOptimizer(learning_rate)
gradient descent最優化問題,需輸入learning rate。
.minimize(loss) 根據optimizer物件最小化loss值。
>>> optimiser = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cross_entropy)
tf.argmax(data,axis=0)
返回data中的最大值的索引號,如果是向量,那就返回一個值,如果是矩陣,那就返回一個向量,這個向量的每一個維度都是相對應矩陣行的最大值元素的索引號。axis為取值維度引數。
>>> A = [[1,3,4,5,6]]
>>> B = [[1,3,4], [2,4,1]]
>>> sess.run(tf.argmax(A,0))
array([0, 0, 0, 0, 0], dtype=int64)
&