rohitg00/ai-engineering-from-scratch · error · ValueError

bins must be positive

Error message

bins must be positive

What it means

Error "bins must be positive" thrown in rohitg00/ai-engineering-from-scratch.

Source

Thrown at phases/19-capstone-projects/73-perplexity-calibration/code/main.py:83

        raise ValueError("confidences must lie in [0, 1]")
    uniq = set(np.unique(correct).tolist())
    if not uniq.issubset({0, 1, 0.0, 1.0, True, False}):
        raise ValueError("correct must be 0/1 or boolean")


def _bin_indices(confidences: np.ndarray, n_bins: int) -> np.ndarray:
    edges = np.linspace(0.0, 1.0, n_bins + 1)
    idx = np.searchsorted(edges, confidences, side="right") - 1
    idx = np.clip(idx, 0, n_bins - 1)
    return idx


def expected_calibration_error(confidences: Sequence[float], correct: Sequence[int], bins: int = 10) -> tuple[float, int]:
    conf = np.asarray(confidences, dtype=np.float64)
    corr = np.asarray(correct, dtype=np.float64)
    _validate_probs(conf, corr)
    if bins <= 0:
        raise ValueError("bins must be positive")
    n = conf.size
    if n == 0:
        return (0.0, 0)
    idx = _bin_indices(conf, bins)
    total_gap = 0.0
    populated = 0
    for b in range(bins):
        mask = idx == b
        size = int(mask.sum())
        if size == 0:
            continue
        populated += 1
        avg_conf = float(conf[mask].mean())
        avg_acc = float(corr[mask].mean())
        total_gap += (size / n) * abs(avg_conf - avg_acc)
    return (float(total_gap), populated)

View on GitHub (pinned to 39ea8a1c6d)

When it happens

Trigger: Thrown at phases/19-capstone-projects/73-perplexity-calibration/code/main.py:83 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of rohitg00/ai-engineering-from-scratch@39ea8a1c6d (2026-08-26). Data as JSON: /api/errors/4372f4554cf12762. Report an issue: GitHub.