赞
踩
本文中所学习的Pytorch官方文档地址link
out_channels = 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("../data", train=False, transform=torchvision.transforms.ToTensor(), download=True) # ".."表示更上一层的父目录 dataloader = DataLoader(dataset, batch_size=64) class Avlon(nn.Module): def __init__(self): super().__init__() self.conv1 = Conv2d(3, out_channels=6, kernel_size=3, stride=1, padding=0) # 彩色图片故in_channels=3 def forward(self, x): x = self.conv1(x) return x avlon = Avlon() print(avlon) writer = SummaryWriter("../logs") step = 0 for data in dataloader: imgs, target = data output = avlon(imgs) print(imgs.shape) print(output.shape) # torch.Size([64, 3, 32, 32]) writer.add_images("input", imgs, step) # torch.Size([64, 6, 30, 30]) writer.add_images("output", output, step) step = step + 1
运行后
可见输出图片的通道变成6,同时经过卷积后图片变小。
报错的原因:6通道数的图片无法显示,直接使用tensorboard可视化会报错。修改35行以下代码
# torch.Size([64, 6, 30, 30]) --> [xxx, 3, 30, 30]
output = torch.reshape(output, (-1, 3, 30, 30)) # 参数未知时填“-1”,自动计算
writer.add_images("output", output, step)
step = step + 1
# 将多余的像素放入batch_size中,即可正常运行
# Terminal中若未启动pytorch环境,可输入:conda activate pytorch
结果为
帮助文档中需要注意的重要公式
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。