0
点赞
收藏
分享

微信扫一扫

【d46】【Java】【力扣】234.回文链表

沈芏 2024-09-21 阅读 27

SwishGLU 是一种激活函数,结合了 Swish 和 GLU(Gated Linear Unit)的特性。它通过引入门控机制来增强模型的表现,尤其是在处理复杂特征时。Swish 本身是一个平滑的激活函数,具有更好的性能,而 GLU 则利用门控结构来控制信息的流动。

SwishGLU 的实现可以分为几个步骤。首先,我们需要了解 Swish 和 GLU 的定义:

  1. Swish 激活函数
    Swish ( x ) = x ⋅ σ ( x ) \text{Swish}(x) = x \cdot \sigma(x) Swish(x)=xσ(x)
    其中, σ ( x ) \sigma(x) σ(x) 是 Sigmoid 函数。

  2. GLU 激活函数
    GLU ( A , B ) = A ⋅ σ ( B ) \text{GLU}(A, B) = A \cdot \sigma(B) GLU(A,B)=Aσ(B)
    这里, A A A B B B 是输入的两个不同线性变换的结果。

结合这两个概念,SwishGLU 可以表示为:
SwishGLU ( x ) = Swish ( A ) ⋅ σ ( B ) \text{SwishGLU}(x) = \text{Swish}(A) \cdot \sigma(B) SwishGLU(x)=Swish(A)σ(B)
其中 A A A B B B 是通过线性层得到的。

实现步骤

以下是一个简单的 PyTorch 示例:

import torch
import torch.nn as nn

class SwishGLU(nn.Module):
    def __init__(self, input_size, output_size):
        super(SwishGLU, self).__init__()
        self.linear_A = nn.Linear(input_size, output_size)
        self.linear_B = nn.Linear(input_size, output_size)

    def swish(self, x):
        return x * torch.sigmoid(x)

    def forward(self, x):
        A = self.linear_A(x)
        B = self.linear_B(x)
        return self.swish(A) * torch.sigmoid(B)

# 示例用法
input_size = 10
output_size = 5
model = SwishGLU(input_size, output_size)
input_tensor = torch.randn(32, input_size)  # 假设批量大小为 32
output = model(input_tensor)

ReLU 和 GELU 激活函数本身不包含可训练参数,只是简单地对输入进行转换。而 SwishGLU 包含两个线性层 A A A B B B,这些层的权重矩阵和偏置是可训练的,因此在训练过程中可以优化,从而增强模型的表达能力。

举报

相关推荐

0 条评论