生活随笔
收集整理的這篇文章主要介紹了
SDG、SGD-M实现
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
https://shop.v2ss.bid/users/index.php?rp=/knowledgebase/10/V2Ray.html
目標(biāo)函數(shù):y=x2y=x^{2}y=x2
基于SGD和帶動(dòng)量的SGD的優(yōu)化算法對(duì)目標(biāo)函數(shù)進(jìn)行優(yōu)化。在單個(gè)變量進(jìn)行優(yōu)化時(shí),迭代次數(shù),及每一輪xxx的更新量,變化不大
動(dòng)量法dw
:當(dāng)前梯度,vdw
:上一輪更新量vdw
= beta
*vdw
+(1-beta
)*dww
= w
- lr
*vdwsgddw
:當(dāng)前梯度w
= w
- lr
*dw
from matplotlib
import pyplot
as plt
import numpy
as np
def func_y(x
):'''目標(biāo)優(yōu)化函數(shù)y = x**2'''return x
**2
def d(x
):'''目標(biāo)函數(shù)關(guān)于梯度的倒數(shù)'''return 2*x
def func_vdw(vdw
,dw
):'''動(dòng)量法中添加動(dòng)量項(xiàng)'''return 0.1*vdw
+0.9*dw
def momentum(x
,threshold
):'''動(dòng)量法dw:當(dāng)前梯度,vdw:上一輪更新量vdw = beta*vdw+(1-beta)*dww = w - lr*vdw'''vdw
= 0x_lis
= [x
] y_lis
= [func_y
(x
)] while func_y
(x
) > threshold
:dw
= d
(x
)vdw
= func_vdw
(vdw
, dw
)x
= x
- lr
* vdw y
= func_y
(x
)x_lis
.append
(x
)y_lis
.append
(y
)return x_lis
,y_lis
def sgd(x
,threshold
):'''sgddw:當(dāng)前梯度w = w - lr*dw'''vdw
= 0x_lis
= [x
]y_lis
= [func_y
(x
)]while func_y
(x
) > threshold
:dw
= d
(x
)vdw
= dwx
= x
- lr
* vdwy
= func_y
(x
)x_lis
.append
(x
)y_lis
.append
(y
)return x_lis
,y_lisx
= 5
lr
= 0.1
threshold
= 0.5x_lis
,y_lis
=momentum
(x
,threshold
)
x_lis_sgd
,y_lis_sgd
=sgd
(x
,threshold
)
plt
.scatter
(x_lis
,y_lis
,c
='k')
plt
.scatter
(x_lis_sgd
,y_lis_sgd
,c
='r',marker
='d')
plt
.title
('y=x**2,lr = {},momen_iteration:{},sgd_iteration:{}'.format(lr
,len(x_lis
),len(x_lis_sgd
)))
x
= np
.arange
(-x
,x
+2,0.01)
y
= x
**2print(x_lis_sgd
)
print(x_lis
)
plt
.plot
(x
,y
)
plt
.show
()
每輪更新量
總結(jié)
以上是生活随笔為你收集整理的SDG、SGD-M实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。