tensorflow中optimizer如何?神經網路的權重,位移等係數的更新和梯度計算

來源:互聯網
上載者:User

案例代碼:


#建立抽象模型
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10])  #實際分布的機率值


w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros(10))
a = tf.nn.softmax(tf.matmul(x, w) + b)  #基於softmax多分類得到的預測機率


#定義損失函數和訓練方法
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(a), reduction_indices=[1]))  #交叉熵
optimizer = tf.train.GradientDescentOptimizer(0.5)  #梯度下降最佳化演算法,學習步長為0.5
train = optimizer.minimize(cross_entropy)  #訓練目標: 最小化損失函數


init = tf.global_variables_initializer()


print('start to run session:')


with tf.Session() as sess:
    sess.run(init)
    for i in range(2000):
        batch_xs, batch_ys = mnist.train.next_batch(100)
        sess.run(train, feed_dict={x : batch_xs, y : batch_ys})


    #test trained model
    correct_prediction = tf.equal(tf.argmax(a, 1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    print (sess.run(accuracy, feed_dict={x : mnist.test.images, y : mnist.test.labels}))


第一步:

神經網路模型係數w,  b 聲明Variable變數,其中預設trainable=True, 那麼這些variable變數就會自動放入到TensorFlow系統的GraphKey.TRAINABLE_VARIABLES列表中:

 Defaults to the list of variables collected in the graph  under the key `GraphKey.TRAINABLE_VARIABLES`.

後面進行不斷的目標函數最佳化,梯度計算過程中,這些變數就會被新的梯度進行更新,達到權重係數更新的目標。


第二步:

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y * tf.log(a), reduction_indices=[1]))  #交叉熵
optimizer = tf.train.GradientDescentOptimizer(0.5)  #梯度下降最佳化演算法,學習步長為0.5
train = optimizer.minimize(cross_entropy)  #訓練目標: 最小化損失函數


這裡定義損失函數,最佳化演算法以及最終訓練模型這三個operation, 前後存在的任務依賴關係,在TensorFlow的graph中這些operation會形成儲存依賴關係,最終session執行train 這個operation時,會根據依賴關係,往前搜尋,找到最早的operation,開始一步步往下執行,最早的operation 即為w b 等聲明的這些op。

在optimizer.minimize函數中, 主要執行兩個函數:

compute_gradients 函數和 apply_gradients函數

compute_gradients 對var_list中的變數(沒有特別指定var_list,則預設更新GraphKey.TRAINABLE_VARIABLES中的變數),計算loss的梯度


apply_gradients 作用為將計算得到的梯度用於更新 var_list中的變數,如果沒有指定var_list, 則更新GraphKey.TRAINABLE_VARIABLES中的變數



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.