神经网络—卷积层

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会自动计算这个维度的大小,使得新的张量包含与原始张量相同数量的元素。
相关推荐
旧故新长15 分钟前
支持Function Call的本地ollama模型对比评测-》开发代理agent
人工智能·深度学习·机器学习
明月与玄武23 分钟前
Python编程的真谛:超越语法,理解编程本质
python·编程语言
CodeCraft Studio25 分钟前
Excel处理控件Aspose.Cells教程:使用 Python 在 Excel 中进行数据验
开发语言·python·excel
微学AI27 分钟前
融合注意力机制和BiGRU的电力领域发电量预测项目研究,并给出相关代码
人工智能·深度学习·自然语言处理·注意力机制·bigru
知来者逆38 分钟前
计算机视觉——速度与精度的完美结合的实时目标检测算法RF-DETR详解
图像处理·人工智能·深度学习·算法·目标检测·计算机视觉·rf-detr
拾忆-eleven1 小时前
C语言实战:用Pygame打造高难度水果消消乐游戏
c语言·python·pygame
旦莫1 小时前
Python 教程:我们可以给 Python 文件起中文名吗?
开发语言·python
豌豆花下猫2 小时前
Python 潮流周刊#99:如何在生产环境中运行 Python?(摘要)
后端·python·ai
小杨4042 小时前
python入门系列二十(peewee)
人工智能·python·pycharm
弧襪2 小时前
FlaskRestfulAPI接口的初步认识
python·flaskrestfulapi