modifiedPrecision static method

RationalNumber modifiedPrecision(
  1. List<List<String>> references,
  2. List<String> hypothesis, {
  3. required int n,
})

Modified n-gram precision (clipped against reference counts).

Implementation

static RationalNumber modifiedPrecision(
  List<List<String>> references,
  List<String> hypothesis, {
  required int n,
}) {
  if (n <= 0) throw ArgumentError('n must be greater than zero.');
  if (references.isEmpty || hypothesis.isEmpty) return RationalNumber.zero;

  final hypCounts = MatchCounter<NGram<String>>(hypothesis.createNGrams(n));

  // Build max reference counts.
  final maxCounts = <NGram<String>, int>{};
  for (final ref in references) {
    final refCounts = MatchCounter<NGram<String>>(ref.createNGrams(n));
    for (final entry in refCounts.entries) {
      final existing = maxCounts[entry.key] ?? 0;
      if (entry.value > existing) maxCounts[entry.key] = entry.value;
    }
  }

  // Clip hypothesis counts.
  var clippedSum = 0;
  var hypSum = 0;
  for (final entry in hypCounts.entries) {
    hypSum += entry.value;
    final maxRef = maxCounts[entry.key] ?? 0;
    clippedSum += entry.value < maxRef ? entry.value : maxRef;
  }

  return RationalNumber(clippedSum, math.max(1, hypSum));
}