一、pytorch官网中torch.nn的相关简介
可以看到torch.nn中有许多模块:
二、Containers模块
1、MODULE(CLASS : torch.nn.Module)
import torch.nn as nn
import torch.nn.functional as F
class 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 + 1
return output
# 创建神经网络
lemon = Lemon()
x = torch.tensor(1.0)
output = lemon(x)
print(output)
三、Convolution Layers
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