r"""Applies Batch Normalization over a 2D or 3D input. .. math:: y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta The mean and standard-deviation are calculated per-dimension over the mini-batches and :math:`\gamma` and :math:`\beta` are learnab
| 215 | |
| 216 | |
| 217 | class BatchNorm1d(_BatchNorm): |
| 218 | r"""Applies Batch Normalization over a 2D or 3D input. |
| 219 | |
| 220 | .. math:: |
| 221 | |
| 222 | y = \frac{x - \mathrm{E}[x]}{\sqrt{\mathrm{Var}[x] + \epsilon}} * \gamma + \beta |
| 223 | |
| 224 | The mean and standard-deviation are calculated per-dimension over |
| 225 | the mini-batches and :math:`\gamma` and :math:`\beta` are learnable parameter vectors |
| 226 | of size `C` (where `C` is the number of features or channels of the input). By default, the |
| 227 | elements of :math:`\gamma` are set to 1 and the elements of :math:`\beta` are set to 0. The |
| 228 | standard-deviation is calculated via the biased estimator, equivalent to `torch.var(input, unbiased=False)`. |
| 229 | |
| 230 | By default, during training this layer keeps running estimates of its |
| 231 | computed mean and variance, which are then used for normalization during |
| 232 | evaluation. The running estimates are kept with a default :attr:`momentum` |
| 233 | of 0.9. |
| 234 | |
| 235 | If :attr:`track_running_stats` is set to ``False``, this layer then does not |
| 236 | keep running estimates, and batch statistics are instead used during |
| 237 | evaluation time as well. |
| 238 | |
| 239 | Because the Batch Normalization is done over the `C` dimension, computing statistics |
| 240 | on `(N, L)` slices, it's common terminology to call this Temporal Batch Normalization. |
| 241 | |
| 242 | .. note:: |
| 243 | |
| 244 | The update formula for ``running_mean`` and ``running_var`` (taking ``running_mean`` as an example) is |
| 245 | |
| 246 | .. math:: |
| 247 | |
| 248 | \textrm{running_mean} = \textrm{momentum} \times \textrm{running_mean} + (1 - \textrm{momentum}) \times \textrm{batch_mean} |
| 249 | |
| 250 | which could be defined differently in other frameworks. Most notably, ``momentum`` of 0.1 in PyTorch |
| 251 | is equivalent to ``mementum`` of 0.9 here. |
| 252 | |
| 253 | Shape: |
| 254 | - Input: :math:`(N, C)` or :math:`(N, C, L)`, where :math:`N` is the batch size, |
| 255 | :math:`C` is the number of features or channels, and :math:`L` is the sequence length |
| 256 | - Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input) |
| 257 | """ |
| 258 | |
| 259 | def _check_input_ndim(self, inp): |
| 260 | if len(inp.shape) not in {2, 3}: |
| 261 | raise ValueError( |
| 262 | "expected 2D or 3D input (got {}D input)".format(len(inp.shape)) |
| 263 | ) |
| 264 | |
| 265 | |
| 266 | class BatchNorm2d(_BatchNorm): |
no outgoing calls