卷积神经网络模型之SPPNet模型实现

本文介绍了一种名为Spatial Pyramid Pooling的空间金字塔池化方法,并提供了一个使用PyTorch实现的示例。该方法允许输入图像的大小可以变化,通过不同层级的池化操作,将不同尺度的特征图转换为固定长度的向量。

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

from torch import nn
import math
import torch

"""
    Args:
        out_side (tuple): Length of side in the pooling results of each pyramid layer. 
    
    Inputs:
        - `input`: the input Tensor to invert ([batch, channel, width, height])
    """
class SpatialPyramidPool2D(nn.Module):
    def __init__(self,out_side):
        super(SpatialPyramidPool2D,self).__init__()
        self.out_side=out_side
        
    def forward(self,x):
        out=None
        for n in self.out_side:
            w_r,h_r=map(lambda s:math.ceil(s/n),x.size()[2:])
            s_w,s_h=map(lambda s:math.floor(s/n),x.size()[2:]) 
            max_pool=nn.MaxPool2d(kernel_size=(w_r,h_r),stride=(s_w,s_h))
            y=max_pool(x)
            if out is None:
                out=y.view(y.size()[0],-1)
            else:
                out=torch.cat((out,y.view(y.size()[0],-1)),1)
        return out

seq=nn.Sequential(
            nn.Conv2d(
                in_channels=1,
                out_channels=16,
                kernel_size=5,
                stride=1,
                padding=2,
            ),
            nn.ReLU(),
            SpatialPyramidPool2D(out_side=(1,2,4))
        )

x=torch.randn(1,1,10,20)
y=seq(x)

print(y.shape)

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值