激活函数 Activation Functions

PyTorch 激活函数 Activation Functions

0. 概述

PyTorch 中,激活函数有两种形式:

  • (模块)的形式:需要先定义,再使用。为 torch.nn 模块下的类,官方文档

  • 函数形式:直接使用。为 torch.nn.functional 模块或 torch.nn 模块中的函数,官方文档

PyTorch 中,对于激活有以下性质

  • 一般不会改变数据的尺寸(size)或维度(dim)

  • 没有学习参数

实例:引入相关模块

import torch
import torch.nn as nn
import torch.nn.functional as F

1. Sigmoid

torch.nn.Sigmoid():对输入数据的每个元素做 sigmoid 激活

等价的函数形式

  • F.sigmoid(input)(PyTorch 官方不推荐

  • torch.sigmoid(input)

A. 计算公式

\[\sigma \ : \ \mathbb{R} \mapsto (0,1) \ , \qquad \sigma(x) = \frac{1}{1+\exp(-x)} \]

实例

input = torch.rand((3, 5))

# 方式 1:nn.Sigmoid()
output_1 = nn.Sigmoid()(input)

# 方式 2:torch.sigmoid() 或 F.sigmoid()
output_2 = torch.sigmoid(input)
output_3 = F.sigmoid(input) 
# 使用 F.sigmoid() 会输出 UserWarning 信息
# UserWarning: nn.functional.sigmoid is deprecated. Use torch.sigmoid instead.
print(torch.sum(torch.abs(output_2 - output_1)), 
      torch.sum(torch.abs(output_3 - output_1)))

2. Softmax

torch.nn.Softmax(dim=None):在指定的维度上做 Softmax 激活

等价的函数形式

  • F.softmax(input, dim=None)

  • torch.softmax(input, dim=None)

A. 计算公式

\[\text{Softmax} \ : \ \mathbb{R} \mapsto (0,1) \ , \qquad \text{Softmax}(x) = \frac{\exp(x_i)}{\sum_j \exp(x_j)} \]

B. 函数形式

主要参数:

  • dim:指定 Softmax 的维度;输出数据在 dim 指定的维度上相加等于 1

实例

input = torch.rand((3, 5))

# 方式 1:torch.softmax() 或 F.softmax()
output_1 = nn.Softmax(dim=1)(input)
print(output_1.size())
print(torch.sum(output_1, dim=1))
# Output: tensor([1., 1., 1.])

# 方式 2:torch.softmax() 或 F.softmax()
output_2 = torch.softmax(input, dim=1)
output_3 = F.softmax(input, dim=1)
print(torch.sum(torch.abs(output_2 - output_1)), 
      torch.sum(torch.abs(output_3 - output_1)))

参考文献

文中代码:ColabGithub

邱锡鹏,"4.1 神经元" in 神经网络与深度学习,机械工业出版社,https://nndl.github.io/, 2020.

Activation function, Wikipedia, site

posted @ 2022-05-26 19:22  veager  阅读(221)  评论(0编辑  收藏  举报