python實現(xiàn)隨機(jī)梯度下降(SGD)
使用神經(jīng)網(wǎng)絡(luò)進(jìn)行樣本訓(xùn)練,要實現(xiàn)隨機(jī)梯度下降算法。這里我根據(jù)麥子學(xué)院彭亮老師的講解,總結(jié)如下,(神經(jīng)網(wǎng)絡(luò)的結(jié)構(gòu)在另一篇博客中已經(jīng)定義):
def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None):
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)代表一個實例,x是圖像的向量表示,y是圖像的類別。
epochs表示訓(xùn)練多少輪。
mini_batch_size表示每一次訓(xùn)練的實例個數(shù)。
eta表示學(xué)習(xí)率。
test_data表示測試集。
比較重要的函數(shù)是self.update_mini_batch,他是更新權(quán)重和偏置的關(guān)鍵函數(shù),接下來就定義這個函數(shù)。
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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Python中利用sqrt()方法進(jìn)行平方根計算的教程
這篇文章主要介紹了Python中利用sqrt()方法進(jìn)行平方根計算的教程,是Python學(xué)習(xí)的基礎(chǔ)知識,需要的朋友可以參考下2015-05-05
Python 數(shù)據(jù)結(jié)構(gòu)之堆棧實例代碼
這篇文章主要介紹了Python 數(shù)據(jù)結(jié)構(gòu)之堆棧實例代碼的相關(guān)資料,需要的朋友可以參考下2017-01-01
Python利用tkinter和socket實現(xiàn)端口掃描
這篇文章主要為大家詳細(xì)介紹了Python如何利用tkinter和socket實現(xiàn)端口掃描功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以嘗試一下2022-12-12

