mean.py 3.9 KB
Newer Older
Matthias Fey's avatar
Matthias Fey committed
1
2
from __future__ import division

rusty1s's avatar
rusty1s committed
3
from .scatter import Scatter, scatter
rusty1s's avatar
rusty1s committed
4
5
6
from .utils import gen_filled_tensor, gen_output


rusty1s's avatar
rusty1s committed
7
8
9
10
11
12
13
14
15
16
17
18
19
class ScatterMean(Scatter):
    def __init__(self, dim):
        super(ScatterMean, self).__init__('mean', dim)

    def save_for_backward_step(self, *data):
        output, index, input, count = data
        self.save_for_backward(index)

    def backward_step(self, *data):
        grad, index = data
        return grad.gather(self.dim, index.data)


rusty1s's avatar
rusty1s committed
20
def scatter_mean_(output, index, input, dim=0):
rusty1s's avatar
rusty1s committed
21
22
23
24
25
26
27
28
29
30
31
32
    r"""
    |

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

    |

    Averages all values from the :attr:`input` tensor into :attr:`output` at
    the indices specified in the :attr:`index` tensor along an given axis
rusty1s's avatar
rusty1s committed
33
34
35
36
37
38
    :attr:`dim`. If multiple indices reference the same location, their
    **contributions average** (`cf.` :meth:`~torch_scatter.scatter_add_`).

    For one-dimensional tensors, the operation computes

    .. math::
rusty1s's avatar
typo  
rusty1s committed
39
        \mathrm{output}_i = \mathrm{output}_i + \frac{1}{N_i} \cdot
rusty1s's avatar
rusty1s committed
40
41
42
        \sum_j \mathrm{input}_j

    where sum is over :math:`j` such that :math:`\mathrm{index}_j = i` and
rusty1s's avatar
typo  
rusty1s committed
43
    :math:`N_i` indicates the number of indices referencing :math:`i`.
rusty1s's avatar
rusty1s committed
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

    Args:
        output (Tensor): The destination tensor
        index (LongTensor): The indices of elements to scatter
        input (Tensor): The source tensor
        dim (int, optional): The axis along which to index

    :rtype: :class:`Tensor`

    .. testsetup::

        import torch

    .. testcode::

        from torch_scatter import scatter_mean_
        input =     torch.Tensor([[2, 0, 1, 4, 3], [0, 2, 1, 3, 4]])
        index = torch.LongTensor([[4, 5, 4, 2, 3], [0, 0, 2, 2, 1]])
        output = torch.zeros(2, 6)
        scatter_mean_(output, index, input, dim=1)
        print(output)

    .. testoutput::

        0.0000  0.0000  4.0000  3.0000  1.5000  0.0000
        1.0000  4.0000  2.0000  0.0000  0.0000  0.0000
       [torch.FloatTensor of size 2x6]
    """
rusty1s's avatar
rusty1s committed
72
    init = gen_filled_tensor(output, output.size(), fill_value=0)
rusty1s's avatar
typos  
rusty1s committed
73
    count = gen_filled_tensor(output, output.size(), fill_value=0)
rusty1s's avatar
rusty1s committed
74
    scatter(ScatterMean, 'mean', dim, init, index, input, count)
rusty1s's avatar
typos  
rusty1s committed
75
    count[count == 0] = 1
rusty1s's avatar
rusty1s committed
76
77
    init /= count
    output += init
rusty1s's avatar
rusty1s committed
78
79
80
    return output


rusty1s's avatar
rename  
rusty1s committed
81
def scatter_mean(index, input, dim=0, size=None, fill_value=0):
rusty1s's avatar
rusty1s committed
82
83
84
85
86
87
88
89
    r"""Averages all values from the :attr:`input` tensor at the indices
    specified in the :attr:`index` tensor along an given axis :attr:`dim`
    (`cf.` :meth:`~torch_scatter.scatter_mean_` and
    :meth:`~torch_scatter.scatter_add`).

    For one-dimensional tensors, the operation computes

    .. math::
rusty1s's avatar
typo  
rusty1s committed
90
        \mathrm{output}_i = \mathrm{fill\_value} + \frac{1}{N_i} \cdot
rusty1s's avatar
rusty1s committed
91
92
93
        \sum_j \mathrm{input}_j

    where sum is over :math:`j` such that :math:`\mathrm{index}_j = i` and
rusty1s's avatar
typo  
rusty1s committed
94
    :math:`N_i` indicates the number of indices referencing :math:`i`.
rusty1s's avatar
rusty1s committed
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

    Args:
        index (LongTensor): The indices of elements to scatter
        input (Tensor): The source tensor
        dim (int, optional): The axis along which to index
        size (int, optional): Output size at dimension :attr:`dim`
        fill_value (int, optional): Initial filling of output tensor

    :rtype: :class:`Tensor`

    .. testsetup::

        import torch

    .. testcode::

        from torch_scatter import scatter_mean
        input =     torch.Tensor([[2, 0, 1, 4, 3], [0, 2, 1, 3, 4]])
        index = torch.LongTensor([[4, 5, 4, 2, 3], [0, 0, 2, 2, 1]])
        output = scatter_mean(index, input, dim=1)
        print(output)

    .. testoutput::

        0.0000  0.0000  4.0000  3.0000  1.5000  0.0000
        1.0000  4.0000  2.0000  0.0000  0.0000  0.0000
       [torch.FloatTensor of size 2x6]
    """
rusty1s's avatar
rename  
rusty1s committed
123
    output = gen_output(index, input, dim, size, fill_value)
rusty1s's avatar
rusty1s committed
124
    return scatter_mean_(output, index, input, dim)