神经网络—卷积层

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会自动计算这个维度的大小,使得新的张量包含与原始张量相同数量的元素。
相关推荐
怪侠_岭南一只猿4 分钟前
爬虫阶段三实战练习题二:使用 Selenium 模拟爬取拉勾网职位表
css·爬虫·python·selenium·html
前端付豪13 分钟前
自动学习建议解决薄弱知识点
前端·python·openai
deephub15 分钟前
LangGraph vs Semantic Kernel:状态图与内核插件的两条技术路线对比
人工智能·python·深度学习·大语言模型·agent
机器学习之心16 分钟前
RF-RFE-BP基于随机森林递归特征消除(RF-RFE)与BP神经网络回归预测,MATLAB代码
神经网络·随机森林·回归·rf-rfe-bp
与虾牵手17 分钟前
多轮对话 API 怎么实现?从原理到代码,踩完坑我总结了这套方案
python·aigc·ai编程
geovindu22 分钟前
python: Simple Factory Pattern
开发语言·python·设计模式·简单工厂模式
weixin1997010801632 分钟前
开山网商品详情页前端性能优化实战
java·前端·python
前端付豪39 分钟前
实现学习报告统计面板
前端·python·llm
EQUINOX140 分钟前
现代卷积神经网络
人工智能·神经网络·cnn
AC赳赳老秦42 分钟前
国产化AI运维新趋势:DeepSeek赋能国产算力部署的高效故障排查
大数据·人工智能·python·django·去中心化·ai-native·deepseek