File size: 2,646 Bytes
646b079 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | from __future__ import annotations
import unittest
from collections import Counter
from dataclasses import dataclass
from buddi_asr.evaluate import stratified_sample
@dataclass
class FakeRecord:
speaker_id: str
index: int
def build(speakers: dict[str, int]) -> list[FakeRecord]:
records = []
for speaker, count in speakers.items():
records.extend(FakeRecord(speaker, i) for i in range(count))
return records
class StratifiedSampleTests(unittest.TestCase):
def test_small_limit_spreads_across_speakers(self) -> None:
# One speaker with ten times the utterances of the others must not take
# ten times the sample, or the score tracks that child rather than the
# model.
records = build({"loud": 100, "a": 10, "b": 10, "c": 10})
picked = stratified_sample(records, 12, seed=42)
counts = Counter(record.speaker_id for record in picked)
self.assertEqual(len(picked), 12)
self.assertEqual(set(counts), {"loud", "a", "b", "c"})
self.assertEqual(max(counts.values()) - min(counts.values()), 0)
def test_it_is_deterministic(self) -> None:
records = build({"a": 20, "b": 20, "c": 20})
first = stratified_sample(records, 15, seed=7)
second = stratified_sample(records, 15, seed=7)
self.assertEqual([(r.speaker_id, r.index) for r in first],
[(r.speaker_id, r.index) for r in second])
def test_a_different_seed_draws_differently(self) -> None:
records = build({"a": 20, "b": 20, "c": 20})
first = stratified_sample(records, 15, seed=7)
second = stratified_sample(records, 15, seed=8)
self.assertNotEqual([(r.speaker_id, r.index) for r in first],
[(r.speaker_id, r.index) for r in second])
def test_no_limit_returns_everything_untouched(self) -> None:
records = build({"a": 5, "b": 5})
self.assertIs(stratified_sample(records, 0, seed=1), records)
self.assertIs(stratified_sample(records, 99, seed=1), records)
def test_limit_larger_than_a_speakers_supply_still_fills(self) -> None:
# "b" runs out after 2; the sample must keep drawing from "a" rather
# than stopping short of the requested size.
records = build({"a": 20, "b": 2})
picked = stratified_sample(records, 10, seed=3)
self.assertEqual(len(picked), 10)
def test_it_never_repeats_a_record(self) -> None:
records = build({"a": 20, "b": 20, "c": 20})
picked = stratified_sample(records, 40, seed=5)
self.assertEqual(len({id(record) for record in picked}), 40)
|