Compute balanced class weights for arbitrary labels in NumPy

Quick Overview

Apply the balanced class weight formula to arbitrary labels, including strings and non-consecutive integers, and return a label-to-weight dict in sorted label order. It tests label-wise counting in NumPy, why np.bincount breaks on such labels, and deterministic key ordering.

Compute balanced class weights for arbitrary labels in NumPy

Role: Data Scientist

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement `balanced_weights_any_labels(y: np.ndarray) -> dict`, applying scikit-learn's `class_weight='balanced'` formula to arbitrary labels (non-consecutive integers or strings). Return a dict mapping each label to `n_samples / (n_classes * count_of_that_label)` as a float, with keys in `np.unique(y)` order. Requirements: - Support integer and string labels without special-casing the dtype. - Do not use `np.bincount` on the raw labels (it fails on strings and yields `inf` for `{10, 20}`). Derive the counts label by label. - Match `compute_class_weight('balanced', classes=np.unique(y), y=y)`. - Grading compares the values, ordered by `np.unique(y)`, with `assert_allclose(rtol=1e-5)`, and the keys with `assert_array_equal`. Examples: ```text y = np.array([10, 10, 20, 20, 20]) n_samples = 5, n_classes = 2 count[10] = 2 -> 5 / (2 * 2) = 1.25 count[20] = 3 -> 5 / (2 * 3) = 0.8333... Output: {10: 1.25, 20: 0.8333333333333334} y = np.array(['cat', 'cat', 'dog', 'bird']) Output: {'bird': 1.333..., 'cat': 0.666..., 'dog': 1.333...} ``` ```hint Counting without indexing by value Look for a NumPy routine that returns the sorted distinct labels together with how often each one occurs, in a single call. ``` ### Constraints & Assumptions - `y` is a non-empty 1-D array, and the label set is exactly the labels that appear in it. - Labels may be integers with any values (negative, large or non-consecutive) or strings. ### What a Strong Answer Covers - Gets the sorted labels and their counts without indexing an array by label value. - Applies the formula with float division and returns a dict whose keys follow `np.unique(y)` order. - Converts NumPy scalar keys and values to plain Python types. - Explains why `np.bincount` breaks on strings and on non-consecutive integers. - States the time and space cost. ### Follow-up Questions - How would you handle a class that is present in a `classes` argument but absent from `y`? - Why does `np.bincount` fail on labels like `{10, 20}`, and what exactly does it return? - If `y` has millions of rows and only a few distinct labels, can you avoid sorting the whole array?

Overview: Apply the balanced class weight formula to arbitrary labels, including strings and non-consecutive integers, and return a label-to-weight dict in sorted label order. It tests label-wise counting in NumPy, why np.bincount breaks on such labels, and deterministic key ordering.

PracHub logo
General
Nov 25, 2026
easyData ScientistOtherMachine Learning
0
0

Implement balanced_weights_any_labels(y: np.ndarray) -> dict, applying scikit-learn's class_weight='balanced' formula to arbitrary labels (non-consecutive integers or strings). Return a dict mapping each label to n_samples / (n_classes * count_of_that_label) as a float, with keys in np.unique(y) order.

Requirements:

  • Support integer and string labels without special-casing the dtype.
  • Do not use np.bincount on the raw labels (it fails on strings and yields inf for {10, 20} ). Derive the counts label by label.
  • Match compute_class_weight('balanced', classes=np.unique(y), y=y) .
  • Grading compares the values, ordered by np.unique(y) , with assert_allclose(rtol=1e-5) , and the keys with assert_array_equal .

Examples:

y = np.array([10, 10, 20, 20, 20])
n_samples = 5, n_classes = 2
count[10] = 2 -> 5 / (2 * 2) = 1.25
count[20] = 3 -> 5 / (2 * 3) = 0.8333...
Output: {10: 1.25, 20: 0.8333333333333334}

y = np.array(['cat', 'cat', 'dog', 'bird'])
Output: {'bird': 1.333..., 'cat': 0.666..., 'dog': 1.333...}

Constraints & Assumptions

  • y is a non-empty 1-D array, and the label set is exactly the labels that appear in it.
  • Labels may be integers with any values (negative, large or non-consecutive) or strings.

What a Strong Answer Covers Guidance

  • Gets the sorted labels and their counts without indexing an array by label value.
  • Applies the formula with float division and returns a dict whose keys follow np.unique(y) order.
  • Converts NumPy scalar keys and values to plain Python types.
  • Explains why np.bincount breaks on strings and on non-consecutive integers.
  • States the time and space cost.

Follow-up Questions Guidance

  • How would you handle a class that is present in a classes argument but absent from y ?
  • Why does np.bincount fail on labels like {10, 20} , and what exactly does it return?
  • If y has millions of rows and only a few distinct labels, can you avoid sorting the whole array?