reminisce commented on a change in pull request #16720: [Numpy] Implement numpy 
operator 'average'
URL: https://github.com/apache/incubator-mxnet/pull/16720#discussion_r346594183
 
 

 ##########
 File path: tests/python/unittest/test_numpy_op.py
 ##########
 @@ -598,6 +598,100 @@ def _test_np_exception(func, shape, dim):
                 _test_np_exception(func, shape, dim)
 
 
+@with_seed()
+@use_np
+def test_np_average():
+    class TestAverage(HybridBlock):
+        def __init__(self, axis=None, returned=False):
+            super(TestAverage, self).__init__()
+            # necessary initializations
+            self._axis = axis
+            self._returned = returned
+             
+        def hybrid_forward(self, F, a, weights):
+            return F.np.average(a, weights=weights, axis=self._axis, 
returned=self._returned)
+    
+    def avg_backward(a, w, avg, axes):
+        # avg = sum(a * w) / sum(w)
+        if axes is not None and not isinstance(axes, tuple) and axes < 0:
+            axes += a.ndim
+        if w is None:
+            return [_np.ones(shape=a.shape, dtype=a.dtype)/(a.size/avg.size), 
None]
+        onedim = a.ndim != w.ndim
+        if onedim:
+            new_shape = [a.shape[i] if i == axes else 1 for i in range(a.ndim)]
+            w = w.reshape(new_shape)
+            w = _np.broadcast_to(w, a.shape)
+       
+        # partial a = w / sum(w)
+        # partial w = (a*sum(w) - sum(a*w)) / (sum(w) * sum(w))
+        scl = _np.sum(w, axis=axes, keepdims=True)
+        a_grad = _np.divide(w, scl)
+        w_grad = _np.divide(a*scl-_np.sum(a*w, axis=axes, keepdims=True), 
scl*scl)
+        
+        if onedim:
+            axis = []
+            for i in range(a.ndim):
+                if i != axes:
+                    axis.append(i)
+            w_grad = _np.sum(w_grad, axis=tuple(axis))
+        return [a_grad, w_grad]
+
+    tensor_shapes = [
+        ((3, 5), (3, 5), None),  # (a_shape, w_shape, axes)
+        ((4, 5, 6), (4, 5, 6), (0, 2)),
+        ((3,), (3,), 0),
+        ((2, 3), (3,), 1),
+        ((2, 3, 4), (2,), 0),
+        ((2, 3, 4), (3,), 1),
+        ((2, 3, 4), (4,), -1),
+        ((2, 3, 4, 5), (5,), 3)
+    ]
+
+    for hybridize in [True, False]:
+        for returned in [True, False]:
+            for a_shape, w_shape, axes in tensor_shapes:
+                for dtype in ['float32', 'float64']:
+                    for is_weighted in [True, False]:
+                        test_average = TestAverage(axes, returned)
+                        if hybridize:
+                            test_average.hybridize()
+                        a = np.random.uniform(-1.0, 1.0, size=a_shape, 
dtype=dtype)
+                        a.attach_grad()
 
 Review comment:
   Please test `a.attach_grad('null')`, `a.attach_grad('write')`, 
`a.attach_grad('add')`.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


With regards,
Apache Git Services

Reply via email to