PyTorch之前向传播函数forward

神经网络的典型处理如下所示:

1. 定义可学习参数的网络结构(堆叠各层和层的设计);
2. 数据集输入;
3. 对输入进行处理(由定义的网络层进行处理),主要体现在网络的前向传播;
4. 计算loss ,由Loss层计算;
5. 反向传播求梯度;
6. 根据梯度改变参数值,最简单的实现方式(SGD)为:

   weight = weight - learning_rate * gradient

下面是利用PyTorch定义深度网络层(Op)示例:

class FeatureL2Norm(torch.nn.Module):
    def __init__(self):
        super(FeatureL2Norm, self).__init__()

    def forward(self, feature):
        epsilon = 1e-6
#        print(feature.size())
#        print(torch.pow(torch.sum(torch.pow(feature,2),1)+epsilon,0.5).size())
        norm = torch.pow(torch.sum(torch.pow(feature,2),1)+epsilon,0.5).unsqueeze(1).expand_as(feature)
        return torch.div(feature,norm)
class FeatureRegression(nn.Module):
    def __init__(self, output_dim=6, use_cuda=True):
        super(FeatureRegression, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(225, 128, kernel_size=7, padding=0),
            nn.BatchNorm2d(128),
            nn.ReLU(inplace=True),
            nn.Conv2d(128, 64, kernel_size=5, padding=0),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
        )
        self.linear = nn.Linear(64 * 5 * 5, output_dim)
        if use_cuda:
            self.conv.cuda()
            self.linear.cuda()

    def forward(self, x):
        x = self.conv(x)
        x = x.view(x.size(0), -1)
        x = self.linear(x)
        return x

由上例代码可以看到,不论是在定义网络结构还是定义网络层的操作(Op),均需要定义forward函数,下面看一下PyTorch官网对PyTorch的forward方法的描述:

那么调用forward方法的具体流程是什么样的呢?具体流程是这样的:

以一个Module为例:
1. 调用module的call方法
2. module的call里面调用module的forward方法
3. forward里面如果碰到Module的子类,回到第1步,如果碰到的是Function的子类,继续往下
4. 调用Function的call方法
5. Function的call方法调用了Function的forward方法。
6. Function的forward返回值
7. module的forward返回值
8. 在module的call进行forward_hook操作,然后返回值。

上述中“调用module的call方法”是指nn.Module 的__call__方法。定义__call__方法的类可以当作函数调用,具体参考Python的面向对象编程。也就是说,当把定义的网络模型model当作函数调用的时候就自动调用定义的网络模型的forward方法。nn.Module 的__call__方法部分源码如下所示:

def __call__(self, *input, **kwargs):
   result = self.forward(*input, **kwargs)
   for hook in self._forward_hooks.values():
       #将注册的hook拿出来用
       hook_result = hook(self, input, result)
   ...
   return result

可以看到,当执行model(x)的时候,底层自动调用forward方法计算结果。具体示例如下:

class LeNet(nn.Module):
    def __init__(self):
        super(LeNet, self).__init__()

	layer1 = nn.Sequential()
	layer1.add_module('conv1', nn.Conv(1, 6, 3, padding=1))
	layer1.add_moudle('pool1', nn.MaxPool2d(2, 2))
	self.layer1 = layer1

	layer2 = nn.Sequential()
	layer2.add_module('conv2', nn.Conv(6, 16, 5))
	layer2.add_moudle('pool2', nn.MaxPool2d(2, 2))
	self.layer2 = layer2

	layer3 = nn.Sequential()
	layer3.add_module('fc1', nn.Linear(400, 120))
	layer3.add_moudle('fc2', nn.Linear(120, 84))
	layer3.add_moudle('fc3', nn.Linear(84, 10))
	self.layer3 = layer3
    def forward(self, x):
	x = self.layer1(x)
	x = self.layer2(x)
	x = x.view(x.size(0), -1)
	x = self.layer3(x)
	return x

model = LeNet()
y = model(x)

如上则调用网络模型定义的forward方法。

如果您觉得我的文章对您有所帮助,欢迎扫码进行赞赏!

参考:

1. pytorch学习笔记(九):PyTorch结构介绍

2. pytorch学习笔记(七):pytorch hook 和 关于pytorch backward过程的理解

3. Pytorch入门学习(三):Neural Networks

 

 

  • 163
    点赞
  • 638
    收藏
    觉得还不错? 一键收藏
  • 24
    评论
PyTorch中的前向传播是指将输入数据通过神经网络模型,从输入层经过各个隐藏层,最终到达输出层的过程。在PyTorch中,我们可以通过定义一个继承自`torch.nn.Module`的网络类来构建神经网络模型。 在这个网络类中,我们需要实现`forward`方法,该方法会接收输入数据作为参数,并按照网络的结构将其传递到下一层。在`forward`方法中,我们可以使用PyTorch提供的各种层(如全连接层、卷积层等)来定义网络的结构。 以下是一个简单的例子,展示了如何在PyTorch中进行前向传播: ```python import torch import torch.nn as nn class MyModel(nn.Module): def __init__(self): super(MyModel, self).__init__() self.fc1 = nn.Linear(10, 5) self.fc2 = nn.Linear(5, 2) def forward(self, x): x = self.fc1(x) x = torch.relu(x) x = self.fc2(x) return x # 创建一个模型实例 model = MyModel() # 生成随机输入数据 input_data = torch.randn(1, 10) # 将输入数据传递给模型进行前向传播 output = model(input_data) print(output) ``` 在上面的例子中,我们首先定义了一个名为`MyModel`的网络类,其中包含两个全连接层。在`forward`方法中,我们首先将输入数据`x`传递给第一个全连接层`fc1`,然后使用ReLU激活函数作用于输出结果。接着,将激活后的结果传递给第二个全连接层`fc2`,最终得到模型的输出。我们可以通过调用模型实例的方式来进行前向传播,将输入数据传递给模型,得到输出结果。 希望这个例子能帮助你理解PyTorch中的前向传播过程!如果还有其他问题,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值