从零实现卷积层
一.数据下载和自定义卷积层的实现
import torch
import torchvision
from torch import nn
from torch.nn import Conv2d
from torch.utils.data import DataLoader
dataset =torchvision.datasets.CIFAR10("../data",train=False,transform=torchvision.transforms.ToTensor(),download=True) #不需要训练数据集 train=False
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)
def forward(self,x):
x=self.conv1(x)
return x
tudui = Tudui()
print(tudui)
二. 输出 卷积后tensor的形状
for data in dataloader:
imgs,targets=data
output =tudui(imgs)
print(output.shape)
三.对比输入与输出的形状
for data in dataloader:
imgs,targets=data
output =tudui(imgs)
print(imgs.shape)
print(output.shape)
彩色图片是3channel的 通过卷积之后变为了6个channel
四.引入tensorboard
错误示范:
# 错误示范 错误原因:彩色图片是3个channel 6个channel不知道如何显示 reshape
writer=SummaryWriter("../log1")
step=0
for data in dataloader:
imgs,targets=data
output =tudui(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
正确示范:
# 正确示范
writer=SummaryWriter("../log1")
step=0
for data in dataloader:
imgs,targets=data
output =tudui(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])
output=torch.reshape(output,(-1,3,30,30)) # 当你不知道第一个数的值的时候 -1是根据后面的自动调整
writer.add_images("output",output,step)
step=step+1