std.py 2.21 KB
Newer Older
rusty1s's avatar
rusty1s committed
1
2
3
4
5
6
7
import torch

from torch_scatter import scatter_add
from torch_scatter.utils.gen import gen


def scatter_std(src, index, dim=-1, out=None, dim_size=None, unbiased=True):
rusty1s's avatar
typo  
rusty1s committed
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
44
45
    r"""
    |

    .. image:: https://raw.githubusercontent.com/rusty1s/pytorch_scatter/
            master/docs/source/_figures/std.svg?sanitize=true
        :align: center
        :width: 400px

    |

    Computes the standard-deviation from all values from the :attr:`src` tensor
    into :attr:`out` at the indices specified in the :attr:`index` tensor along
    a given axis :attr:`dim` (`cf.` :meth:`~torch_scatter.scatter_add`).

    For one-dimensional tensors, the operation computes

    .. math::
        \mathrm{out}_i = \sqrt{\frac{\sum_j {\left( x_j - \overline{x}_i
        \right)}^2}{N_i - 1}}

    where :math:`\sum_j` is over :math:`j` such that
    :math:`\mathrm{index}_j = i`. :math:`N_i` and :math:`\overline{x}_i`
    indicate the number of indices referencing :math:`i` and their mean value,
    respectively.

    Args:
        src (Tensor): The source tensor.
        index (LongTensor): The indices of elements to scatter.
        dim (int, optional): The axis along which to index.
            (default: :obj:`-1`)
        out (Tensor, optional): The destination tensor. (default: :obj:`None`)
        dim_size (int, optional): If :attr:`out` is not given, automatically
            create output with size :attr:`dim_size` at dimension :attr:`dim`.
            If :attr:`dim_size` is not given, a minimal sized output tensor is
            returned. (default: :obj:`None`)
        unbiased (bool, optional): If set to :obj:`False`, then the standard-
            deviation will be calculated via the biased estimator.
            (default: :obj:`True`)
rusty1s's avatar
rusty1s committed
46
47

    :rtype: :class:`Tensor`
rusty1s's avatar
typo  
rusty1s committed
48
    """
rusty1s's avatar
rusty1s committed
49
50
51
52
53
54
    src, out, index, dim = gen(src, index, dim, out, dim_size, fill_value=0)

    tmp = scatter_add(src, index, dim, None, dim_size)
    count = scatter_add(torch.ones_like(src), index, dim, None, dim_size)
    mean = tmp / count.clamp(min=1)

rusty1s's avatar
rusty1s committed
55
56
    var = (src - mean.gather(dim, index))
    var = var * var
rusty1s's avatar
rusty1s committed
57
58
    out = scatter_add(var, index, dim, out, dim_size)
    out = out / (count - 1 if unbiased else count).clamp(min=1)
rusty1s's avatar
typo  
rusty1s committed
59
    out = torch.sqrt(out)
rusty1s's avatar
rusty1s committed
60
61

    return out