rohitg00/ai-engineering-from-scratch · error · ValueError
n must be positive
Error message
n must be positive
What it means
_ngram_counts builds n-gram Counters for BLEU's modified precision; n must be a positive integer because a 0-gram or negative window over token sequences has no defined slices and range(len(seq) - n + 1) would be empty or invalid.
Solutions
- Use n in 1..4 for standard BLEU variants
- Clamp n = max(1, n) when it comes from user input
- Validate max_n when parsing corpus_bleu arguments
Defensive patterns
Strategy: validation
When it happens
Trigger: Thrown at phases/19-capstone-projects/71-classical-metrics/code/main.py:57 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/e390570f18e3a6da.
Report an issue: GitHub.
Appendix: source
Thrown at phases/19-capstone-projects/71-classical-metrics/code/main.py:57
pred_tokens = tokenize(prediction)
tgt_tokens = tokenize(target)
if not pred_tokens and not tgt_tokens:
return 1.0
if not pred_tokens or not tgt_tokens:
return 0.0
pred_counts = Counter(pred_tokens)
tgt_counts = Counter(tgt_tokens)
overlap = sum((pred_counts & tgt_counts).values())
if overlap == 0:
return 0.0
precision = overlap / sum(pred_counts.values())
recall = overlap / sum(tgt_counts.values())
return 2.0 * precision * recall / (precision + recall)
def _ngram_counts(tokens: list[str], n: int) -> Counter:
if n <= 0:
raise ValueError("n must be positive")
if len(tokens) < n:
return Counter()
return Counter(tuple(tokens[i:i + n]) for i in range(len(tokens) - n + 1))
def _modified_precision(cand_tokens: list[str], ref_tokens: list[str], n: int) -> tuple[int, int]:
cand_ngrams = _ngram_counts(cand_tokens, n)
if not cand_ngrams:
return (0, 0)
ref_ngrams = _ngram_counts(ref_tokens, n)
clipped = 0
for gram, count in cand_ngrams.items():
clipped += min(count, ref_ngrams.get(gram, 0))
total = sum(cand_ngrams.values())
return (clipped, total)
def _brevity_penalty(cand_len: int, ref_len: int) -> float:View on GitHub (pinned to 39ea8a1c6d)