神经网络—卷积层

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会自动计算这个维度的大小,使得新的张量包含与原始张量相同数量的元素。
相关推荐
蹦蹦跳跳真可爱5897 分钟前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
nananaij12 分钟前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
雷羿 LexChien17 分钟前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt
敲键盘的小夜猫1 小时前
LLM复杂记忆存储-多会话隔离案例实战
人工智能·python·langchain
高压锅_12201 小时前
Django Channels WebSocket实时通信实战:从聊天功能到消息推送
python·websocket·django
白杆杆红伞伞2 小时前
T01_神经网络
人工智能·深度学习·神经网络
槑槑紫2 小时前
深度学习pytorch整体流程
人工智能·pytorch·深度学习
盼小辉丶3 小时前
TensorFlow深度学习实战——去噪自编码器详解与实现
人工智能·深度学习·tensorflow
胖达不服输3 小时前
「日拱一码」020 机器学习——数据处理
人工智能·python·机器学习·数据处理
吴佳浩3 小时前
Python入门指南-番外-LLM-Fingerprint(大语言模型指纹):从技术视角看AI开源生态的边界与挑战
python·llm·mcp