NN学习中的技巧之(一) 参数的最优化之AdaGrad

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()
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值