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

Gamma shape parameter must be positive

Error message

Gamma shape parameter must be positive

What it means

Raised in _gamma_sample when the shape parameter is zero or negative. Gamma sampling (used by _beta_sample for posterior draws) is only defined for a positive shape, and the Marsaglia-Tsang-style algorithm branches on shape >= 1, so non-positive input is rejected up front.

Solutions

  1. Pass positive alpha/beta parameters to _beta_sample (they propagate to _gamma_sample)
  2. Validate posterior parameters before sampling: Beta(alpha, beta) requires alpha > 0 and beta > 0
  3. Fix likelihood/prior counts that produced zero pseudo-counts; add a smoothing constant if needed
Defensive patterns

Strategy: validation

When it happens

Trigger: Thrown at phases/01-math-foundations/07-bayes-theorem/code/bayes.py:320 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/353a8f8c6fceec2a. Report an issue: GitHub.

Appendix: source

Thrown at phases/01-math-foundations/07-bayes-theorem/code/bayes.py:320

    lifts.sort()
    median_lift = lifts[len(lifts) // 2]
    low = lifts[int(len(lifts) * 0.05)]
    high = lifts[int(len(lifts) * 0.95)]
    print(f"  Median lift: {median_lift:.1%}")
    print(f"  90% credible interval: [{low:.1%}, {high:.1%}]")


def _beta_sample(alpha, beta_param, rng_module):
    x = _gamma_sample(alpha, rng_module)
    y = _gamma_sample(beta_param, rng_module)
    if x + y == 0:
        return 0.5
    return x / (x + y)


def _gamma_sample(shape, rng_module):
    if shape <= 0:
        raise ValueError("Gamma shape parameter must be positive")
    if shape < 1:
        return _gamma_sample(shape + 1, rng_module) * rng_module.random() ** (1.0 / shape)

    d = shape - 1.0 / 3.0
    c = 1.0 / (9.0 * d) ** 0.5

    while True:
        x = rng_module.gauss(0, 1)
        v = (1 + c * x) ** 3
        if v <= 0:
            continue
        u = rng_module.random()
        if u < 1 - 0.0331 * x ** 4:
            return d * v
        if math.log(u) < 0.5 * x ** 2 + d * (1 - v + math.log(v)):
            return d * v

View on GitHub (pinned to 39ea8a1c6d)