Sample negative items a user has not interacted with
Why it matters Two-tower retrieval models for feeds and ads are trained with sampled negatives like these.
Implicit-feedback training pairs each positive item with random items the user has not touched.
Write sample_negatives(positives, n_items, k, seed). Use rng = np.random.default_rng(seed). Repeatedly draw rng.integers(0, n_items) one at a time and keep a draw if it is not in positives and not already kept, until k are kept. Return them in the order kept. If fewer than k valid items exist, raise ValueError.
def sample_negatives(positives, n_items, k, seed)Example
positives {0, 1}, n_items 3, k 1 must return [2].
Understand the idea
With implicit feedback you only know what a user clicked. To train, you pair those positives with negatives: random items the user never touched. Rejection sampling is the simplest fair way. Draw a random item; if it is a positive or already picked, throw it away and draw again. Worked example: positives {1, 3}, n_items 5, k 2. Suppose the draws come out as 3, 0, 0, 4. Draw 3 is a positive, so skip it. Draw 0 is valid, keep it. The next 0 is already kept, so skip it. Draw 4 is valid, keep it. Now 2 are kept, so return [0, 4] in the order kept. Rule: create the generator from the seed once, draw one integer in [0, n_items) at a time, keep it only if it is not a positive and not already kept, and stop at k. First check that n_items minus the number of valid positives in range is at least k, otherwise raise ValueError, so the loop can never run forever. Used in: training two-tower retrieval models, matrix factorisation with BPR, and word2vec style negative sampling.