https://shop.v2ss.bid/users/index.php?rp=/knowledgebase/10/V2Ray.html
目标函数:
y
=
x
2
y=x^{2}
y=x2
基于SGD和带动量的SGD的优化算法对目标函数进行优化。在单个变量进行优化时,迭代次数,及每一轮
x
x
x的更新量,变化不大
动量法
dw:当前梯度,vdw:上一轮更新量
vdw = beta*vdw+(1-beta)*dw
w = w - lr*vdw
sgd
dw:当前梯度
w = w - lr*dw
from matplotlib import pyplot as plt
import numpy as np
def func_y(x):
'''
目标优化函数
y = x**2
'''
return x**2
def d(x):
'''
目标函数关于梯度的倒数
'''
return 2*x
def func_vdw(vdw,dw):
'''
动量法中添加动量项
'''
return 0.1*vdw+0.9*dw
def momentum(x,threshold):
'''
动量法
dw:当前梯度,vdw:上一轮更新量
vdw = beta*vdw+(1-beta)*dw
w = w - lr*vdw
'''
vdw = 0
x_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):
'''
sgd
dw:当前梯度
w = w - lr*dw
'''
vdw = 0
x_lis = [x]# 记录自变量更新情况
y_lis = [func_y(x)]# 记录因变量更新情况
while func_y(x) > threshold:
dw = d(x)
vdw = dw# 只有当前的梯度
x = x - lr * vdw# 更新变量
y = func_y(x)
x_lis.append(x)
y_lis.append(y)
return x_lis,y_lis
x = 5# 初始值
lr = 0.1# 学习率
threshold = 0.5# 目标的误差限
x_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('iteration:'+str(len(x_lis)))
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**2
print(x_lis_sgd)
print(x_lis)
plt.plot(x,y)
plt.show()
每轮更新量