使用神經(jīng)網(wǎng)絡(luò)進(jìn)行樣本訓(xùn)練,要實(shí)現(xiàn)隨機(jī)梯度下降算法。這里我根據(jù)麥子學(xué)院彭亮老師的講解,總結(jié)如下,(神經(jīng)網(wǎng)絡(luò)的結(jié)構(gòu)在另一篇博客中已經(jīng)定義):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
if test_data: n_test = len (test_data) #有多少個測試集 n = len (training_data) for j in xrange (epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k + mini_batch_size] for k in xrange ( 0 ,n,mini_batch_size)] for mini_batch in mini_batches: self .update_mini_batch(mini_batch, eta) if test_data: print "Epoch {0}: {1}/{2}" . format (j, self .evaluate(test_data),n_test) else : print "Epoch {0} complete" . format (j) |
其中training_data是訓(xùn)練集,是由很多的tuples(元組)組成。每一個元組(x,y)代表一個實(shí)例,x是圖像的向量表示,y是圖像的類別。
epochs表示訓(xùn)練多少輪。
mini_batch_size表示每一次訓(xùn)練的實(shí)例個數(shù)。
eta表示學(xué)習(xí)率。
test_data表示測試集。
比較重要的函數(shù)是self.update_mini_batch,他是更新權(quán)重和偏置的關(guān)鍵函數(shù),接下來就定義這個函數(shù)。
1
2
3
4
5
6
7
8
9
10
|
def update_mini_batch( self , mini_batch,eta): nabla_b = [np.zeros(b.shape) for b in self .biases] nabla_w = [np.zeros(w.shape) for w in self .weights] for x,y in mini_batch: delta_nabla_b, delta_nable_w = self .backprop(x,y) #目標(biāo)函數(shù)對b和w的偏導(dǎo)數(shù) nabla_b = [nb + dnb for nb,dnb in zip (nabla_b,delta_nabla_b)] nabla_w = [nw + dnw for nw,dnw in zip (nabla_w,delta_nabla_w)] #累加b和w #最終更新權(quán)重為 self .weights = [w - (eta / len (mini_batch)) * nw for w, nw in zip ( self .weights, nabla_w)] self .baises = [b - (eta / len (mini_batch)) * nb for b, nb in zip ( self .baises, nabla_b)] |
這個update_mini_batch函數(shù)根據(jù)你傳入的一些數(shù)據(jù)進(jìn)行更新神經(jīng)網(wǎng)絡(luò)的權(quán)重和偏置。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://blog.csdn.net/leichaoaizhaojie/article/details/56840328