AlecAlameddine's picture
Upload 105 files
d79a78d verified
Raw History Blame Contribute Delete
1.96 kB
"""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))}