PyTorch快速入门教程【小土堆】-神经网络-卷积层

1.nn.Conv2d

参数:

CLASS

torch.nn.Conv2d(in_channelsout_channelskernel_sizestride=1padding=0dilation=1groups=1bias=Truepadding_mode='zeros'device=Nonedtype=None)[SOURCE]

  • in_channels (int) – Number of channels in the input image 输入图像通道数

  • out_channels (int) – Number of channels produced by the convolution 输出图像通道数

  • kernel_size (int or tuple) – Size of the convolving kernel 卷积核大小

  • stride (int or tupleoptional) – Stride of the convolution. Default: 1 步长

  • padding (inttuple or stroptional) – Padding added to all four sides of the input. Default: 0 

  • padding_mode (stringoptional) – 'zeros''reflect''replicate' or 'circular'. Default: 'zeros' padding填充已什么样的方式填充

  • dilation (int or tupleoptional) – Spacing between kernel elements. Default: 1 

  • groups (intoptional) – Number of blocked connections from input channels to output channels. Default: 1

  • bias (booloptional) – If True, adds a learnable bias to the output. Default: True 偏置

 

 公式:

 

 N是batch_size,Cin输入通道数,Hin 输入的高,Win 输入的宽

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("dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True)
dataloader=DataLoader(dataset,batch_size=64)

#搭建简单的神经网络
class Lh(nn.Module):
    def __init__(self) -> None:
        super().__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

lh=Lh() #实例化
writer=SummaryWriter("pp")
step=0
for data in dataloader:
    imgs,targets=data
    output=lh(imgs)
    print(imgs.shape)
    print(output.shape)
    #torch.Size([64, 3, 32, 32]) 输入大小 batch_size=64 in_channel=3,32*32
    writer.add_images("input",imgs,step)
    #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=step+1

writer.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值