Layer Normalization(层规范化)

news2024/9/23 16:13:43

详细内容在这篇论文:Layer Normalization
训练深度神经网络需要大量的计算,减少计算时间的一个有效方法是规范化神经元的活动,例如批量规范化BN(batch normalization)技术,然而,批量规范化对小批量大小(batch size)敏感并且无法直接应用到RNN中(recurrent neural networks),为了解决上述问题,层规范化LN(Layer Normalization)被提出,不仅能直接应用到RNN,还能显著减少训练时间。与批量归一化不同,层规范化直接根据隐藏层内神经元的总输入估计归一化统计数据,因此不会在训练案例之间引入任何新的依赖关系。

背景

A feed-forward neural network is a non-linear mapping from a input pattern x \mathbf{x} x to an output vector y y y. Consider the l th  l^{\text {th }} lth  hidden layer in a deep feed-forward, neural network, and let a l a^l al be the vector representation of the summed inputs to the neurons in that layer. a i l a_i^l ail是第 l l l层第 i i i个神经元的线性加权输出。 The summed inputs are computed through a linear projection with the weight matrix W l W^l Wl and the bottom-up inputs h l h^l hl given as follows:
a i l = w i l ⊤ h l h i l + 1 = f ( a i l + b i l ) a_i^l=w_i^{l^{\top}} h^l \quad h_i^{l+1}=f\left(a_i^l+b_i^l\right) ail=wilhlhil+1=f(ail+bil)

where f ( ⋅ ) f(\cdot) f() is an element-wise non-linear function(激活函数) and w i l w_i^l wil is the incoming weights to the i t h i^{t h} ith hidden units and b i l b_i^l bil is the scalar bias parameter. The parameters in the neural network are learnt using gradient-based optimization algorithms with the gradients being computed by back-propagation.

Batch Normalization

BN是为了减少协变量偏移提出的,它在训练阶段对隐神经元加权输出进行规范化,例如,对于 l t h l^{th} lth层的 i t h i^{th} ith个加权输出 a i l a_i^l ail,BN根据输入数据的分布进行了缩放
a ˉ i l = g i l σ i l ( a i l − μ i l ) μ i l = E x ∼ P ( x ) [ a i l ] σ i l = E x ∼ P ( x ) [ ( a i l − μ i l ) 2 ] \bar{a}_i^l=\frac{g_i^l}{\sigma_i^l}\left(a_i^l-\mu_i^l\right) \quad \mu_i^l=\underset{\mathbf{x} \sim P(\mathbf{x})}{\mathbb{E}}\left[a_i^l\right] \quad \sigma_i^l=\sqrt{\underset{\mathbf{x} \sim P(\mathbf{x})}{\mathbb{E}}\left[\left(a_i^l-\mu_i^l\right)^2\right]} aˉil=σilgil(ailμil)μil=xP(x)E[ail]σil=xP(x)E[(ailμil)2]

where a ˉ i l \bar{a}_i^l aˉil is normalized summed inputs to the i t h i^{t h} ith hidden unit in the l t h l^{t h} lth layer and g i g_i gi is a gain parameter scaling the normalized activation before the non-linear activation function.

实际中不会计算真正的 μ \mu μ σ \sigma σ,转而去估计一个batch里的 μ \mu μ σ \sigma σ,所以BN要求这个batchsize不能太小。然而,在一些在线学习任务以及超大分布模型中往往需要很小的batchsize。

Layer Normalization

μ l = 1 H ∑ i = 1 H a i l σ l = 1 H ∑ i = 1 H ( a i l − μ l ) 2 \mu^l=\frac{1}{H} \sum_{i=1}^H a_i^l \quad \sigma^l=\sqrt{\frac{1}{H} \sum_{i=1}^H\left(a_i^l-\mu^l\right)^2} μl=H1i=1Hailσl=H1i=1H(ailμl)2

H H H是一个隐藏层中的隐藏单元数量。在LN中,同一个层共享 μ \mu μ σ \sigma σ, but different training cases have different normalization terms. Unlike batch normalization, layer normalization does not impose any constraint on the size of a mini-batch and it can be used in the pure online regime with batch size 1.

In a standard RNN, the summed inputs in the recurrent layer are computed from the current input x t \mathbf{x}^t xt and previous vector of hidden states h t − 1 \mathbf{h}^{t-1} ht1 which are computed as a t = W h h h t − 1 + W x h x t \mathbf{a}^t=W_{h h} h^{t-1}+W_{x h} \mathbf{x}^t at=Whhht1+Wxhxt. The layer normalized recurrent layer re-centers and re-scales its activations using the extra normalization terms :
h t = f [ g σ t ⊙ ( a t − μ t ) + b ] μ t = 1 H ∑ i = 1 H a i t σ t = 1 H ∑ i = 1 H ( a i t − μ t ) 2 \mathbf{h}^t=f\left[\frac{\mathbf{g}}{\sigma^t} \odot\left(\mathbf{a}^t-\mu^t\right)+\mathbf{b}\right] \quad \mu^t=\frac{1}{H} \sum_{i=1}^H a_i^t \quad \sigma^t=\sqrt{\frac{1}{H} \sum_{i=1}^H\left(a_i^t-\mu^t\right)^2} ht=f[σtg(atμt)+b]μt=H1i=1Haitσt=H1i=1H(aitμt)2

where W h h W_{h h} Whh is the recurrent hidden to hidden weights and W x h W_{x h} Wxh are the bottom up input to hidden weights. ⊙ \odot is the element-wise multiplication between two vectors. b \mathbf{b} b and g \mathbf{g} g are defined as the bias and gain parameters of the same dimension as h t \mathbf{h}^t ht.

在标准RNN中存在梯度爆炸和消失问题,用了LN之后会更加稳定。
贴两个图便于理解:
在这里插入图片描述
在这里插入图片描述

视频讲解可以参考:What is Layer Normalization? | Deep Learning Fundamentals

代码实现

这边贴一个Restormer中的LN层的实现
首先定义两个函数用于reshape。4d到3d不需要参数,因为只需要把已有的两个维度合并;3d到4d需要参数,因为需要把一个维度分成两个维度

def to_3d(x):
    return rearrange(x, 'b c h w -> b (h w) c')

def to_4d(x,h,w):
    return rearrange(x, 'b (h w) c -> b c h w',h=h,w=w)

定义一个没有bias的LN层,weight是可学习的参数,所以用 n n . P a r a m e t e r nn.Parameter nn.Parameter包装

# 没有bias的LayerNorm层
class BiasFree_LayerNorm(nn.Module):
    def __init__(self, normalized_shape):
        super(BiasFree_LayerNorm, self).__init__()
        if isinstance(normalized_shape, numbers.Integral):
            normalized_shape = (normalized_shape,)
        normalized_shape = torch.Size(normalized_shape)

        assert len(normalized_shape) == 1

        self.weight = nn.Parameter(torch.ones(normalized_shape))
        self.normalized_shape = normalized_shape

    def forward(self, x):
    	#x的维度(batch_size, height x width, channels)
    	#sigma的维度(batch_size, height x width, 1)
        sigma = x.var(-1, keepdim=True, unbiased=False)
        return x / torch.sqrt(sigma+1e-5) * self.weight

定义一个有bias的LN层,同样的,weight和bias都是可学习的参数

class WithBias_LayerNorm(nn.Module):
    def __init__(self, normalized_shape):
        super(WithBias_LayerNorm, self).__init__()
        #如果输入的normalized_shape是个整数,则化为元组
        if isinstance(normalized_shape, numbers.Integral):
            normalized_shape = (normalized_shape,)
        normalized_shape = torch.Size(normalized_shape)

        assert len(normalized_shape) == 1

        self.weight = nn.Parameter(torch.ones(normalized_shape))
        #比上面多定义一个bias
        self.bias = nn.Parameter(torch.zeros(normalized_shape))
        self.normalized_shape = normalized_shape

    def forward(self, x):
        mu = x.mean(-1, keepdim=True)
        sigma = x.var(-1, keepdim=True, unbiased=False)
        return (x - mu) / torch.sqrt(sigma+1e-5) * self.weight + self.bias#这边加了bias

把上面的函数包装起来,定义一个统一的层规范化函数

class LayerNorm(nn.Module):
    def __init__(self, dim, LayerNorm_type):
        super(LayerNorm, self).__init__()
        if LayerNorm_type =='BiasFree':
            self.body = BiasFree_LayerNorm(dim)
        else:
            self.body = WithBias_LayerNorm(dim)

    def forward(self, x):
        h, w = x.shape[-2:]
        return to_4d(self.body(to_3d(x)), h, w)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/922356.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【若依管理系统 权限控制】

1.在菜单管理添加按钮权限,如图 2.在角色管理里面加上菜单,如图 3.前端控制: 4.后端控制: 5.重启后台后,重新登录用户。

无涯教程-Python - Dictionary(字典)

每个键都由一个冒号(:)与其值分隔,各元素之间以逗号分隔,并且整个内容都用花括号括起来。一个没有任何元素的空字典用两个大括号书写,如:{}。 键在字典中是唯一的,而值可能不是。字典的值可以是任何类型,但是键必须是…

【机器学习7】特征缩放

特征缩放 🍀特征缩放的重要性🌱归一化🌱标准化🌱更高级的缩放方法🌸导入数据集&将数据集划分为训练集和测试集🌸Sklearn-Learn算法实现归一化🌸Sklearn-Learn算法实现标准化 🍀特…

Activity 的启动流程(Android 13)

Activity 的启动过程分为两种:一种是普通 Activity 的启动过程,另一种是根 Activity 的启动过程。普通 Activity 指的是除应用程序启动的第一个 Activity 之外的其他 Activity。根 Activity 指的是应用程序启动的第一个 Activity,因此&#x…

春秋云镜 :CVE-2020-21650(MyuCMS后台rce)

一、题目 靶标介绍: MyuCMS开源内容管理系统,采用ThinkPHP开发而成的社区商城聚合,插件,模板,轻便快捷容易扩展 其2.2版本中admin.php/config/add方法存在任意命令执行漏洞. 进入题目: exp: url/index.p…

计算机网络 QA

DNS 的解析过程 浏览器缓存。当用户通过浏览器访问某域名时,浏览器首先会在自己的缓存中查找是否有该域名对应的 IP 地址(曾经访问过该域名并且没有清空缓存)系统缓存。当浏览器缓存中无域名对应的 IP 地址时,会自动检测用户计算机…

opencv 进阶20-随机森林示例

OpenCV中的随机森林是一种强大的机器学习算法,旨在解决分类和回归问题。随机森林使用多个决策树来进行预测,每个决策树都是由随机选择的样本和特征组成的。在分类问题中,随机森林通过投票来确定最终的类别;在回归问题中&#xff0…

Blazor组件化开发心得:Blazor开发套路

文章目录 前言Blazor开发套路文件分类示意图 如何分工 前言 接触Blazor也快有一个多月了,了解Blazor之后发现确实是个好东西,开发速度太快了,前端直接拿数据,通过SSR保证安全。但是有一个问题,服务器能承受多大的压力…

Spark项目Java和Scala混合打包编译

文章目录 项目结构Pom完整文件编译查看 实际开发用有时候引用自己写的一些java工具类,但是整个项目是scala开发的spark程序,在项目打包时需要考虑到java和scala混合在一起编译。 今天看到之前很久之前写的一些打包编译文章,发现很多地方不太对…

【资料分享】基于NXP i.MX 8M Plus的异构多核核心板规格书

1 核心板简介 创龙科技SOM-TLIMX8MP是一款基于NXP i.MX 8M Plus的四核ARM Cortex-A53 单核ARM Cortex-M7异构多核处理器设计的高端工业核心板,ARM Cortex-A53(64-bit)主处理单元主频高达1.6GHz,ARM Cortex-M7实时处理单元主频高达800MHz。处理器采用14…

【Java】代理实现重试功能

在有些调用http请求功能中,会因为网络的抖动,使得网络不稳定。这时需要一个功能来实现重试。 下面介绍使用JDK的代理功能和Cglib来实现简单的代理重试。 JDK的代理需要被代理的类实现接口,下面的newProxyInstance代码中需要interfaces参数&am…

element-table的动态操作,自动以表格,动态新增行、列,删除行列

灵活的自定义表格行列以及增删改查的操作,右键选中列则是列的删除&#xff0c;效果如下 <template><div class"st-table"><div style"width: 100%"><el-button click"addRow()" type"primary" icon"CircleP…

深入理解android线程池实现原理

为什么要引入线程池 降低资源消耗。通过重复利用已创建的线程降低线程创建和销毁造成的消耗提高响应速度。当任务到达时&#xff0c;任务可以不需要等到线程创建就能立即执行提高线程的可管理性。线程是稀缺资源&#xff0c;如果无限制的创建&#xff0c;不仅会消耗系统的资源…

大学资产管理,这个细节真的很绝!

无论是个人还是企业&#xff0c;资产都是其成功的基石。通过资产管理系统&#xff0c;个人可以更好地管理他们的投资组合&#xff0c;实现财务目标。 对于企业而言&#xff0c;资产管理系统有助于提高资源利用效率&#xff0c;减少损失和浪费&#xff0c;优化生产和运营流程。 …

深度学习处理文本(NLP)

文章目录 引言1. 反向传播1.1 实例流程实现1.2 前向传播1.3 计算损失1.4 反向传播误差1.5 更新权重1.6 迭代1.7 BackPropagation & Adam 代码实例 2. 优化器 -- Adam2.1 Adam解析2.2 代码实例 3. NLP任务4. 神经网络处理文本4.1 step1 字符数值化4.2 step 2 矩阵转化为向量…

javaWeb差缺补漏(一)【针对于自身知识点掌握情况】

前端三大件部分 1、a标签的target属性iframe标签的name属性 2、textarea标签&#xff1a;表示多行文本输入。起始标签和结束标签中的内容是默认值。 rows&#xff1a;属性设置可以显示多少行。 cols&#xff1a;属性设置每行显示多少列。 3、form表单的action提交的时候&a…

LC-1267. 统计参与通信的服务器(枚举 + 计数)

1267. 统计参与通信的服务器 中等 这里有一幅服务器分布图&#xff0c;服务器的位置标识在 m * n 的整数矩阵网格 grid 中&#xff0c;1 表示单元格上有服务器&#xff0c;0 表示没有。 如果两台服务器位于同一行或者同一列&#xff0c;我们就认为它们之间可以进行通信。 请…

服务器数据恢复-ESXi虚拟化误删除的数据恢复案例

服务器数据恢复环境&#xff1a; 一台服务器安装的ESXi虚拟化系统&#xff0c;该虚拟化系统连接了多个LUN&#xff0c;其中一个LUN上运行了数台虚拟机&#xff0c;虚拟机安装Windows Server操作系统。 服务器故障&分析&#xff1a; 管理员因误操作删除了一台虚拟机&#x…

苹果iPhone 15 Ultra和iPhone 15 Pro Max:新名字是否值得期待?

我们即将发现一个名字里有什么,至少如果一个关于iPhone 15 Pro Max的新谣言被证明是准确的。一份新的报告表明,当这款手机可能在苹果9月的发布会上首次亮相时,苹果可能会放弃Pro Max的名字,而将其称为iPhone 15 Ultra。 改名的原因是什么?好吧,这肯定会将苹果最高端的手…

【MD5加密】

MD5加密 什么是MD5密码MD5用途MD5特点MD5加密MD5解密总结那我们上面也已经提到啦&#xff0c;说MD5是可以进行解密或者说他是可以泄露密码等&#xff0c;所以我们还可以使用以下方法进行再次加密 第一种&#xff1a;MD5固定盐值第二种&#xff1a;MD5随机盐值 什么是MD5密码 官…