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)
Parameters:
in_channels (int) – Number of channels in the input image 输入图像的通道数,彩色图像通道数 3
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'
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
演示链接:https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
代码实战:
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
# train=False为下载测试数据集还是训练数据集。此时为下载测试数据集
dataset = torchvision.datasets.CIFAR10("../data", train=False, transform=torchvision.transforms.ToTensor(),
download=True)
dataloader = DataLoader(dataset, batch_size=4)
class Peipei(nn.Module):
def __init__(self):
super(Peipei, self).__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
peipei = Peipei()
writer = SummaryWriter("logs")
step = 0
for data in dataloader:
imgs, targets = data
# print(imgs.shape)
# 完成卷积操作并输出
output = peipei(imgs)
# print(output.shape)
# torch.Size([4, 3, 32, 32])
writer.add_images("input", imgs, step)
# torch.Size([4, 6, 30, 30]) 6个通道无法显示
output = torch.reshape(output, (-1, 3, 30, 30))
writer.add_images("output", output, step)
step = step + 1
writer.close()
输出: