案例代碼:
#建立抽象模型
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中的變數