神经网络—卷积层

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会自动计算这个维度的大小,使得新的张量包含与原始张量相同数量的元素。
相关推荐
量化君也10 分钟前
快速入门量化交易都要学些什么?
大数据·人工智能·python·算法·金融
吴卫斌10 分钟前
行业ETF轮动策略实战(二):精选候选池——打造你的赛道武器库
大数据·python·股票·量化交易
Tbisnic15 分钟前
AI大模型学习 第十天:让程序“指挥”大模型 —— 从对话到工具调用
人工智能·python·ai·大模型·react·cot·提示词工程
伊布拉西莫18 分钟前
Flask 请求生命周期
后端·python·flask
站大爷IP35 分钟前
那天,我的Python函数死活改不了全局变量
python
右耳朵猫AI36 分钟前
Python周刊2026W22 | Django 6.1 Alpha 1发布、Nuitka 4.1发布、PEP 831终稿、PEP 808已接受
开发语言·python·django
Wonderful U42 分钟前
Python+Django实战|美食菜谱分享与食材采购一体化系统:食谱发布收藏、图文教程、食材商城、购物车、订单管理、美食点评、智能食谱推荐
python·django·美食
JobDocLS42 分钟前
Jetson Orin的用法
深度学习
秦jh_1 小时前
【LangChain核心组件】少样本提示(示例选择器)
人工智能·python·langchain