Pytorch(笔记3)--MaxPool2d&AdaptiveAvgPool2d

本文主要介绍Pytorch中常见的Pooling操作。此前已阐述Conv2d计算原理,Pytorch用Pooling操作实现采样,常见的有Max_pool、Avg_pool,还介绍了AdaptiveAvgPool2d和AdaptiveMaxPool2d,它们可实现自适应size运算,还能与前两者转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

   在上一节中我们详细的阐述了Conv2d的计算原理,今天我们来讲述下Pytorch中其他比较常见的操作!

   在lenet5的时候,受限于计算能力和存储能力,通常采用downsample来降维

        

在pytorch中使用Pooling操作来实现采样,常见的pool操作包含Max_pool,Avg_pool等

Max_pool

x = t.rand(1,3,7,7)
out = nn.MaxPool2d(kernel_size=2,stride=2)
out.forward(x).shape
torch.Size([1, 3, 3, 3])

启动kernel代表的是观察角度,如下图kernel就是2*2,stride和Conv操作中一样代表每次移动的步长。

下图操作,在每次观察区域内取最大值作为采样数据进行降维操作,这样做的优点是可以使显性特征更明显,降维操作并没有更改输出和输出的channel_num 

Avg_pool

对于Avg_pool来说,参数和Max_pool是完全相同的,主要区别就是在kernel中取的是平均值操作。

AdaptiveAvgPool2d&AdaptiveMaxPool2d

和之前的运算方法不同,torch.nn提供了自适应size的函数样例如下:

可以看出,输出结果的size是按照我们给丁的结果进行运算的,一个参数代表H和W相同,也可以自定义(H,W),底层是对F.adaptive_avg_pool2d的封装,一般在类中的是大写小写的是函数,在Function中。

class AdaptiveAvgPool2d(_AdaptiveAvgPoolNd):
    r"""Applies a 2D adaptive average pooling over an input signal composed of several input planes.

    The output is of size H x W, for any input size.
    The number of output features is equal to the number of input planes.

    Args:
        output_size: the target output size of the image of the form H x W.
                     Can be a tuple (H, W) or a single H for a square image H x H.
                     H and W can be either a ``int``, or ``None`` which means the size will
                     be the same as that of the input.

    Examples:
        >>> # target output size of 5x7
        >>> m = nn.AdaptiveAvgPool2d((5,7))
        >>> input = torch.randn(1, 64, 8, 9)
        >>> output = m(input)
        >>> # target output size of 7x7 (square)
        >>> m = nn.AdaptiveAvgPool2d(7)
        >>> input = torch.randn(1, 64, 10, 9)
        >>> output = m(input)
        >>> # target output size of 10x7
        >>> m = nn.AdaptiveMaxPool2d((None, 7))
        >>> input = torch.randn(1, 64, 10, 9)
        >>> output = m(input)

    """

    @weak_script_method
    def forward(self, input):
        return F.adaptive_avg_pool2d(input, self.output_size)

我们可以根据下面的内容推导出我们不知道的参数,从而实现AdaptiveAvgPool2d&AdaptiveMaxPool2与前两个函数的转换,C++源码

stride = floor ( (input_size / (output_size) )

kernel_size = input_size − (output_size−1) * stride

padding = 0

坚持一件事或许很难,但坚持下来一定很酷!^_^

### PyTorch 学习笔记与技术总结 PyTorch 是一个功能强大的开源机器学习框架,广泛应用于深度学习领域。以下是关于 PyTorch 的一些核心知识点和技术总结: #### 1. 环境配置 在开始使用 PyTorch 前,需完成必要的环境配置工作。这通常包括安装 Python、设置 GPU 支持以及导入所需的依赖项[^2]。 #### 2. 数据加载与处理 PyTorch 提供了灵活的数据加载方式,主要包括 `torch.utils.data.Dataset` 和 `torch.utils.data.DataLoader` 这两个库函数。通过这些工具可以高效地管理数据的组织形式和批量加载过程[^2]。 #### 3. 可视化工具 为了更好地监控模型训练的过程,PyTorch 集成了 TensorBoard 工具。该工具能够实时绘制损失曲线、显示权重分布以及其他重要指标,从而帮助开发者调整超参数并优化性能[^2]。 #### 4. 构建神经网络 构建神经网络是 PyTorch 中的核心部分之一。以下是一些常用的模块及其作用: - **基本骨架**: 使用 `nn.Module` 类定义自定义网络结构。 - **卷积操作**: 利用 `torch.nn.functional` 实现动态卷积计算。 - **卷积层**: 调用 `torch.nn.Conv2d` 创建二维卷积层。 - **池化层**: 应用 `torch.nn.MaxPool2d` 执行最大池化操作。 - **填充层**: 设置边界扩展策略以控制特征图大小变化。 - **非线性激活函数**: 如 ReLU (`torch.nn.ReLU`) 或 Sigmoid (`torch.nn.Sigmoid`)- **全连接层**: 即线性变换层,可通过 `torch.nn.Linear` 来实现。 - **序列容器**: 将多个层按顺序组合起来形成完整的网络架构,推荐使用 `torch.nn.Sequential`。 #### 5. 设备分配原则 对于大规模计算任务而言,合理安排 CPU 和 GPU 上的任务至关重要。一般情况下会将数据读取及预处理阶段留在 CPU 上执行;而涉及大量矩阵乘法等密集型运算则交由 GPU 处理,以此达到最大化硬件效能的目的[^3]。 #### 6. 模型评估与保存 经过充分训练后的模型可以通过测试集来验证其泛化能力,并最终导出为可部署的形式以便实际应用中调用。常用方法有 `.eval()` 方法切换至推理模式以及 `torch.save(model.state_dict(), PATH)` 函数持久化模型状态字典[^2]。 ```python import torch from torch import nn class SimpleNet(nn.Module): def __init__(self): super(SimpleNet, self).__init__() self.fc = nn.Linear(10, 1) def forward(self, x): return torch.sigmoid(self.fc(x)) model = SimpleNet() print(model) ``` 以上代码片段展示了一个简单的前馈神经网络实例,其中包含了输入维度为 10 输出维度为 1 的单隐藏层感知机模型定义[^2]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值