Remap sparse token ids to a compact vocabulary with np.unique

Why it matters Id remapping keeps embedding tables and one-hot features small in recommenders and classic NLP pipelines.

When you train an embedding table on a small dataset that uses only a few ids out of a huge range, you remap them to 0..k-1 so the table stays small.

Write compact_ids(ids) for a 1D int array. Return a tuple (vocab, new_ids, counts): vocab is the sorted array of distinct ids, new_ids has the same length as ids and new_ids[i] is the position of ids[i] in vocab, and counts[j] is how often vocab[j] occurs.

Signaturedef compact_ids(ids)

Example

compact_ids([50, 7, 50, 900]) gives vocab [7, 50, 900], new_ids [1, 0, 1, 2], counts [1, 2, 1].

Understand the idea

np.unique sorts an array and keeps one copy of each value. With flags it also returns:
return_index: where each unique value first appears in the input.
return_inverse: for each input element, which unique value it is.
return_counts: how many times each unique value appears.

Worked example: ids [50, 7, 50, 900]. Sorted unique values: [7, 50, 900]. The first 50 is vocab position 1, 7 is 0, the second 50 is 1, 900 is 2, so new_ids = [1, 0, 1, 2]. Counts are [1, 2, 1]. return_index would be [1, 0, 3], which is not a remap.

Rule: vocab[new_ids] == ids, and sum(counts) == len(ids).

Recommenders compact user and item ids this way, and classic NLP builds vocabularies and frequency tables from token arrays with it.

Shapes and data flow

ids (N,) -> vocab (K,), new_ids (N,), counts (K,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplecompact_ids([50, 7, 50, 900])
  • Sample 2: repeated idscompact_ids([3, 3, 3, 10, 2, 10])
  • Test 3: one idcompact_ids([42])
  • Test 4: round trip(lambda v, n, c: v[n])(*compact_ids([9, 1, 9, 5]))