zihaolucky commented on a change in pull request #9195: [WIP]NCE loss gluon
URL: https://github.com/apache/incubator-mxnet/pull/9195#discussion_r161788287
 
 

 ##########
 File path: python/mxnet/gluon/data/sampler.py
 ##########
 @@ -136,3 +138,74 @@ def __len__(self):
         raise ValueError(
             "last_batch must be one of 'keep', 'discard', or 'rollover', " \
             "but got %s"%self._last_batch)
+
+
+class AliasMethodSampler(object):
+    """ The Alias Method: Efficient Sampling with Many Discrete Outcomes.
+    Can be use in NCELoss.
+
+    Parameters
+    ----------
+    K : int
+        Number of events.
+    probs : array
+        Probability of each events, corresponds to K.
+
+    References
+    -----------
+        
https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
+    """
+    def __init__(self, K, probs):
+        if K != len(probs):
+            raise ValueError("K should be equal to len(probs). K:%d, 
len(probs):%d" % (K, len(probs)))
+        self.K = K
+        self.prob = nd.zeros(K)
+        self.alias = nd.zeros(K, dtype='int32')
+
+        # Sort the data into the outcomes with probabilities
+        # that are larger and smaller than 1/K.
+        smaller = []
+        larger = []
+        for kk, prob in enumerate(probs):
+            self.prob[kk] = K*prob
+            if self.prob[kk] < 1.0:
 
 Review comment:
   @eric-haibin-lin The test code `speed` in my server, the Numpy is 100x 
faster than NDArray.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on 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