目录

一、 torch.nn模块 

二、module模块

 三、自定义搭建神经网络


 

一、 torch.nn模块 

 torch.nn — PyTorch 1.13 documentation

pytorch初学笔记(七):神经网络基本骨架 torch.nn.Module-LMLPHP

二、module模块

Module — PyTorch 1.13 documentation

 我们自己定义的神经网络需要继承nn.Module类,需要重写以下两个方法:

  1. init方法:初始化
  2. forward方法:前向传播

        在官方文档给出的实例中, 在init方法中进行了卷积操作,在forward方法中进行了relu非线性处理操作,代码如下所示。

import torch.nn as nn
import torch.nn.functional as F

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv1 = nn.Conv2d(1, 20, 5)
        self.conv2 = nn.Conv2d(20, 20, 5)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))

         示例代码中进行的操作流程是:

  • 对输入的x进行第一次卷积,再进行第一次非线性操作;
  • 再第二次进行卷积,然后第二次非线性操作。

pytorch初学笔记(七):神经网络基本骨架 torch.nn.Module-LMLPHP

 三、自定义搭建神经网络

  1. 自定义名为Maweiyi的神经网络,继承自nn.Module
  2. 重写init和forward两个方法,在forward中定义该神经网络的规则,即输入+1为输出
  3. 实例化神经网络
  4. 把tensor类型的值x放入神经网络中进行输出
  5. 成功输出结果为 x+1
import torch
from torch import nn


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

    def forward(self,input):
        output = input + 1;
        return output

# 创建神经网络
maweiyi = Maweiyi()
# 输入的值为x,tensor型,数值为1
x = torch.tensor(1.0)
# 输出为output
output = maweiyi(x)
print(output)
11-21 06:43