Module: CompletionKit::CalibrationMath

Defined in:
app/services/completion_kit/calibration_math.rb

Constant Summary collapse

Z_95 =
1.959963984540054

Class Method Summary collapse

Class Method Details

.mae(pairs) ⇒ Object



18
19
20
21
22
# File 'app/services/completion_kit/calibration_math.rb', line 18

def mae(pairs)
  return nil if pairs.empty?
  sum = pairs.sum { |ai, human| (ai.to_f - human.to_f).abs }
  sum / pairs.length
end

.pearson(pairs) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'app/services/completion_kit/calibration_math.rb', line 24

def pearson(pairs)
  return nil if pairs.length < 2
  xs = pairs.map { |a, _| a.to_f }
  ys = pairs.map { |_, h| h.to_f }
  mx = xs.sum / xs.length
  my = ys.sum / ys.length
  num = xs.zip(ys).sum { |x, y| (x - mx) * (y - my) }
  dx2 = xs.sum { |x| (x - mx)**2 }
  dy2 = ys.sum { |y| (y - my)**2 }
  denom = Math.sqrt(dx2 * dy2)
  return nil if denom.zero?
  num / denom
end

.quadratic_weighted_kappa(pairs, categories:) ⇒ Object



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
66
67
68
69
70
71
72
73
74
75
# File 'app/services/completion_kit/calibration_math.rb', line 38

def quadratic_weighted_kappa(pairs, categories:)
  return nil if pairs.empty?

  ratings = categories.to_a
  k = ratings.length
  return nil if k < 2

  index = ratings.each_with_index.to_h
  observed = Array.new(k) { Array.new(k, 0) }
  row_totals = Array.new(k, 0)
  col_totals = Array.new(k, 0)
  n = 0

  pairs.each do |ai, human|
    i = index[score_bucket(ai, ratings)]
    j = index[score_bucket(human, ratings)]
    next if i.nil? || j.nil?
    observed[i][j] += 1
    row_totals[i] += 1
    col_totals[j] += 1
    n += 1
  end
  return nil if n.zero?

  max_dist_sq = (k - 1.0)**2
  numerator = 0.0
  denominator = 0.0
  (0...k).each do |i|
    (0...k).each do |j|
      weight = ((i - j)**2) / max_dist_sq
      expected = (row_totals[i] * col_totals[j]).to_f / n
      numerator   += weight * observed[i][j]
      denominator += weight * expected
    end
  end
  return 1.0 if denominator.zero?
  1.0 - (numerator / denominator)
end

.score_bucket(value, ratings) ⇒ Object



77
78
79
80
81
82
# File 'app/services/completion_kit/calibration_math.rb', line 77

def score_bucket(value, ratings)
  rounded = value.to_f.round
  return ratings.first if rounded <= ratings.first
  return ratings.last if rounded >= ratings.last
  rounded
end

.wilson_interval(successes:, n:, z: Z_95) ⇒ Object



7
8
9
10
11
12
13
14
15
16
# File 'app/services/completion_kit/calibration_math.rb', line 7

def wilson_interval(successes:, n:, z: Z_95)
  return { point: nil, low: nil, high: nil } if n.to_i.zero?

  p_hat = successes.to_f / n
  denom = 1.0 + (z * z) / n
  center = (p_hat + (z * z) / (2.0 * n)) / denom
  margin = z * Math.sqrt((p_hat * (1 - p_hat) / n) + ((z * z) / (4.0 * n * n))) / denom

  { point: p_hat, low: [center - margin, 0.0].max, high: [center + margin, 1.0].min }
end