神经网络—卷积层

1.讲解 Conv2d

  • out_channels 参数为2时,会生成两个卷积核,分别与输入进行卷积。得到的两个输出为输出

新生成的卷积核和原来的卷积核不一定相同

  • 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 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

2.代码实现

python 复制代码
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)
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):
        self.conv1(x)
        return  x


tudui=Tudui()
print(tudui)
python 复制代码
for data in dataloader:
    imgs,targets=data
    output=tudui(imgs)
    print(output.shape)
python 复制代码
tudui=Tudui()

writer=SummaryWriter("./logs")
step=0

for data in dataloader:
    imgs,targets=data
    output=tudui(imgs)
    # print(output.shape)
    print(imgs.shape)
    print(output.shape)
    #torch.Size([64, 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

注意:torch.Size([64, 3, 32, 32])与torch.Size([64, 6, 30, 30])

  • ①输出通道数从3增加到6,因为使用了6个卷积核。
  • ②宽度和高度的计算公式:
    (输入尺寸 - 卷积核大小 + 2 * 填充) / 步长 + 1
    将假设的值代入公式中:
    宽度:(32 - 3 + 2 * 0) / 1 + 1 = 30
    高度:(32 - 3 + 2 * 0) / 1 + 1 = 30

注意:reshape(output,(-1,3,30,30))

  • -1:这个值是一个占位符,表示新张量的第一个维度的大小应该自动计算,以保持元素总数不变。这意味着PyTorch会自动计算这个维度的大小,使得新的张量包含与原始张量相同数量的元素。
相关推荐
niuniu_6661 小时前
selenium应用测试场景
python·selenium·测试工具·单元测试·测试
满怀10152 小时前
Python扩展知识详解:lambda函数
开发语言·python
蓝博AI4 小时前
基于卷积神经网络的眼疾识别系统,resnet50,efficentnet(pytorch框架,python代码)
pytorch·python·cnn
牧歌悠悠5 小时前
【Python 算法】动态规划
python·算法·动态规划
lisw057 小时前
DeepSeek原生稀疏注意力(Native Sparse Attention, NSA)算法介绍
人工智能·深度学习·算法
Doris Liu.7 小时前
如何检测代码注入(Part 2)
windows·python·安全·网络安全·网络攻击模型
逢生博客7 小时前
阿里 FunASR 开源中文语音识别大模型应用示例(准确率比faster-whisper高)
人工智能·python·语音识别·funasr
噔噔噔噔@7 小时前
软件测试对于整个行业的重要性及必要性
python·单元测试·压力测试
赵谨言8 小时前
基于Python的Django框架的个人博客管理系统
经验分享·python·毕业设计
Guarding and trust8 小时前
python系统之综合案例:用python打造智能诗词生成助手
服务器·数据库·python