循环神经网络——裁剪梯度(应对梯度爆炸)

循环神经网络中比较容易出现梯度衰减或梯度爆炸,为了应对梯度爆炸,可以进行裁剪梯度。假设把所有模型参数梯度的元素拼接成一个向量g,并设裁剪的阈值是 θ \theta 。裁剪后的梯度 m i n ( θ g , 1 ) g min(\frac{\theta}{||g||},1)g L 2 L_2 范数不超过 θ \theta

通过代码进行演示:

def grad_clipping(params, theta)  #paras是模型参数,theta是阈值
    norm = 0
    for param in params:
        norm += (param ** 2).sum()
    norm = norm.sqrt()
    if norm > theta:
        for param in params:
            param *= theta/norm
发布了256 篇原创文章 · 获赞 10 · 访问量 8265

猜你喜欢

转载自blog.csdn.net/qq_37388085/article/details/104382837