Erythrocyte commited on
Commit
509157b
1 Parent(s): ae4a9fc

Upload upsampling.py

Browse files
Files changed (1) hide show
  1. upsampling.py +253 -0
upsampling.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .module import Module
2
+ from .. import functional as F
3
+
4
+ from torch import Tensor
5
+ from typing import Optional
6
+ from ..common_types import _size_2_t, _ratio_2_t, _size_any_t, _ratio_any_t
7
+
8
+
9
+ class Upsample(Module):
10
+ r"""Upsamples a given multi-channel 1D (temporal), 2D (spatial) or 3D (volumetric) data.
11
+
12
+ The input data is assumed to be of the form
13
+ `minibatch x channels x [optional depth] x [optional height] x width`.
14
+ Hence, for spatial inputs, we expect a 4D Tensor and for volumetric inputs, we expect a 5D Tensor.
15
+
16
+ The algorithms available for upsampling are nearest neighbor and linear,
17
+ bilinear, bicubic and trilinear for 3D, 4D and 5D input Tensor,
18
+ respectively.
19
+
20
+ One can either give a :attr:`scale_factor` or the target output :attr:`size` to
21
+ calculate the output size. (You cannot give both, as it is ambiguous)
22
+
23
+ Args:
24
+ size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int], optional):
25
+ output spatial sizes
26
+ scale_factor (float or Tuple[float] or Tuple[float, float] or Tuple[float, float, float], optional):
27
+ multiplier for spatial size. Has to match input size if it is a tuple.
28
+ mode (str, optional): the upsampling algorithm: one of ``'nearest'``,
29
+ ``'linear'``, ``'bilinear'``, ``'bicubic'`` and ``'trilinear'``.
30
+ Default: ``'nearest'``
31
+ align_corners (bool, optional): if ``True``, the corner pixels of the input
32
+ and output tensors are aligned, and thus preserving the values at
33
+ those pixels. This only has effect when :attr:`mode` is
34
+ ``'linear'``, ``'bilinear'``, ``'bicubic'``, or ``'trilinear'``.
35
+ Default: ``False``
36
+ recompute_scale_factor (bool, optional): recompute the scale_factor for use in the
37
+ interpolation calculation. If `recompute_scale_factor` is ``True``, then
38
+ `scale_factor` must be passed in and `scale_factor` is used to compute the
39
+ output `size`. The computed output `size` will be used to infer new scales for
40
+ the interpolation. Note that when `scale_factor` is floating-point, it may differ
41
+ from the recomputed `scale_factor` due to rounding and precision issues.
42
+ If `recompute_scale_factor` is ``False``, then `size` or `scale_factor` will
43
+ be used directly for interpolation.
44
+
45
+ Shape:
46
+ - Input: :math:`(N, C, W_{in})`, :math:`(N, C, H_{in}, W_{in})` or :math:`(N, C, D_{in}, H_{in}, W_{in})`
47
+ - Output: :math:`(N, C, W_{out})`, :math:`(N, C, H_{out}, W_{out})`
48
+ or :math:`(N, C, D_{out}, H_{out}, W_{out})`, where
49
+
50
+ .. math::
51
+ D_{out} = \left\lfloor D_{in} \times \text{scale\_factor} \right\rfloor
52
+
53
+ .. math::
54
+ H_{out} = \left\lfloor H_{in} \times \text{scale\_factor} \right\rfloor
55
+
56
+ .. math::
57
+ W_{out} = \left\lfloor W_{in} \times \text{scale\_factor} \right\rfloor
58
+
59
+ .. warning::
60
+ With ``align_corners = True``, the linearly interpolating modes
61
+ (`linear`, `bilinear`, `bicubic`, and `trilinear`) don't proportionally
62
+ align the output and input pixels, and thus the output values can depend
63
+ on the input size. This was the default behavior for these modes up to
64
+ version 0.3.1. Since then, the default behavior is
65
+ ``align_corners = False``. See below for concrete examples on how this
66
+ affects the outputs.
67
+
68
+ .. note::
69
+ If you want downsampling/general resizing, you should use :func:`~nn.functional.interpolate`.
70
+
71
+ Examples::
72
+
73
+ >>> input = torch.arange(1, 5, dtype=torch.float32).view(1, 1, 2, 2)
74
+ >>> input
75
+ tensor([[[[ 1., 2.],
76
+ [ 3., 4.]]]])
77
+
78
+ >>> m = nn.Upsample(scale_factor=2, mode='nearest')
79
+ >>> m(input)
80
+ tensor([[[[ 1., 1., 2., 2.],
81
+ [ 1., 1., 2., 2.],
82
+ [ 3., 3., 4., 4.],
83
+ [ 3., 3., 4., 4.]]]])
84
+
85
+ >>> m = nn.Upsample(scale_factor=2, mode='bilinear') # align_corners=False
86
+ >>> m(input)
87
+ tensor([[[[ 1.0000, 1.2500, 1.7500, 2.0000],
88
+ [ 1.5000, 1.7500, 2.2500, 2.5000],
89
+ [ 2.5000, 2.7500, 3.2500, 3.5000],
90
+ [ 3.0000, 3.2500, 3.7500, 4.0000]]]])
91
+
92
+ >>> m = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
93
+ >>> m(input)
94
+ tensor([[[[ 1.0000, 1.3333, 1.6667, 2.0000],
95
+ [ 1.6667, 2.0000, 2.3333, 2.6667],
96
+ [ 2.3333, 2.6667, 3.0000, 3.3333],
97
+ [ 3.0000, 3.3333, 3.6667, 4.0000]]]])
98
+
99
+ >>> # Try scaling the same data in a larger tensor
100
+ >>>
101
+ >>> input_3x3 = torch.zeros(3, 3).view(1, 1, 3, 3)
102
+ >>> input_3x3[:, :, :2, :2].copy_(input)
103
+ tensor([[[[ 1., 2.],
104
+ [ 3., 4.]]]])
105
+ >>> input_3x3
106
+ tensor([[[[ 1., 2., 0.],
107
+ [ 3., 4., 0.],
108
+ [ 0., 0., 0.]]]])
109
+
110
+ >>> m = nn.Upsample(scale_factor=2, mode='bilinear') # align_corners=False
111
+ >>> # Notice that values in top left corner are the same with the small input (except at boundary)
112
+ >>> m(input_3x3)
113
+ tensor([[[[ 1.0000, 1.2500, 1.7500, 1.5000, 0.5000, 0.0000],
114
+ [ 1.5000, 1.7500, 2.2500, 1.8750, 0.6250, 0.0000],
115
+ [ 2.5000, 2.7500, 3.2500, 2.6250, 0.8750, 0.0000],
116
+ [ 2.2500, 2.4375, 2.8125, 2.2500, 0.7500, 0.0000],
117
+ [ 0.7500, 0.8125, 0.9375, 0.7500, 0.2500, 0.0000],
118
+ [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]])
119
+
120
+ >>> m = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True)
121
+ >>> # Notice that values in top left corner are now changed
122
+ >>> m(input_3x3)
123
+ tensor([[[[ 1.0000, 1.4000, 1.8000, 1.6000, 0.8000, 0.0000],
124
+ [ 1.8000, 2.2000, 2.6000, 2.2400, 1.1200, 0.0000],
125
+ [ 2.6000, 3.0000, 3.4000, 2.8800, 1.4400, 0.0000],
126
+ [ 2.4000, 2.7200, 3.0400, 2.5600, 1.2800, 0.0000],
127
+ [ 1.2000, 1.3600, 1.5200, 1.2800, 0.6400, 0.0000],
128
+ [ 0.0000, 0.0000, 0.0000, 0.0000, 0.0000, 0.0000]]]])
129
+ """
130
+ __constants__ = ['size', 'scale_factor', 'mode', 'align_corners', 'name', 'recompute_scale_factor']
131
+ name: str
132
+ size: Optional[_size_any_t]
133
+ scale_factor: Optional[_ratio_any_t]
134
+ mode: str
135
+ align_corners: Optional[bool]
136
+ recompute_scale_factor: Optional[bool]
137
+
138
+ def __init__(self, size: Optional[_size_any_t] = None, scale_factor: Optional[_ratio_any_t] = None,
139
+ mode: str = 'nearest', align_corners: Optional[bool] = None,
140
+ recompute_scale_factor: Optional[bool] = None) -> None:
141
+ super(Upsample, self).__init__()
142
+ self.name = type(self).__name__
143
+ self.size = size
144
+ if isinstance(scale_factor, tuple):
145
+ self.scale_factor = tuple(float(factor) for factor in scale_factor)
146
+ else:
147
+ self.scale_factor = float(scale_factor) if scale_factor else None
148
+ self.mode = mode
149
+ self.align_corners = align_corners
150
+ self.recompute_scale_factor = recompute_scale_factor
151
+
152
+ def forward(self, input: Tensor) -> Tensor:
153
+ return F.interpolate(input, self.size, self.scale_factor, self.mode, self.align_corners)
154
+ #recompute_scale_factor=self.recompute_scale_factor)
155
+
156
+ def extra_repr(self) -> str:
157
+ if self.scale_factor is not None:
158
+ info = 'scale_factor=' + str(self.scale_factor)
159
+ else:
160
+ info = 'size=' + str(self.size)
161
+ info += ', mode=' + self.mode
162
+ return info
163
+
164
+
165
+ class UpsamplingNearest2d(Upsample):
166
+ r"""Applies a 2D nearest neighbor upsampling to an input signal composed of several input
167
+ channels.
168
+
169
+ To specify the scale, it takes either the :attr:`size` or the :attr:`scale_factor`
170
+ as it's constructor argument.
171
+
172
+ When :attr:`size` is given, it is the output size of the image `(h, w)`.
173
+
174
+ Args:
175
+ size (int or Tuple[int, int], optional): output spatial sizes
176
+ scale_factor (float or Tuple[float, float], optional): multiplier for
177
+ spatial size.
178
+
179
+ .. warning::
180
+ This class is deprecated in favor of :func:`~nn.functional.interpolate`.
181
+
182
+ Shape:
183
+ - Input: :math:`(N, C, H_{in}, W_{in})`
184
+ - Output: :math:`(N, C, H_{out}, W_{out})` where
185
+
186
+ .. math::
187
+ H_{out} = \left\lfloor H_{in} \times \text{scale\_factor} \right\rfloor
188
+
189
+ .. math::
190
+ W_{out} = \left\lfloor W_{in} \times \text{scale\_factor} \right\rfloor
191
+
192
+ Examples::
193
+
194
+ >>> input = torch.arange(1, 5, dtype=torch.float32).view(1, 1, 2, 2)
195
+ >>> input
196
+ tensor([[[[ 1., 2.],
197
+ [ 3., 4.]]]])
198
+
199
+ >>> m = nn.UpsamplingNearest2d(scale_factor=2)
200
+ >>> m(input)
201
+ tensor([[[[ 1., 1., 2., 2.],
202
+ [ 1., 1., 2., 2.],
203
+ [ 3., 3., 4., 4.],
204
+ [ 3., 3., 4., 4.]]]])
205
+ """
206
+ def __init__(self, size: Optional[_size_2_t] = None, scale_factor: Optional[_ratio_2_t] = None) -> None:
207
+ super(UpsamplingNearest2d, self).__init__(size, scale_factor, mode='nearest')
208
+
209
+
210
+ class UpsamplingBilinear2d(Upsample):
211
+ r"""Applies a 2D bilinear upsampling to an input signal composed of several input
212
+ channels.
213
+
214
+ To specify the scale, it takes either the :attr:`size` or the :attr:`scale_factor`
215
+ as it's constructor argument.
216
+
217
+ When :attr:`size` is given, it is the output size of the image `(h, w)`.
218
+
219
+ Args:
220
+ size (int or Tuple[int, int], optional): output spatial sizes
221
+ scale_factor (float or Tuple[float, float], optional): multiplier for
222
+ spatial size.
223
+
224
+ .. warning::
225
+ This class is deprecated in favor of :func:`~nn.functional.interpolate`. It is
226
+ equivalent to ``nn.functional.interpolate(..., mode='bilinear', align_corners=True)``.
227
+
228
+ Shape:
229
+ - Input: :math:`(N, C, H_{in}, W_{in})`
230
+ - Output: :math:`(N, C, H_{out}, W_{out})` where
231
+
232
+ .. math::
233
+ H_{out} = \left\lfloor H_{in} \times \text{scale\_factor} \right\rfloor
234
+
235
+ .. math::
236
+ W_{out} = \left\lfloor W_{in} \times \text{scale\_factor} \right\rfloor
237
+
238
+ Examples::
239
+
240
+ >>> input = torch.arange(1, 5, dtype=torch.float32).view(1, 1, 2, 2)
241
+ >>> input
242
+ tensor([[[[ 1., 2.],
243
+ [ 3., 4.]]]])
244
+
245
+ >>> m = nn.UpsamplingBilinear2d(scale_factor=2)
246
+ >>> m(input)
247
+ tensor([[[[ 1.0000, 1.3333, 1.6667, 2.0000],
248
+ [ 1.6667, 2.0000, 2.3333, 2.6667],
249
+ [ 2.3333, 2.6667, 3.0000, 3.3333],
250
+ [ 3.0000, 3.3333, 3.6667, 4.0000]]]])
251
+ """
252
+ def __init__(self, size: Optional[_size_2_t] = None, scale_factor: Optional[_ratio_2_t] = None) -> None:
253
+ super(UpsamplingBilinear2d, self).__init__(size, scale_factor, mode='bilinear', align_corners=True)