在前面的章節(jié)中,我們一直在訓練過程中使用隨機梯度下降,但是沒有解釋它為什么有效。為了闡明它,我們剛剛在第 12.3 節(jié)中描述了梯度下降的基本原理。在本節(jié)中,我們將繼續(xù) 更詳細地討論隨機梯度下降。
%matplotlib inline
import math
import tensorflow as tf
from d2l import tensorflow as d2l
						 12.4.1。隨機梯度更新
在深度學習中,目標函數(shù)通常是訓練數(shù)據(jù)集中每個示例的損失函數(shù)的平均值。給定訓練數(shù)據(jù)集n例子,我們假設 fi(x)是關于 index 訓練樣例的損失函數(shù)i, 在哪里x是參數(shù)向量。然后我們到達目標函數(shù)
目標函數(shù)的梯度在x被計算為
如果使用梯度下降,每次自變量迭代的計算成本為O(n), 線性增長 n. 因此,當訓練數(shù)據(jù)集較大時,每次迭代的梯度下降代價會更高。
隨機梯度下降 (SGD) 減少了每次迭代的計算成本。在隨機梯度下降的每次迭代中,我們統(tǒng)一采樣一個索引i∈{1,…,n}隨機獲取數(shù)據(jù)示例,并計算梯度?fi(x)更新x:
在哪里η是學習率。我們可以看到每次迭代的計算成本從O(n) 梯度下降到常數(shù)O(1). 此外,我們要強調(diào)的是隨機梯度 ?fi(x)是完整梯度的無偏估計?f(x)因為
這意味著,平均而言,隨機梯度是對梯度的良好估計。
現(xiàn)在,我們將通過向梯度添加均值為 0 和方差為 1 的隨機噪聲來模擬隨機梯度下降,將其與梯度下降進行比較。
def f(x1, x2): # Objective function
  return x1 ** 2 + 2 * x2 ** 2
def f_grad(x1, x2): # Gradient of the objective function
  return 2 * x1, 4 * x2
def sgd(x1, x2, s1, s2, f_grad):
  g1, g2 = f_grad(x1, x2)
  # Simulate noisy gradient
  g1 += torch.normal(0.0, 1, (1,)).item()
  g2 += torch.normal(0.0, 1, (1,)).item()
  eta_t = eta * lr()
  return (x1 - eta_t * g1, x2 - eta_t * g2, 0, 0)
def constant_lr():
  return 1
eta = 0.1
lr = constant_lr # Constant learning rate
d2l.show_trace_2d(f, d2l.train_2d(sgd, steps=50, f_grad=f_grad))
							 
epoch 50, x1: 0.014749, x2: 0.009829
						
def f(x1, x2): # Objective function
  return x1 ** 2 + 2 * x2 ** 2
def f_grad(x1, x2): # Gradient of the objective function
  return 2 * x1, 4 * x2
def sgd(x1, x2, s1, s2, f_grad):
  g1, g2 = f_grad(x1, x2)
  # Simulate noisy gradient
  g1 += np.random.normal(0.0, 1, (1,))
  g2 += np.random
						
	                電子發(fā)燒友App
	            
	        
	        
          
        
        
	                    
                        
                        
                        
                        
                        


創(chuàng)作
發(fā)文章
發(fā)帖  
提問  
發(fā)資料
發(fā)視頻
上傳資料賺積分
           
            
            
                
            
評論