torch.nn.modules中不同激活函数的应用比较
在torch.nn.modules中,提供了许多不同的激活函数来引入非线性特征和增加网络的表达能力。下面将介绍一些常用的激活函数,并给出它们的使用示例。
1. ReLU激活函数:
ReLU(Rectified Linear Unit)是最常用的激活函数之一,其定义为:f(x) = max(0, x)。ReLU函数在x大于0时输出x,而在x小于等于0时输出0。它可以帮助网络更好地拟合非线性数据,并提供了快速和有效的计算。
import torch
import torch.nn as nn
# 定义网络类
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.relu = nn.ReLU()
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
return x
# 创建网络实例
net = Net()
# 使用ReLU激活函数
input = torch.randn(5, 10)
output = net(input)
print(output)
2. Sigmoid激活函数:
Sigmoid激活函数定义为:f(x) = 1 / (1 + exp(-x))。它将输入的值映射到0到1之间的连续输出。Sigmoid函数常用于二分类问题,但它在深度神经网络中的使用受到梯度消失问题的限制。
import torch
import torch.nn as nn
# 定义网络类
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.fc1(x)
x = self.sigmoid(x)
return x
# 创建网络实例
net = Net()
# 使用Sigmoid激活函数
input = torch.randn(5, 10)
output = net(input)
print(output)
3. Tanh激活函数:
Tanh激活函数定义为:f(x) = (exp(x) - exp(-x)) / (exp(x) + exp(-x))。它将输入的值映射到-1到1之间的连续输出,因此更适合于有负数输入的情况。Tanh函数在处理输入数据时保持了其均值接近零的特性,并且相对于Sigmoid激活函数具有更大的梯度。
import torch
import torch.nn as nn
# 定义网络类
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 20)
self.tanh = nn.Tanh()
def forward(self, x):
x = self.fc1(x)
x = self.tanh(x)
return x
# 创建网络实例
net = Net()
# 使用Tanh激活函数
input = torch.randn(5, 10)
output = net(input)
print(output)
4. Softmax激活函数:
Softmax激活函数定义为:f(x_i) = exp(x_i) / sum(exp(x_j), for j=1 to n)。它通常用于多分类问题中,将输入的向量映射为概率分布。Softmax函数能够将每个元素的输出转化为一个大于0且求和为1的实数,以表示该元素属于对应类别的概率。
import torch
import torch.nn as nn
# 定义网络类
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(10, 3)
self.softmax = nn.Softmax(dim=1)
def forward(self, x):
x = self.fc1(x)
x = self.softmax(x)
return x
# 创建网络实例
net = Net()
# 使用Softmax激活函数
input = torch.randn(5, 10)
output = net(input)
print(output)
除了上述介绍的激活函数之外,torch.nn.modules还提供了很多其他激活函数,例如LeakyReLU、ELU、SELU等。不同的激活函数适用于不同的场景,可以根据具体任务需求选择合适的激活函数来提高网络的性能。
