加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python实现随机梯度下降(SGD)

发布时间:2020-12-17 07:43:59 所属栏目:Python 来源:网络整理
导读:使用神经网络进行样本训练,要实现随机梯度下降算法。这里我根据麦子学院彭亮老师的讲解,总结如下,(神经网络的结构在另一篇博客中已经定义): def SGD(self,training_data,epochs,mini_batch_size,eta,test_data=None): if test_data: n_test = len(test

使用神经网络进行样本训练,要实现随机梯度下降算法。这里我根据麦子学院彭亮老师的讲解,总结如下,(神经网络的结构在另一篇博客中已经定义):

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是训练集,是由很多的tuples(元组)组成。每一个元组(x,y)代表一个实例,x是图像的向量表示,y是图像的类别。
epochs表示训练多少轮。
mini_batch_size表示每一次训练的实例个数。
eta表示学习率。
test_data表示测试集。
比较重要的函数是self.update_mini_batch,他是更新权重和偏置的关键函数,接下来就定义这个函数。

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)#目标函数对b和w的偏导数
    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
  #最终更新权重为
  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函数根据你传入的一些数据进行更新神经网络的权重和偏置。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读