Average values per group id with weighted bincount

Why it matters Group statistics over integer ids appear in per-class metrics, segment reductions and embedding bag layers.

Per-class loss, per-user latency and per-token-type accuracy are all group means. With integer group ids, np.bincount computes them without a loop or pandas.

Write group_means(values, groups, n_groups). values is a 1D float array, groups a 1D int array of the same length with ids in 0..n_groups-1. Return a float array of shape (n_groups,) with the mean of the values in each group, and NaN for groups with no values. Do not emit warnings.

Signaturedef group_means(values, groups, n_groups)

Example

group_means([1.0, 3.0, 10.0], [0, 0, 2], 4) is [2.0, nan, 10.0, nan].

Understand the idea

np.bincount(g) counts how many times each integer 0, 1, 2, ... appears in g. With weights=v, it adds up v for each integer instead of counting. Sum divided by count is the group mean.

Worked example: values [1, 3, 10] with groups [0, 0, 2] and 4 groups. Weighted sums: group 0 = 1 + 3 = 4, group 1 = 0, group 2 = 10, group 3 = 0. Counts: [2, 0, 1, 0]. Means: 4 / 2 = 2.0, group 1 has no data so NaN, 10 / 1 = 10.0, group 3 NaN.

Rule: mean_k = sum(v_i for g_i = k) / count(g_i = k), defined only when the count is positive. Use minlength = number of groups so the arrays line up.

Used for per-class accuracy and loss, segment means in graph networks and averaging embeddings per document.

Shapes and data flow

values (N,), groups (N,) -> means (n_groups,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

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

  • Sample 1: examplegroup_means([1.0, 3.0, 10.0], [0, 0, 2], 4)
  • Sample 2: random groupsgroup_means(_v, _g, 5)
  • Test 3: single groupgroup_means([2.0, 4.0, 9.0], [1, 1, 1], 2)