介绍
torch.nn.functional 是 PyTorch 中的一个模块,提供了许多函数式的神经网络操作,包括激活函数、损失函数、卷积操作等。这些函数是无状态的(stateless),与 torch.nn 中的模块化层(如 nn.ReLU、nn.Conv2d 等)不同,torch.nn.functional 提供的是直接的函数调用方式。
激活函数
torch.nn.functional 提供了许多常用的激活函数,例如 ReLU、Sigmoid、Tanh 等。
import torch.nn.functional as F
示例
import torch
import torch.nn.functional as F
x = torch.tensor([-1.0, 0.0, 1.0])
relu_output = F.relu(x) # ReLU 激活
softmax_output = F.softmax(x, dim=0) # Softmax 激活
print(relu_output) # tensor([0., 0., 1.])
print(softmax_output