(七)神经网络-卷积层

文章详细讲解了如何使用PyTorch中的conv2d函数进行卷积计算,并结合CIFAR10数据集实例展示了如何构建和应用Conv2d层。
摘要由CSDN通过智能技术生成

1.卷积操作

在这里插入图片描述
卷积演示动态图

2.conv2d()函数

import torch
from torch.nn import functional as f

input_tensor = torch.tensor([
    [1, 2, 0, 3, 1],
    [0, 1, 2, 3, 1],
    [1, 2, 1, 0, 0],
    [5, 2, 3, 1, 1],
    [2, 1, 0, 1, 1]
])
kernel = torch.tensor([  # 卷积核
    [1, 2, 1],
    [0, 1, 0],
    [2, 1, 0]
])
# 因为conv2d的输入format是(batch_size,channel,HW)所以需要转换
input_tensor = torch.reshape(input_tensor, (1, 1, 5, 5))
kernel = torch.reshape(kernel, (1, 1, 3, 3))
output1 = f.conv2d(input=input_tensor, weight=kernel, stride=1)
print(output1)
# stride = 1,padding = 0时输出结果为:
# tensor([[[[10, 12, 12],
#           [18, 16, 16],
#           [13,  9,  3]]]])
output2 = f.conv2d(input=input_tensor, weight=kernel, stride=2)
print(output2)
# stride = 2,padding = 0时输出结果为:
# tensor([[[[10, 12],
#           [13,  3]]]])
output3 = f.conv2d(input=input_tensor, weight=kernel, stride=1, padding=1)
print(output3)
# stride = 1,padding = 1时输出结果为:
# tensor([[[[ 1,  3,  4, 10,  8],
#           [ 5, 10, 12, 12,  6],
#           [ 7, 18, 16, 16,  8],
#           [11, 13,  9,  3,  4],
#           [14, 13,  9,  7,  4]]]])

3.Convolution Layers

3.1 torch.nn.Conv2d类介绍

在这里插入图片描述

3.2 参数介绍

在这里插入图片描述

3.3代码实战

from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from torch import nn
from torch.utils.tensorboard import SummaryWriter

test_dataset = datasets.CIFAR10(root="datasets", train=False, transform=transforms.ToTensor(), download=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=64, shuffle=True, drop_last=False)


class My_module(nn.Module):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.conv2d = nn.Conv2d(in_channels=3, out_channels=3, kernel_size=3, stride=1, padding=0)

    def forward(self, x):
        output = self.conv2d(x)
        return output


my_module = My_module()
print(my_module)
writer = SummaryWriter("conv2d")
step = 0
for data in test_loader:
    imgs, labels = data
    imgs_conv2d = my_module(imgs)
    writer.add_images(tag="Before_Conv2d", img_tensor=imgs, global_step=step)
    writer.add_images(tag="After_Conv2d", img_tensor=imgs_conv2d, global_step=step)
    step += 1

writer.close()

在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值