PyTorch学习笔记:nn.Tanh——Tanh激活函数
torch.nn.Tanh()
功能:逐元素应用Tanh函数(双曲正切)对数据进行激活,将元素调整到区间(-1,1)内
函数方程:
Tanh
(
x
)
=
tanh
(
x
)
=
e
x
−
e
−
x
e
x
+
e
−
x
\text{Tanh}(x)=\text{tanh}(x)=\frac{e^x-e^{-x}}{e^x+e^{-x}}
Tanh(x)=tanh(x)=ex+e−xex−e−x
注意:
- 输入可以是任意尺寸的数据,输出尺寸与输入尺寸相同
- 该激活函数定义时无输入
代码案例
一般用法
import torch.nn as nn
import torch
Tanh = nn.Tanh()
x = torch.randn(10)
value = Tanh(x)
print(x)
print(value)
输出
# 输入
tensor([-0.7827, -0.3373, 0.2476, -0.5910, -1.2637, 1.0676, 1.1027, -0.8984,
-0.0252, -0.1457])
# 数据经过Tanh激活函数之后
tensor([-0.6542, -0.3251, 0.2426, -0.5306, -0.8521, 0.7885, 0.8015, -0.7155,
-0.0252, -0.1447])
注:绘图程序
import torch.nn as nn
import torch
import numpy as np
import matplotlib.pyplot as plt
Tanh = nn.Tanh()
x = torch.from_numpy(np.linspace(-5,5,100))
value = Tanh(x)
plt.plot(x, value)
plt.savefig('Tanh.jpg')
官方文档
nn.Tanh():https://pytorch.org/docs/stable/generated/torch.nn.Tanh.html#torch.nn.Tanh
初步完稿于:2022年2月16日