04 - 非线性激活
概念
在PyTorch中,非线性激活函数是用于神经网络中的一种函数,它们的作用是在神经网络的各层之间引入非线性特性,从而增强模型的表达能力。常见的非线性激活函数包括ReLU(Rectified Linear Unit)、Sigmoid、Tanh等。
https://pytorch.org/docs/stable/nn.html
下面是这些激活函数的简要介绍以及如何在PyTorch中使用它们:
- ReLU(Rectified Linear Unit):ReLU是最常用的激活函数之一,其公式为 f(x) = max(0, x)。它将所有负数映射为0,保留正数不变。
- inplace参数用于指定是否原地修改张量。原地操作意味着直接在原始张量上进行操作,而不是创建一个新的张量来保存结果。这可以在节省内存的同时提高性能。对于ReLU激活函数而言,inplace参数控制是否在原地修改输入张量。默认情况下,inplace参数为False,即不进行原地操作。如果将inplace设置为True,则会在原始张量上直接执行ReLU操作,而不创建新的张量。(简而言之就是是否对input进行原位置上的替换)
在PyTorch中,使用ReLU激活函数的示例代码如下:
import torch
import torch.nn as nn
# 定义一个全连接层
linear_layer = nn.Linear(in_features=10, out_features=5)
# 使用ReLU作为激活函数
activation = nn.ReLU()
# 输入数据
input_data = torch.randn(1, 10)
# 计算全连接层的输出
output = linear_layer(input_data)
# 对输出应用ReLU激活函数
output_with_activation = activation(output)
- Sigmoid:Sigmoid函数的公式为 f(x) = 1 / (1 + e^(-x)),它将输入的值映射到0到1之间,常用于二分类问题中的输出层。
在PyTorch中,使用Sigmoid激活函数的示例代码如下:
import torch
import torch.nn as nn
# 定义一个全连接层
linear_layer = nn.Linear(in_features=10, out_features=1)
# 使用Sigmoid作为激活函数
activation = nn.Sigmoid()
# 输入数据
input_data = torch.randn(1, 10)
# 计算全连接层的输出
output = linear_layer(input_data)
# 对输出应用Sigmoid激活函数
output_with_activation = activation(output)
- Tanh:Tanh函数的公式为 f(x) = (e^(2x) - 1) / (e^(2x) + 1),它将输入的值映射到-1到1之间,在某些情况下用于隐藏层的激活函数。
在PyTorch中,使用Tanh激活函数的示例代码如下:
import torch
import torch.nn as nn
# 定义一个全连接层
linear_layer = nn.Linear(in_features=10, out_features=5)
# 使用Tanh作为激活函数
activation = nn.Tanh()
# 输入数据
input_data = torch.randn(1, 10)
# 计算全连接层的输出
output = linear_layer(input_data)
# 对输出应用Tanh激活函数
output_with_activation = activation(output)
示例
import torch
input = torch.tensor([[1, -0.5],
[-1, 3]])
print(input)
output = torch.reshape(input, (-1, 1, 2, 2))
print(output.shape)
class MyReLU(torch.nn.Module):
def __init__(self):
super(MyReLU, self).__init__()
self.relu = torch.nn.ReLU()
def forward(self, input):
output = self.relu(input)
return output
net = MyReLU()
output = net(input)
print(output)
import torch
import torchvision
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
dataset = torchvision.datasets.CIFAR10(root='./dataset', train=False, download=True,
transform=torchvision.transforms.ToTensor())
dataloader = DataLoader(dataset, batch_size=64)
class MySig(torch.nn.Module):
def __init__(self):
super(MySig, self).__init__()
self.relu = torch.nn.ReLU()
self.sigmoid = torch.nn.Sigmoid()
def forward(self, input):
output = self.sigmoid(input)
return output
net = MySig()
writer = SummaryWriter("logs_sigmoid")
step = 0
for data in dataloader:
imgs, targets = data
writer.add_images("input", imgs, step)
output = net(imgs)
writer.add_images("output", output, step)
step += 1
writer.close()