Safemotion Lib
Loading...
Searching...
No Matches
pooling.py
Go to the documentation of this file.
1# encoding: utf-8
2"""
3@author: l1aoxingyu
4@contact: sherlockliao01@gmail.com
5"""
6
7import torch
8import torch.nn.functional as F
9from torch import nn
10
11__all__ = ["Flatten",
12 "GeneralizedMeanPooling",
13 "GeneralizedMeanPoolingP",
14 "FastGlobalAvgPool2d",
15 "AdaptiveAvgMaxPool2d",
16 "ClipGlobalAvgPool2d",
17 ]
18
19
20class Flatten(nn.Module):
21 def forward(self, input):
22 return input.view(input.size(0), -1)
23
24
25class GeneralizedMeanPooling(nn.Module):
26 r"""Applies a 2D power-average adaptive pooling over an input signal composed of several input planes.
27 The function computed is: :math:`f(X) = pow(sum(pow(X, p)), 1/p)`
28 - At p = infinity, one gets Max Pooling
29 - At p = 1, one gets Average Pooling
30 The output is of size H x W, for any input size.
31 The number of output features is equal to the number of input planes.
32 Args:
33 output_size: the target output size of the image of the form H x W.
34 Can be a tuple (H, W) or a single H for a square image H x H
35 H and W can be either a ``int``, or ``None`` which means the size will
36 be the same as that of the input.
37 """
38
39 def __init__(self, norm=3, output_size=1, eps=1e-6):
40 super(GeneralizedMeanPooling, self).__init__()
41 assert norm > 0
42 self.p = float(norm)
43 self.output_size = output_size
44 self.eps = eps
45
46 def forward(self, x):
47 x = x.clamp(min=self.eps).pow(self.p)
48 return torch.nn.functional.adaptive_avg_pool2d(x, self.output_size).pow(1. / self.p)
49
50 def __repr__(self):
51 return self.__class__.__name__ + '(' \
52 + str(self.p) + ', ' \
53 + 'output_size=' + str(self.output_size) + ')'
54
55
57 """ Same, but norm is trainable
58 """
59
60 def __init__(self, norm=3, output_size=1, eps=1e-6):
61 super(GeneralizedMeanPoolingP, self).__init__(norm, output_size, eps)
62 self.pp = nn.Parameter(torch.ones(1) * norm)
63
64
65class AdaptiveAvgMaxPool2d(nn.Module):
66 def __init__(self):
67 super(AdaptiveAvgMaxPool2d, self).__init__()
69 self.gmp = nn.AdaptiveMaxPool2d(1)
70
71 def forward(self, x):
72 avg_feat = self.gap(x)
73 max_feat = self.gmp(x)
74 feat = avg_feat + max_feat
75 return feat
76
77
78class FastGlobalAvgPool2d(nn.Module):
79 def __init__(self, flatten=False):
80 super(FastGlobalAvgPool2d, self).__init__()
81 self.flatten = flatten
82
83 def forward(self, x):
84 if self.flatten:
85 in_size = x.size()
86 return x.view((in_size[0], in_size[1], -1)).mean(dim=2)
87 else:
88 return x.view(x.size(0), x.size(1), -1).mean(-1).view(x.size(0), x.size(1), 1, 1)
89
90
91class ClipGlobalAvgPool2d(nn.Module):
92 def __init__(self):
93 super().__init__()
95
96 def forward(self, x):
97 x = self.avgpool(x)
98 x = torch.clamp(x, min=0., max=1.)
99 return x
__init__(self, norm=3, output_size=1, eps=1e-6)
Definition pooling.py:39
__init__(self, norm=3, output_size=1, eps=1e-6)
Definition pooling.py:60