AdaGrad中的Ada是Adaptive之意,即“自适应的”,什么自适应呢,这里是指NN中的学习率,可以自适应的调整,并且是每一个参数有自己专门的调整,不是全体参数的学习率同时调整(共享一个学习率)。
NN的学习中,学习率对于学习效果非常重要。学习率太大,一次学太多,容易太发散,跳来跳去的,难收敛还慢;学习率太小,则学的慢,效率低。所以自适应减小学习率是很容易想到的解决方案,也叫 learining rate decay,学习率衰减。
Adagrad就是进一步发展了这个思想,为每一个参数赋予“定制”的值:
L是损失函数
W是权重矩阵
第一个式子后面那项是损失函数对所有权重参数的梯度的平方和,让学习率除以根号h,那么随着学习的进行,相当于减小学习率,很好理解。数学之美,美的有力量!
下面实验用的函数和函数图像在我的另外两篇讲参数最优化的博客里有,可以对比观看四种算法对于这一个函数的收敛效果
用Adagrad需要把初始学习率设置的比较大,然后随着学习进行,学习率会自行调整减小,从图中可以明显看出越接近最小值点,每一步越小,和SGD, 动量梯度法比较,Adagrad的效果都是非常好的
# AdaGrad.py
import numpy as np
import matplotlib.pyplot as plt
class AdaGrad:
def __init__(self, lr=0.01):
self.lr = lr
self.h = None
def update(self, params, grads):
if self.h is None: # 第一次调用
self.h = {}
for key, val in params.items(): # 初始化字典变量h
self.h[key] = np.zeros_like(val)
for key in params.keys():
self.h[key] += grads[int(key)] * grads[int(key)]
params[key] -= self.lr * grads[int(key)] / (np.sqrt(self.h[key] + 1e-7))
return params
def numerical_gradient(f, x):
h = 1e-4
x = np.array(list(init_x.values())) # 转换为ndarray
grad = np.zeros_like(x)
for idx in range(x.size):
temp = x[idx]
x[idx] = temp + h
fxh1 = f(x)
x[idx] = temp - h
fxh2 = f(x)
grad[idx] = (fxh1 - fxh2) / (2 * h)
x[idx] = temp
return grad
def func2(x):
return (x[0]**2) / 20 + x[1] ** 2
def adagrad_update(init_x, stepnum):
x = init_x
x_history = []
for i in range(stepnum):
x_history.append(np.array(list(x.copy().values())))
grad = numerical_gradient(func2, x)
x = m.update(x, grad)
return x, np.array(x_history)
init_x = {} # 起始点
init_x['0'] = -7.0
init_x['1'] = 2.0
learning_rate = 0.9
m = AdaGrad(lr=learning_rate)
stepnum = 45
x, x_history = adagrad_update(init_x=init_x, stepnum=stepnum)
axis_range = 10
x = np.arange(-axis_range, axis_range, 0.05)
y = np.arange(-axis_range, axis_range, 0.05)
X, Y = np.meshgrid(x, y)
z = np.array([X, Y])
# 画等高线
plt.figure()
plt.contour(x, y, func2(z),np.arange(0,10,2), zdir='z', cmap='binary')
# 画所有由梯度下降找到的点
plt.plot(x_history[:, 0], x_history[:, 1], '+', color='blue')
# 画点间连线
for i in range(x_history.shape[0]-2):
tmp = x_history[i:i+2]
tmp = tmp.T
plt.plot(tmp[0], tmp[1], color='blue')
# 标注最小值位置
plt.plot(0, 0, 'o', color='r')
plt.xlabel('x')
plt.ylabel('y')
plt.title('AdaGrad 0.05x^2 + y^2 ')
plt.show()