-
Notifications
You must be signed in to change notification settings - Fork 0
/
Spp.py
43 lines (35 loc) · 1.5 KB
/
Spp.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import math
import torch
import torch.nn.functional as F
class SpatialPyramidPooling2d(torch.nn.Module):
def __init__(self, num_levels=3, pool_type='ave_pool'):
super(SpatialPyramidPooling2d, self).__init__()
self.num_levels = num_levels
self.pool_type = pool_type
def forward(self, x):
# num:样本数量 c:通道数 h:高 w:宽
# num: the number of samples
# c: the number of channels
# h: height
# w: width
num, c, h, w = x.size()
for i in range(self.num_levels):
level = i+1
'''
The equation is explained on the following site:
http://www.cnblogs.com/marsggbo/p/8572846.html#autoid-0-0-0
'''
kernel_size = (math.ceil(h / level), math.ceil(w / level))
stride = (math.ceil(h / level), math.ceil(w / level))
pooling = (math.floor((kernel_size[0]*level-h+1)/2), math.floor((kernel_size[1]*level-w+1)/2))
# 选择池化方式
if self.pool_type == 'max_pool':
tensor = F.max_pool2d(x, kernel_size=kernel_size, stride=stride, padding=pooling).view(num, -1)
else:
tensor = F.avg_pool2d(x, kernel_size=kernel_size, stride=stride, padding=pooling).view(num, -1)
# 展开、拼接
if i == 0:
x_flatten = tensor.view(num, -1)
else:
x_flatten = torch.cat((x_flatten, tensor.view(num, -1)), 1)
return x_flatten