趋近智
双曲正切,通常称为 Tanh,是一种常见的 S 形激活函数。与 Sigmoid 等其他 S 形函数类似,Tanh 引入非线性,使网络能从简单的线性关系中学到复杂模式。然而,由于其输出范围,Tanh 在特定情境下具有独特的优点。
从数学上看,Tanh 函数的定义如下:
tanh(x)=ex+e−xex−e−x有趣的是,Tanh 与 Sigmoid 函数关系密切。它可以表示为 Sigmoid 的缩放和偏移形式:
tanh(x)=2⋅sigmoid(2x)−1我们来看一下 Tanh 函数的一些属性:
以下是 Tanh 函数及其导数的可视化图示:
Tanh 函数将输入映射到 (-1, 1) 范围,并以零为中心。当输入为 0 时,其导数达到峰值 1,并且随着输入大小的增加而趋近于 0。
优点:
不足:
过去,Tanh 因其零中心输出,常被用于隐藏层,优于 Sigmoid。它普遍用于前馈网络,尤其是在某些类型的循环神经网络(RNN)中。
然而,随着 ReLU 及其变体(我们接下来会谈到)的兴起,Tanh 作为标准前馈网络和卷积神经网络(CNN)隐藏层的默认选择已不再那么常见。它仍然在特定情境中发挥作用,尤其是在 LSTM 和 GRU(某种类型的 RNN)的门控机制中,其 (-1, 1) 范围是有益的。
以下是如何在 PyTorch 层中使用 Tanh 的示例:
import torch
import torch.nn as nn
# 示例输入张量
input_tensor = torch.randn(5, 10) # 批大小为 5,每个样本有 10 个特征
# 定义一个使用 Tanh 激活的层
# 选项 1:使用 nn.Tanh() 作为模块
tanh_activation = nn.Tanh()
output_tensor = tanh_activation(input_tensor)
# 选项 2:直接使用 torch.tanh(函数式方法)
output_tensor_functional = torch.tanh(input_tensor)
# 定义一个线性层,后接 Tanh
linear_layer = nn.Linear(in_features=10, out_features=20)
activated_output = torch.tanh(linear_layer(input_tensor))
print("输入形状:", input_tensor.shape)
print("输出形状(模块方式):", output_tensor.shape)
print("输出形状(函数方式):", output_tensor_functional.shape)
print("输出形状(线性层 + Tanh):", activated_output.shape)
print("\n输出示例(第一个元素,前 5 个特征):\n", activated_output[0, :5])
虽然 Tanh 解决了 Sigmoid 非零中心的问题,但它没有解决饱和函数本身具有的梯度消失问题。这一局限性促成了 ReLU 及其变体的发展和广泛使用,我们将在下节中介绍这些内容。
这部分内容有帮助吗?
© 2026 ApX Machine Learning用心打造