一、pytorch官网中torch.nn的相关简介

可以看到torch.nn中有许多模块:

二、Containers模块

1、MODULE(CLASS : torch.nn.Module)

import torch.nn as nn
import torch.nn.functional as Fclass Model(nn.Module):#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))

forward(*input)

Defines the computation performed at every call. Should be overridden by all subclasses.

2、搭建神经网络模型

import torch
import torch.nn as nn
import torch.nn.functional as F
# 定义自己的神经网络模板
class Lemon(nn.Module):def __init__(self) -> None:super().__init__()def forward(self,input):output = input + 1return output
# 创建神经网络
lemon = Lemon()
x = torch.tensor(1.0)
output = lemon(x)
print(output)

三、Convolution Layers 卷积层

  1. nn.Conv1d/nnCon2d

  • input – input tensor of shape (minibatch,in_channels,iH,iW)输入

  • weight – filters of shape (out_channels,groupsin_channels,kH,kW)权重/卷积核

  • bias – optional bias tensor of shape (out_channels). Default: None偏置

  • stride – the stride of the convolving kernel. Can be a single number or a tuple (sH, sW). Default: 1步进/长 SH和SW分别控制横向的步进和纵向的步进

  • padding – implicit paddings on both sides of the input. Can be a single number or a tuple (padH, padW). Default: 0

  • dilation – the spacing between kernel elements. Can be a single number or a tuple (dH, dW). Default: 1

  • groups – split input into groups, in_channelsin_channels should be divisible by the number of groups. Default: 1

import torch
import torch.nn.functional as F
# 输入
input = torch.tensor([[1,2,0,3,1],[0,1,2,3,1],[1,2,1,0,0],[5,2,3,1,1],[2,1,0,1,1]])
# 卷积核
kernel = torch.tensor([[1,2,1],[0,1,0],[2,1,0]])
print(input.shape) #torch.Size([5, 5])
print(kernel.shape) #torch.Size([3, 3])
#官方文档中输入input和卷积核weight需要四个参数——>input tensor of shape (minibatch,in_channels,iH,iW)
#所以可以使用reshape二参变四参
input = torch.reshape(input,(1,1,5,5)) #torch.Size([1, 1, 5, 5])
kernel = torch.reshape(kernel,(1,1,3,3)) #torch.Size([1, 1, 3, 3])
print(input.shape) #torch.Size([5, 5])
print(kernel.shape) #torch.Size([3, 3])output = F.conv2d(input,kernel,stride=1)
print(output)

一般来讲,输出的维度 = 输入的维度 - 卷积核大小/stride + 1

padding =1,为上下左右各填充一行,空的地方默认为0

torch.nn.Conv2d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros')
bias:偏置,卷积后的结果是否加减一个常数
padding_mode:填充模式
in_channels (int) – Number of channels in the input image # 输入图像的通道数,彩色一般是三通道
out_channels (int) – Number of channels produced by the convolution# 输出的通道数
kernel_size (int or tuple) – Size of the convolving kernel #定义卷积核大小 3---3*3  (1,2) #卷积核不需要自己给定,是在训练过程中不断完善的。

in_channel和out_channel的实际解释:

若outchannel=2时,卷积层就会生成两个卷积核【输出通道数就是卷积核的个数】

  1. Pooling layers

nn.MaxPool2d

torch.nn.MaxPool2d(kernel_size, stride=None, padding=0, dilation=1, return_indices=False, ceil_mode=False)kernel_size:表示做最大池化的窗口大小,可以是单个值,也可以是tuple元组
stride:步长,默认是kernel_size大小
dilation:空洞卷积
ceil_mode :布尔类型,为True,用向上取整的方法,计算输出形状;默认是向下取整。

默认的步长是池化核的大小(3)

Ceil_mode=True时候,向上取整,保留6个数 。False时不保留

import torch
from torch import nn
from torch.nn import MaxPool2d
input = torch.tensor([[1,2,0,3,1],[0,1,2,3,1],[1,2,1,0,0],[5,2,3,1,1],[2,1,0,1,1]], dtype=torch.float)
# input:(N,C,Hin,Win)  N->batch-size C->通道数
input = torch.reshape(input,(-1,1,5,5))
print(input.shape)#torch.Size([1, 1, 5, 5])class Lemon(nn.Module):def __init__(self):super(Lemon,self).__init__()self.maxpool1 = MaxPool2d(kernel_size=3,ceil_mode=True)def forward(self,input):output = self.maxpool1(input)return output
lemon = Lemon()
output = lemon(input)
print(output)

最大池化的目的就是保留输入的特征,同时减少数据量。(卷积的作用是提取特征,池化的作用是降低特征的数据量)

import torch
import torchvision
from torch import nn
from torch.nn import MaxPool2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriterdataset = torchvision.datasets.CIFAR10("../data",train=False,download=True,transform=torchvision.transforms.ToTensor())
dataloader = DataLoader(dataset,batch_size=64)class Lemon(nn.Module):def __init__(self):super(Lemon,self).__init__()self.maxpool1 = MaxPool2d(kernel_size=3,ceil_mode=False)def forward(self,input):output = self.maxpool1(input)return output
lemon = Lemon()
writer = SummaryWriter("../logs_maxpool")
step=0
for data in dataloader:imgs, targets = datawriter.add_images("input",imgs,step)print(imgs.shape)output = lemon(imgs) #torch.Size([64, 3, 32, 32])writer.add_images("output",output,step)print(output.shape) #torch.Size([64, 3, 10, 10])step = step + 1
writer.close()
  1. 非线性激活Non-linear Activations (weighted sum, nonlinearity)

非线性激活是为了给神经网络中引入一些非线性的特质,相当于两层神经元之间的关系函数,上层的输出被激活函数作用得到下层的输入。

import torch
from torch import nn
from torch.nn import ReLUinput = torch.tensor([[1,-0.5],[-1,3]])input = torch.reshape(input,(-1,1,2,2)) #batch-size自己算   1维 2*2
print(input.shape) #torch.Size([1, 1, 2, 2])class Lemon(nn.Module):def __init__(self):super(Lemon,self).__init__()self.relu1 = ReLU()#inplace:bool=True直接在input上进行替换,默认为Falsedef forward(self,input):output = self.relu1(input)return output
lemon = Lemon()
output = lemon(input)
print(output)
  1. Linear Layers线性层

torch.nn.Linear(in_features, out_features, bias=True)
# in_features就是输入的个数d, out_features就是输出的个数l

weight与bias都是从上述分布中进行采样,进行初始化的。

# vgg16 moedel
import torch
import torchvision
from torch import nn
from torch.nn import Linear
from torch.utils.data import DataLoader
dataset = torchvision.datasets.CIFAR10("../data",train=False,transform=torchvision.transforms.ToTensor(),download=True)
dataloader = DataLoader(dataset,batch_size=64,drop_last=True)#doop_last默认为False,保留了最后16张图,会报错class Lemon(nn.Module):def __init__(self):super(Lemon,self).__init__()self.linear1 = Linear(in_features=196608,out_features=10)def forward(self,input):output = self.linear1(input)return outputlemon = Lemon()
for data in dataloader:imgs,targets = data # imgs.shape-->torch.Size([64, 3, 32, 32])print(imgs.shape)input = torch.reshape(imgs,(1,1,1,-1)) # output.shape-->torch.Size([1, 1, 1, 196608])  每个batch里面只有一个 单通道 1行n列的矩阵 (batch_size,channel,height,weight)print(input.shape)output = lemon(input) #torch.Size([1, 1, 1, 10])print(output.shape)

神经网络的基本骨架—nn.Module使用相关推荐

  1. 神经网络的基本骨架——nn.Module的使用

    pytorch官网--docs(官方文档)--torch.nn(关于神经网络的工具) Containers:给神经网络定义了一些骨架 在卷积神经网络中的一些核心部分: Convolution Laye ...

  2. 神经网络的基本骨架-nn.Moudle的使用

    文章 Module是Contains中最常用的模块,Contains是用来构建神经网络架构的. Contains官方文档 神经网络的基本骨架-nn.Moudle的使用官方文档 根据官方文档的示例: i ...

  3. [Pytorch系列-30]:神经网络基础 - torch.nn库五大基本功能:nn.Parameter、nn.Linear、nn.functioinal、nn.Module、nn.Sequentia

    作者主页(文火冰糖的硅基工坊):文火冰糖(王文兵)的博客_文火冰糖的硅基工坊_CSDN博客 本文网址:https://blog.csdn.net/HiWangWenBing/article/detai ...

  4. 深度之眼 PyTorch 训练营第 4 期(5):构建模型 torch.nn.Module

    本文中,我们看一看如何构建模型. 创造一个模型分两步:构建模型和权值初始化.而构建模型又有"定义单独的网络层"和"把它们拼在一起"两步. 1. torch.nn ...

  5. PyTorch 笔记(14)— nn.module 实现简单感知机和多层感知机

    autograd 实现了自动微分系统,然而对深度学习来说过于底层,而本节将介绍 nn 模块,是构建于 autograd 之上的神经网络模块. 1. 简单感知机 使用 autograd 可实现深度学习模 ...

  6. 【小白学习PyTorch教程】四、基于nn.Module类实现线性回归模型

    「@Author:Runsen」 上次介绍了顺序模型,但是在大多数情况下,我们基本都是以类的形式实现神经网络. 大多数情况下创建一个继承自 Pytorch 中的 nn.Module 的类,这样可以使用 ...

  7. 43_pytorch nn.Module,模型的创建,构建子模块,API介绍,Sequential(序号),ModuleList,ParameterList,案例等(学习笔记)

    1.40.PyTorch nn.Module 1.40.1.模型的创建 1.40.2.构建子模块 1.40.3.nn.Module API介绍 1.40.3.1.核心功能 1.40.3.2.查看模块 ...

  8. nn.functional 和 nn.Module入门讲解

    本文来自<20天吃透Pytorch> 一,nn.functional 和 nn.Module 前面我们介绍了Pytorch的张量的结构操作和数学运算中的一些常用API. 利用这些张量的AP ...

  9. torch.nn.Module()

    torch.nn.Module() 如果自己想研究,官方文档 它是所有的神经网络的根父类! 你的神经网络必然要继承! 模块也可以包含其他模块,允许将它们嵌套在树结构中.所以呢,你可以将子模块指定为常规 ...

最新文章

  1. 7.Mongodb复制(副本集)
  2. 单细胞转录组专题研讨会第二期
  3. 知识点2-对二进制的运用
  4. centos下如何停止ping命令
  5. 算法学习之路|称量硬币(模拟)
  6. 有关Java中json字符串与map的转换使用
  7. 有哪些好用不火的软件?
  8. 在Spring Boot使用H2内存数据库
  9. MyEclipse for Windows快捷键
  10. 基于Windows 7旗舰版搭建WinCE6.0开发环境的过程
  11. Android之自定义控件深入
  12. python Lambda 表达式
  13. 2021年慈溪中学高考成绩查询,2021年慈溪市高考状元名单资料,今年慈溪市高考状元多少分...
  14. 第0次作业 -- 博客园作业提交方法
  15. Java ConcurrentModificationException 异常分析与解决方案
  16. php mvc框架单例,ZeroPHP: 开发的第一个PHP框架 遵循MVC架构设计。 任重道远。
  17. python将linux时间戳转换,Unix时间戳转换(python)
  18. Excel如何计算两列数据的乘积之和(相乘之后相加)
  19. 【ATSC】【OTT】Netflix将作为美国有线机顶盒界面中的一个频道
  20. 用python绘制叠加等边三角形_python叠加等边三角形绘制

热门文章

  1. 用Visual Studio查看图片的二进制流
  2. Markdown基础命令
  3. 国内有替代Intel的选择吗?
  4. React 路由报错 You should not use Route or withRouter() outside a Router
  5. JQuery自动轮播效果,带字幕说明,带底部滚动圈圈,兼容IE7以上所有主流浏览器。(魔兽背景哟亲)
  6. java 输入 字符_在java中如何输入一个char型字符。
  7. 百度搜索的网页点进去一片空白,刷新才可以
  8. CISSP考试大纲将在2021年5月1日更新
  9. 老年人孤独感与精神病症状加剧有关
  10. Qt修改工程名称的方法