tensorflow(2)-優化函數

Tensorflow API

加減乘除

a = tf.matmul(x, w1)

損失函數及優化

這裏寫圖片描述

# 通過運行sess.run(train_ step)就可以對所有在GraphKeys.TRAINABLEes VARIABLES集合中的變量進行優化,使得在當前batch下的損失函數最小
cross_entropy = -tf.reduce_mean(y_ * tf.log(tf.clip_by_value(y, 1e-10, 1.0))) # 【交叉熵】
train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entropy)   # 一個batch裏面所有樣例的交叉熵平均值【train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)】
# softmax + 交叉熵===============================
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
cross_entropy_mean = tf.reduce_mean(cross_entropy)
# 迴歸:迴歸問題的神經網絡一般只有一個輸出節點,這個節點的輸出值就是預測值
mse = tf.reduce_mean(tf.square(y_-y))   【mse_loss = tf.reduce_sum(tf.pow(y_ - y, 2)) / sample_size】

這裏寫圖片描述

梯度下降

梯度下降算法:通過梯度下降得到的結果都會落到局部最優解,也可能落到全局解
隨機梯度下降算法(SGD):在每一輪迭代中,隨機優化某一條訓練數據上的損失函數。這樣每一輪參數更新的速度就大大加快了。某一條數據上損失函數更小並不代表在全部數據上損失函數更小,甚至使用隨機梯度下降法優化‘得到的神經網絡甚至可能無法達到局部最優。
梯度下降算法:通過梯度下降得到的結果都會落到局部最優解,也可能落到全局解

tf.train.GradientDescentOptimizer
tf.train.AdamOptimizer
tf.train.MomentumOptimizer

學習率設置-指數衰減

使用指數衰減的學習率,在迭代初期得到較高的下降速度,可以在較小的訓練輪數下取得不錯的收斂程度
計算:decayed_learning_rate = learning_rate * decay_rate^(global_step / decay_steps) 【 decay_rate:衰減係數,global_step:當前迭代輪數,decay_steps:衰減速度】

LEARNING_RATE = tf.train.exponential_decay(0.1, global_step, 1, 0.96, staircase=True)        # 0.1學習率+1衰減係數+0.96衰減速度【staircase=True時,global_step/decay_steps會被轉爲整數】
learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE, global_step, mnist.train.num_examples / BATCH_SIZE, LEARNING_RATE_DECAY, staircase=True)
train_op = tf.train.GradientDescentOptimizer(LEARNING_RATE).minimize(y, global_step=global_step)

正則化

解決過擬合問題
這裏寫圖片描述

loss=tf.reduce_mean(tf.square(y_ - y)) + tf .contrib.layers.12_regularizer(lambda)(w)
loss=tf.reduce_mean(tf.square(y_ - y)) + tf .contrib.layers.11_regularizer(lambda)(w)

多層時用提供的集合

tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(lambda1)(var))  # 每層的正則化
mse_loss = tf.reduce_sum(tf.pow(y_ - y, 2)) / sample_size    # 輸出的損失函數
# 合在一起-----------------------------
tf.add_to_collection('losses', mse_loss)
loss = tf.add_n(tf.get_collection('losses'))

滑動平均模型

這裏寫圖片描述

num_updates = tf.Variable(0, trainable=False)
ema = tf.train.ExponentialMovingAverage(0.99, num_updates)   # decay=0.99,step=num_updates
maintain_averages_op = ema.apply([v1])  # 列表裏面的都能更新

在訓練神經網絡模型時,每過一遍數據既需要通過反向傳播來更新神經網絡中的參數,又要更新每一個參數的滑動平均值。爲了一次完成多個操作,TensorFlow提供了tf.control_dependencies和tf.group兩種機制。下而兩行程序和train_op = tf.group(train_step,variables_averages_op)是等價的。
滑動平均類的保存

# 使用滑動平均。
v = tf.Variable(0, dtype=tf.float32, name="v")
for variables in tf.global_variables(): 
    print variables.name
'''
v:0
'''
ema = tf.train.ExponentialMovingAverage(0.99)
maintain_averages_op = ema.apply(tf.global_variables())
for variables in tf.global_variables(): 
    print variables.name
'''
v:0
v/ExponentialMovingAverage:0
'''
# 保存滑動平均模型
saver = tf.train.Saver()
with tf.Session() as sess:
    init_op = tf.global_variables_initializer()
    sess.run(init_op)
    sess.run(tf.assign(v, 10))
    sess.run(maintain_averages_op)
    # 保存的時候會將v:0  v/ExponentialMovingAverage:0這兩個變量都存下來。
    saver.save(sess, "Saved_model/model2.ckpt")
    print sess.run([v, ema.average(v)])  # [10.0, 0.099999905]
# 加載滑動平均模型
v = tf.Variable(0, dtype=tf.float32, name="v")
saver = tf.train.Saver({"v/ExponentialMovingAverage": v})  # 通過變量重命名將原來變量v的滑動平均值直接賦值給v。
# saver = tf.train.Saver(ema.variables_to_restore())
with tf.Session() as sess:
    saver.restore(sess, "Saved_model/model2.ckpt")
    print sess.run(v)          # 0.0999999

準確率

correct_prediction = tf.equal(tf.argmax(average_y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

激活函數

這裏寫圖片描述
tf.nn.relu, tf.sigmoid和tf.tanh

a = tf.nn.relu(tf.matmul(x,w1) + biases1)

維度變換

# 將標籤數據由稀疏格式轉換成稠密格式
# [ 2,       [[0,1,0,0,0]
#   4,        [0,0,0,1,0]
#   3,   -->  [0,0,1,0,0]
#   5,        [0,0,0,0,1]
#   1 ]       [1,0,0,0,0]]
labels = tf.reshape(labels, [batch_size, 1])
indices = tf.reshape(tf.range(0, batch_size, 1), [batch_size, 1])
labels = tf.sparse_to_dense(tf.concat(values=[indices, labels], axis=1),[batch_size, num_classes], 1.0, 0.0)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章