python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > PyTorch 激活函数

PyTorch 激活函数的实现示例

作者:byxdaz

激活函数是神经网络中至关重要的组成部分,本文就来详细的介绍一下PyTorch常用的激活函数,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

激活函数是神经网络中至关重要的组成部分,它们为网络引入了非线性特性,使得神经网络能够学习复杂模式。PyTorch 提供了多种常用的激活函数实现。

常用激活函数

1. ReLU (Rectified Linear Unit)

数学表达式:

PyTorch实现:

torch.nn.ReLU(inplace=False)

特点:

示例:

relu = nn.ReLU()
input = torch.tensor([-1.0, 0.0, 1.0, 2.0])
output = relu(input)  # tensor([0., 0., 1., 2.])

2. LeakyReLU

数学表达式:

PyTorch实现:

torch.nn.LeakyReLU(negative_slope=0.01, inplace=False)

特点:

示例

leaky_relu = nn.LeakyReLU(negative_slope=0.1)
input = torch.tensor([-1.0, 0.0, 1.0, 2.0])
output = leaky_relu(input)  # tensor([-0.1000, 0.0000, 1.0000, 2.0000])

3. Sigmoid

数学表达式:

 PyTorch实现:

torch.nn.Sigmoid()

特点:

示例:

sigmoid = nn.Sigmoid()
input = torch.tensor([-1.0, 0.0, 1.0, 2.0])
output = sigmoid(input)  # tensor([0.2689, 0.5000, 0.7311, 0.8808])

4. Tanh (Hyperbolic Tangent)

数学表达式:

PyTorch实现

torch.nn.Tanh()

特点:

示例:

tanh = nn.Tanh()
input = torch.tensor([-1.0, 0.0, 1.0, 2.0])
output = tanh(input)  # tensor([-0.7616, 0.0000, 0.7616, 0.9640])

5. Softmax

数学表达式:

PyTorch实现:

torch.nn.Softmax(dim=None)

特点:

示例:

softmax = nn.Softmax(dim=1)
input = torch.tensor([[1.0, 2.0, 3.0]])
output = softmax(input)  # tensor([[0.0900, 0.2447, 0.6652]])

其他激活函数

6. ELU (Exponential Linear Unit)

torch.nn.ELU(alpha=1.0, inplace=False)

7. GELU (Gaussian Error Linear Unit)

torch.nn.GELU()

8. Swish

class Swish(nn.Module):
    def forward(self, x):
        return x * torch.sigmoid(x)

选择指南

自定义激活函数

PyTorch可以轻松实现自定义激活函数:

class CustomActivation(nn.Module):
    def __init__(self):
        super().__init__()
    
    def forward(self, x):
        return torch.where(x > 0, x, torch.exp(x) - 1)

注意事项

您可能感兴趣的文章:
阅读全文