当前位置:   article > 正文

PyTorch深度学习入门笔记(八)神经网络的基本骨架 nn.Module的使用_class net(torch.nn.module)

class net(torch.nn.module)

课程学习笔记,课程链接
学习笔记同步发布在我的个人网站上,欢迎来访查看。

这篇博客将讲述如何搭建一个网络,是课程学习笔记,课程链接已经放在上方。

一、torch.nn简介

搭建神经网络常用的工具在 torch.nn 模块。官网:https://pytorch.org/docs/stable/nn.html
在这里插入图片描述
Containers中文翻译为容器,但这里可以理解为骨架,往这个骨架中添加一些内容就可以构成一个神经网络
Convolution Layers
Pooling Layers
Paading Layers
都是要添加进网络的各层。

其中,torch,nn.Module 神经网络所有模块的基类
在这里插入图片描述
官网示例代码如下:

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

class Model(nn.Module):
    def __init__(self):
        super(Model, self).__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))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

第三行定义的 Model 就是所要搭建的网络,继承了 nn.Module 类
定义了 forward 函数
神经网络前向传播,就是将数据输入到网络,通过前向传播,输出处理后的数据
在这里插入图片描述
在官网示例代码中:

def forward(self, x):
        x = F.relu(self.conv1(x))
        return F.relu(self.conv2(x))
  • 1
  • 2
  • 3

forward 对输入数据 x先进行卷积+非线性处理,再对前一步处理所得到的结果再进行一次卷积+非线性处理。
在这里插入图片描述

二、简单示例

参考官网示例代码,建立一个自己的网络模板

import torch
from torch import nn


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

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

net1 = net()
x = torch.tensor(1.0)
output = net1(x)
print(output)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

结果:
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/360155
推荐阅读
相关标签
  

闽ICP备14008679号