nn.Conv2d 常用
nn.Conv几d就是几维卷积
图片里第一个小汽车的图片,224*224(尺寸),3通道
self.conv1 = Conv2d(in_channels=3,out_channels=64,kernel_size=3,stride=1,padding=0)
in_channels=3,out_channels=64
改成64通道
N表示bacthsize,上面那个公式可以用来推导,如果哪个论文不写全的话
代码如下
import torch.nn.functional as F
import torch
import torchvision
from torch.utils.data import DataLoader
from torch import nn
from torch.nn import Conv2d
# x= torch.nn.Conv2d(参数如下)
# Args:
# in_channels (int):输入图像的通道数 】Number of channels in the input image
# 输入图像只有一层(一个平面),in_channels=1
# out_channels (int):输出图像的通道数】 Number of channels produced by the convolution
# kernel_size (int or tuple):卷积核大小单个数字(3表示3*3)或元组(4*2)】 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 (str, 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``
dataset = torchvision.datasets.CIFAR10("/Users/bbing517/Downloads/数据集/hymenoptera_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)
#在网络中建立了一个卷积层conv1,
def forward(self,x):
y = self.conv1(x) #把x放到卷积层里,经过处理得到的结果存入y
return y
tudui = Tudui()
print(tudui)
writer = SummaryWriter("../logs")
step=0
for data in dataloader:
imgs, targets = data
output = tudui(imgs)
print(imgs.shape) #torch.Size([64, 3, 32, 32])
print(output.shape)#torch.Size([64, 6, 30, 30])
# 两个print 看一下,imgs是原始的;output是经过卷积层的
writer.add_images("input", imgs, step)
#因为torch.Size([64, 6, 30, 30]),tensorboard不能显示,要给他变成torch.Size([?, 3, 30, 30])
output = torch.reshape(output,(-1,3,30,30))
#为什么第一个数写-1?不知道写多少就这么写,他会自己调整的
writer.add_images("output", output, step)
step = step+1