sparse_softmax_cross_entropy_with_logits()
sparse_softmax_cross_entropy_with_logits(_sentinel=None,
labels=None,
logits=None,
name=None)
- logits
- 神經網絡最後一層的輸出
- 大小爲[ [ batch_size, num_classes]
- labels
- 表示實際標籤值
- 大小爲[ [ batch_size,num_classes]
- 第一步是先對網絡最後一層的輸出做一個 softmax ,輸出爲屬於某一屬性的概率向量;再將概率向量與實際標籤向量做交叉熵,返回向量
用於求含有正則化的損失值
- 對網絡最後一層的輸出 y 做 softmax,求取輸出屬於某一類的概率,結果爲一個num_classes 大小的向量,再將此向量和實際標籤值做交叉熵,返回一個向量值。
ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
- 通過 tf.reduce_mean()函數對得到的向量求均值,得到 loss
cem = tf.reduce_mean(ce)
loss = cem + tf.add_n(tf.get_collection('losses'))
tf.reduce_mean()
tf.reduce_mean( input_tensor,
reduction_indices=None,
keep_dims=False,
name=None)
- 此函數表示對得到的向量求取均值。參數 r input_tensor 表示 要減少的張量 ;
- reduction_indices
- keep_dims
- 含義爲: 如果爲 true ,則保留長度爲 1 1 的縮小尺寸。e name 表示 操作的名稱。
- 例如:
x = tf.constant([[1., 1.], [2., 2.]])
tf.reduce_mean(x) #表示對向量整體求均值 1.5
tf.reduce_mean(x, 0) #表示對向量在列上求均值[1.5, 1.5]
tf.reduce_mean(x, 1) #表示對向量在行上求均值[1., 2.]
tf.train.exponential_decay()
learning_rate = tf.train.exponential_decay(
LEARNING_RATE_BASE,
global_step,
mnist.train.num_examples / BATCH_SIZE,
LEARNING_RATE_DECAY,
staircase=True)
- 實現指數衰減學習率
- LEARNING_RATE_BASE
- LEARNING_RATE_DECAY
- 表示學習率衰減速率。實現指數級的減小學習率,可以讓模型在訓練的前期快速接近較優解,又可以保證模型在訓練後期不會有太大波動
- staircase
- staircase=True 時,爲階梯形衰減,(global_step/decay_steps)則被轉化爲整數
- staircase=False 時,爲曲線形衰減,
- 以此根據 staircase 來選擇不同的衰減方式。
- 計算公式爲:
decayed_learning_rate=learining_rate*decay_rate^(global_step/decay_steps)
tf.train.GradientDescentOptimizer()
train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)
- learning_rate
- 構造一個實現梯度下降算法的優化器,再通過使用 minimize 更新存儲要訓練的變量的列表來減小 loss。
tf.train.ExponentialMovingAverage()
ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
ema_op = ema.apply(tf.trainable_variables())
- 實現滑動平均模型
- MOVING_AVERAGE_DECAY
- 此函數維護一個影子變量,影子變量初始值爲變量初始值。影子變量值的更新方式如下:
shadow_variable = decay * shadow_variable + (1-decay) * variable。
- shadow_variable 是影子變量
- variable 表示待更新的變量
- decay 爲衰減速率。decay 一般設爲接近於 1 的數(0.99,0.999),decay 越大模型越穩定。
tf.control_dependencies()
with tf.control_dependencies([train_step, ema_op]):
train_op = tf.no_op(name='train')
- 將train_step和ema_op 兩個訓練操作都綁定到train_op上
np.reshape()
reshaped_xs = np.reshape(xs,(BATCH_SIZE,
mnist_lenet5_forward.IMAGE_SIZE,
mnist_lenet5_forward.IMAGE_SIZE,
mnist_lenet5_forward.NUM_CHANNELS))
- 讀取一個 batch 數據,將輸入數據 xs 轉成與網絡輸入相同形狀的矩陣。
tf.equal()
tf.equal(x, y)
- 此函數用於判斷函數的兩個參數 x 與 與y 是否相等
- 一般x 表示預測值,y 表示實際值