1.创建神经网络实例
import torch import torchvision from torch import nn from torch.nn import Conv2d from torch.utils.data import DataLoader dataset=torchvision.datasets.CIFAR10("../dataset_cov2d",train=False,transform=torchvision.transforms.ToTensor(), download=True) dataloader=DataLoader(dataset,batch_size=64) class Xuexu(nn.Module): def __init__(self): super(Xuexu, self).__init__() self.conv1=Conv2d(in_channels=3,out_channels=6,kernel_size=3,stride=1,padding=0) def forward(self,x): self.conv1(x) return x xuexu=Xuexu() print(xuexu)
2.观察输出
输出图像的形状信息,以便检查输入和输出的张量形状是否符合预期。在深度学习中,了解输入和输出的形状对于调试和确保网络结构正确连接非常重要
import torch import torchvision from torch import nn from torch.nn import Conv2d from torch.utils.data import DataLoader # 加载 CIFAR-10 数据集 from torch.utils.tensorboard import SummaryWriter dataset=torchvision.datasets.CIFAR10("../dataset_cov2d",train=False,transform=torchvision.transforms.ToTensor(), download=True) dataloader=DataLoader(dataset,batch_size=64)# 创建数据加载器 # 定义神经网络模型 class Xuexu(nn.Module): def __init__(self): super(Xuexu, 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 xuexu=Xuexu() # writer=SummaryWriter("./logs") step=0 for data in dataloader: imgs,target=data output=xuexu(imgs) print(f"imgs:{imgs.shape}") print(f"output:{output.shape}") # writer.add_images("input",imgs,step) # writer.add_images("output",output,step) # step+=1
3.修改输出
import torch import torchvision from torch import nn from torch.nn import Conv2d from torch.utils.data import DataLoader # 加载 CIFAR-10 数据集 from torch.utils.tensorboard import SummaryWriter dataset=torchvision.datasets.CIFAR10("../dataset_cov2d",train=False,transform=torchvision.transforms.ToTensor(), download=True) dataloader=DataLoader(dataset,batch_size=64)# 创建数据加载器 # 定义神经网络模型 class Xuexu(nn.Module): def __init__(self): super(Xuexu, 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)# 调用卷积层,并将输出赋给 x return x xuexu=Xuexu() writer=SummaryWriter("./logs") step=0 for data in dataloader: imgs,target=data output=xuexu(imgs) # print(f"imgs:{imgs.shape}") # print(f"output:{output.shape}") # imgs:torch.Size([64, 3, 32, 32]) writer.add_images("input",imgs,step) # output: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+=1
终端运行
tensorboard --logdir="logs"
点击蓝色链接进入tensorboard网页
可以看到图片经过卷积之后得到的输出
参考
【PyTorch深度学习快速入门教程(绝对通俗易懂!)【小土堆】】 https://www.bilibili.com/video/BV1hE411t7RN/?p=18&share_source=copy_web&vd_source=be33b1553b08cc7b94afdd6c8a50dc5a