Pytorch中 maxpool的ceil_mode

原文:https://blog.csdn.net/GZHermit/article/details/79351803 


Pytorch里面的maxpool,有一个属性叫ceil_mode,这个属性在api里面的解释是

ceil_mode: when True, will use ceil instead of floor to compute the output shape

也就是说,在计算输出的shape的时候,如果ceil_mode的值为True,那么则用天花板模式,否则用地板模式

???

举两个例子就明白了。

# coding:utf-8
import torch
import torch.nn as nn
from torch.autograd import Variable


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.maxp = nn.MaxPool2d(kernel_size=2, ceil_mode=False)

    def forward(self, x):
        x = self.maxp(x)
        return x

square_size = 6
inputs = torch.randn(1, 1, square_size, square_size)
for i in range(square_size):
    inputs[0][0][i] = i * torch.ones(square_size)
inputs = Variable(inputs)
print(inputs)

net = Net()
outputs = net(inputs)
print(outputs.size())
print(outputs)

Variable containing: 

(0 ,0 ,.,.) = 

0 0 0 0 0 0

1 1 1 1 1 1

2 2 2 2 2 2

3 3 3 3 3 3

4 4 4 4 4 4

5 5 5 5 5 5

[torch.FloatTensor of size 1x1x6x6] 

torch.Size([1, 1, 3, 3])

Variable containing: 

(0 ,0 ,.,.) = 

1 1 1 

3 3 3 

5 5 5 

[torch.FloatTensor of size 1x1x3x3]

在上面的代码中,无论ceil_mode是True or False,结果都是一样 
但是如果设置square_size=5,那么

当ceil_mode=True

Variable containing: 

(0 ,0 ,.,.) = 

0 0 0 0 0 

1 1 1 1 1 

2 2 2 2 2 

3 3 3 3 3 

4 4 4 4 4 

[torch.FloatTensor of size 1x1x5x5] 
torch.Size([1, 1, 3, 3]) 
Variable containing: 

(0 ,0 ,.,.) = 

1 1 1 

3 3 3 

4 4 4 

[torch.FloatTensor of size 1x1x3x3]

当ceil_mode=False

Variable containing: 

(0 ,0 ,.,.) = 

0 0 0 0 0 

1 1 1 1 1 

2 2 2 2 2 

3 3 3 3 3 

4 4 4 4 4 

[torch.FloatTensor of size 1x1x5x5] 

torch.Size([1, 1, 2, 2]) 

Variable containing: 

(0 ,0 ,.,.) = 

1 1 

3 3 

[torch.FloatTensor of size 1x1x2x2]

所以ceil模式就是会把不足square_size的边给保留下来,单独另算,或者也可以理解为在原来的数据上补充了值为-NAN的边。而floor模式则是直接把不足square_size的边给舍弃了

你可能感兴趣的:(Deep,Learning,Pytorch)