1. 程式人生 > >tensorflow-啟用函式及tf.nn.dropout

tensorflow-啟用函式及tf.nn.dropout

參考《Tensorflow技術解析與實戰》

啟用函式

  • 啟用函式(activation function)將神經元計算wTx+b的結果經過非線性表達對映到下一層。
  • 需要可微,啟用函式不會改變輸入資料維度。
  • sigmoid函式:σ(x)=11+ex(1)
    • 將輸出對映到(0,1)內,缺點:
      • 軟飽和性:取值無窮大時,一階導數趨於0,容易產生梯度消失。(硬飽和:某階段一階導數等於0)
  • tanh函式:tanh(x)=1e2x1+e2x(2)
    • 也具有軟飽和,收斂速度比sigmoid快
    • 會發生梯度消失
  • relu函式:f(x)=max(x,0)(3)
    softplus函式:f(x)=log(
    1+ex)
    (4)

    • relu在x<0時硬飽和,x>0梯度不衰減,為1,緩解梯度消失問題
    • 收斂快,提供神經網路稀疏表達能力
    • 缺點:
      • 部分輸入落入硬飽和區,權重無法更新,發生“神經元死亡”
  • 當輸入資料特徵相差明顯時,tanh效果好,在nlp上用處廣泛。
  • 當特徵不明顯時,sigmoid效果比較好。
  • 使用sigmoid和tanh時,輸入需要進行規範化,否則啟用後的值全部進入平坦區,隱層輸出趨於相同,喪失特徵表達。
  • relu有時可以不需要,目前大多數選擇relu

dropout函式

  • 以keep_prob的概率值決定是否被抑制,若抑制則神經元為0,若不被抑制,則神經元輸出值y y
    =1keep_prob
import tensorflow as tf
a = tf.constant([[1.,2.],[5.,-2.]])
relu_a = tf.nn.relu(a)
sigmoid_a = tf.nn.sigmoid(a)
tanh_a = tf.nn.tanh(a)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    result_relu_a = sess.run(relu_a)
    result_sigmoid_a = sess.run(sigmoid_a)
    result_tanh_a = sess.run(tanh_a)
    print('the result of relu(a) is : \n{}'
.format(result_relu_a)) print('the result of sigmoid(a) is : \n{}'.format(result_sigmoid_a)) print('the result of tanh(a) is : \n{}'.format(result_tanh_a))
the result of relu(a) is : 
[[ 1.  2.]
 [ 5.  0.]]
the result of sigmoid(a) is : 
[[ 0.7310586   0.88079703]
 [ 0.99330717  0.11920292]]
the result of tanh(a) is : 
[[ 0.76159418  0.96402758]
 [ 0.99990916 -0.96402758]]
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    d = tf.constant([[1.,2.,3.,4.],[5.,6.,7.,8.],[9.,10.,11.,12.],[13.,14.,15.,16.]])
    print(sess.run(tf.shape(d)))

    #由於[4,4] == [4,4] 行和列都為獨立
    dropout_a44 = tf.nn.dropout(d, 0.5, noise_shape = [4,4])
    result_dropout_a44 = sess.run(dropout_a44)
    print(result_dropout_a44)

    #noise_shpae[0]=4 == tf.shape(d)[0]=4  
    #noise_shpae[1]=4 != tf.shape(d)[1]=1
    #所以[0]即行獨立,[1]即列相關,每個行同為0或同不為0
    dropout_a41 = tf.nn.dropout(d, 0.5, noise_shape = [4,1])
    result_dropout_a41 = sess.run(dropout_a41)
    print(result_dropout_a41)

    #noise_shpae[0]=1 != tf.shape(d)[0]=4  
    #noise_shpae[1]=4 == tf.shape(d)[1]=4
    #所以[1]即列獨立,[0]即行相關,每個列同為0或同不為0
    dropout_a24 = tf.nn.dropout(d, 0.5, noise_shape = [1,4])
    result_dropout_a24 = sess.run(dropout_a24)
    print(result_dropout_a24)
    #不相等的noise_shape只能為1
[4 4]
[[  0.   4.   0.   8.]
 [  0.   0.  14.   0.]
 [  0.   0.  22.   0.]
 [  0.   0.  30.   0.]]
[[  2.   4.   6.   8.]
 [  0.   0.   0.   0.]
 [ 18.  20.  22.  24.]
 [ 26.  28.  30.  32.]]
[[  0.   0.   6.   0.]
 [  0.   0.  14.   0.]
 [  0.   0.  22.   0.]
 [  0.   0.  30.   0.]]
d.shape
TensorShape([Dimension(4), Dimension(4)])