卷积层
介绍¶
卷积层对应前面的卷积操作,直接作为神经网络的一层。
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("../data", train=False, transform=torchvision.transforms.ToTensor(),
download=True)
dataloader = DataLoader(dataset, batch_size=64)
class Tudui(nn.Module):
def __init__(self):
super(Tudui, self).__init__()
self.conv1 = Conv2d(in_channels=3, out_channels=6, kernel_size=3, stride=1, padding=0) # 输入通道(这里RGB是3)、输出通道(卷积核数量)
def forward(self, x):
x = self.conv1(x) # x 已经放到了卷积层 conv1当中了
return x
tudui = Tudui() # 初始化网络
print(tudui)
# 下面把每一张图像都进行卷积
writer = SummaryWriter("logs")
step = 0
for data in dataloader:
imgs, targets = data
output = tudui(imgs)
print("imgs.shape:", imgs.shape)
print("output.shape:", output.shape)
# torch.Size([64, 3, 32, 32])
writer.add_images("input", imgs, step)
# torch.Size([64, 6, 30, 30]) 由于6个channel的图像,是无法显示的
# torch.Size([xxx, 3, 30, 30])
output = torch.reshape(output, (-1, 3, 30, 30)) # 强行转,无依据,正常可以汇聚层、奇异值分解等。
writer.add_images("output", output, step)
step += 1
writer.close()
参数说明:
in_channels 输入通道数
out_channels 输出通道数,对应卷积核数量
kernel_size 卷积核大小,这里卷积核大小是n*n的
stride 步长
padding 填充
后面没啥可介绍的,注意下细节就行。