File size: 1,956 Bytes
d79a78d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""The challenge's scoring, as in the Space's scoring.py.

    MAE_m  = mean |predicted - actual| over the scored rows of metric m
    S_m    = 1 - MAE_m / MAE_ref,m          (ref = the 30-year-average baseline)
    Score  = 100 * max(0, mean of the four S_m)

Scored rows: valid years (10-day rule) of city-metrics that have a baseline
(>= 10 valid years in the 30 years up to the origin).
"""

import numpy as np
import pandas as pd

from .common import METRICS

KEY = ["city_id", "year", "metric"]


def skill(mae: float, mae_ref: float) -> float:
    return 1.0 - mae / mae_ref


def challenge_score(skills: dict[str, float]) -> float:
    """Score 0-100 from the four per-metric skills."""
    assert set(skills) == set(METRICS)
    return 100.0 * max(0.0, float(np.mean([skills[m] for m in METRICS])))


def score_frames(submission: pd.DataFrame, answer_key: pd.DataFrame, reference: pd.DataFrame) -> dict:
    """Score a submission table the way the Space does (used to cross-check the array path).

    submission: city_id, year, metric, predicted_value
    answer_key: city_id, year, metric, actual_value, scored (bool)
    reference:  the 30-year-average forecasts, same columns as submission
    """
    truth = answer_key[answer_key["scored"].astype(bool)][KEY + ["actual_value"]]

    def mae(pred):
        rows = truth.merge(pred[KEY + ["predicted_value"]], on=KEY, how="left")
        if not np.isfinite(rows["predicted_value"]).all():
            raise ValueError("scored rows without a finite prediction")
        return (rows["predicted_value"] - rows["actual_value"]).abs().groupby(rows["metric"]).mean()

    model, ref = mae(submission), mae(reference)
    skills = {m: skill(float(model[m]), float(ref[m])) for m in METRICS}
    return {"score": challenge_score(skills), "mae": {m: float(model[m]) for m in METRICS},
            "mae_ref": {m: float(ref[m]) for m in METRICS}, "skill": skills,
            "n_rows": int(len(truth))}