1.nn.Conv2d
参数:
CLASS
torch.nn.
Conv2d
(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=True, padding_mode='zeros', device=None, dtype=None)[SOURCE]
-
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 卷积核大小
-
stride (int or tuple, optional) – Stride of the convolution. Default: 1 步长
-
padding (int, tuple or str, optional) – Padding added to all four sides of the input. Default: 0
-
padding_mode (string, optional) –
'zeros'
,'reflect'
,'replicate'
or'circular'
. Default:'zeros' padding填充已什么样的方式填充
-
dilation (int or tuple, optional) – Spacing between kernel elements. Default: 1
-
groups (int, optional) – Number of blocked connections from input channels to output channels. Default: 1
-
bias (bool, optional) – If
True
, adds a learnable bias to the output. Default:True 偏置
公式:
N是batch_size,Cin输入通道数,Hin 输入的高,Win 输入的宽
2.使用
import torch
import torchvision
from torch import nn
from torch.nn import Conv2d
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
#下载数据集
dataset=torchvision.datasets.CIFAR10("dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True)
dataloader=DataLoader(dataset,batch_size=64)
#搭建简单的神经网络
class Lh(nn.Module):
def __init__(self) -> None:
super().__init__()
#定义卷积层
self.conv1=Conv2d(in_channels=3,out_channels=6,kernel_size=3,stride=1,padding=0)
def forward(self,x):
x=self.conv1(x)
return x
lh=Lh() #实例化
writer=SummaryWriter("pp")
step=0
for data in dataloader:
imgs,targets=data
output=lh(imgs)
print(imgs.shape)
print(output.shape)
#torch.Size([64, 3, 32, 32]) 输入大小 batch_size=64 in_channel=3,32*32
writer.add_images("input",imgs,step)
#torch.Size([64, 6, 30, 30]) 输出大小
#将形状变为[xxx,3,30,30]
output=torch.reshape(output,(-1,3,30,30))
writer.add_images("output",output,step)
step=step+1
writer.close()