B站小土堆Pytorch视频学习——卷积层的基本操作(2023.06.14)

一.卷积操作

在这里插入图片描述

此为functional里的conv2d


import torch
import torch.nn.functional as F
input=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]])
#pytorch提供的尺寸变换
#通道为1,batchsize为1
input=torch.reshape(input,(1,1,5,5))
kernel=torch.reshape(kernel,(1,1,3,3))
print(input.shape)
print(kernel.shape)
output=F.conv2d(input,kernel,stride=1)
print(output)
output2=F.conv2d(input,kernel,stride=2)
print(output2)
output3=F.conv2d(input,kernel,stride=1,padding=1)
print(output3)

此为nn里的Conv2d

二.卷积意义

在这里插入图片描述
将图片卷积


```python
import torch
import torchvision
import torch.nn as nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

#数据处理
dataset=torchvision.datasets.CIFAR10("./data",train=False,transform=torchvision.transforms.ToTensor(),download=True)
data_loader=DataLoader(dataset=dataset,batch_size=64)
#构建神经网络,此神经网络名称叫Tudui,输入的通道数为3,滤波器个数为6个,滤波器大小3x3,步数为1,不扩展,forward中进行卷积
class Tudui(nn.Module):
    def __init__(self):
        super(Tudui,self).__init__()
        self.conv1=nn.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)
writer=SummaryWriter("logs")
i=0
for data in data_loader:
    imgs,targets=data
    #调用forwar进行卷积
    output=tudui(imgs)
    print(imgs.shape)
    print(output.shape)
    #因为无法add6通道,只能平铺变成3通道
    output=torch.reshape(output, (-1, 3, 30, 30))
    writer.add_images("before",imgs,i)
    writer.add_images("after",output,i)
    i+=1
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值