{ "cells": [ { "cell_type": "markdown", "id": "f9728f51", "metadata": {}, "source": [ "# Protostar Challenge: example entry (\"Ocarina of Ten\" on the leaderboard)\n", "\n", "*The 10-year mean.* A complete, simple entry for the *Climate Risk Intelligence* challenge. Its forecasts are on the leaderboard as **Ocarina of Ten**¹ (tagged *reference*): run it, then try to beat it.\n", "\n", "1. Load the yearly data (up to 2018).\n", "2. Try the model on a **practice run**: train up to 2010, predict 2011–2018, and score it like the challenge does.\n", "3. Refit on all data up to 2018 and write `submission.csv` for 2019–2025 (5,880 rows).\n", "\n", "## The model: the 10-year average\n", "\n", "For each city and metric, every forecast year (2019–2025) gets the same number: **the average of the city's last 10 valid years** (up to 2018).\n", "\n", "- **Why recent years?** The climate is warming, so the last decade is closer to the next few years than a 30-year average is. NOAA's Climate Prediction Center has long used such short \"optimal climate normals\" for this reason (Huang, van den Dool & Barnston, 1996, *Journal of Climate* 9:809, doi:10.1175/1520-0442(1996)009<0809:LLSTPU>2.0.CO;2).\n", "- **Why 10 years?** A trade-off: fewer years follow the warming better but are noisier (one hot summer weighs more); more years are smoother but lag behind the trend.\n", "- **What it ignores:** the trend *within* the 10 years, year-to-year cycles (e.g., El Niño), and other cities. Each of those is a way to improve on it.\n", "- **Where it should help:** average temperature and CDD (steady warming). Hottest day and precipitation are noisy: no simple model beats the 30-year average there by much.\n", "\n", "No data after 2018 is used, so the notebook follows the data rule.\n", "\n", "¹ *Ocarina of Ten is not to be confused with* Ocarina of Time, *whose Switch 2 remake comes out on November 5. Save the princess after the deadline: in Hyrule, pulling the Master Sword jumps you 7 years ahead; here, you have to forecast them.*" ] }, { "cell_type": "code", "execution_count": 1, "id": "196b9c2e", "metadata": { "execution": { "iopub.execute_input": "2026-11-05T14:00:48.885998Z", "iopub.status.busy": "2026-11-05T14:00:48.885488Z", "iopub.status.idle": "2026-11-05T14:00:50.034585Z", "shell.execute_reply": "2026-11-05T14:00:50.033293Z" } }, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/tmp/claude-1000/-home-alfredo-Datasets-NVIDIA-Hackhathon/03276e96-5a28-48c5-a971-d3be837fcaea/scratchpad/nbvenv/lib64/python3.14/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] }, { "name": "stdout", "output_type": "stream", "text": [ "(28052, 24) 1851 2018 210 cities\n" ] } ], "source": [ "from pathlib import Path\n", "import numpy as np\n", "import pandas as pd\n", "\n", "LOCAL = Path(\"protostar-climate-train-to-2018\")\n", "SOURCE = LOCAL if LOCAL.exists() else \"hf://datasets/CMU-OSPO/protostar-climate-train-to-2018\"\n", "annual = pd.read_parquet(f\"{SOURCE}/annual_indices\")\n", "# with the datasets library: load_dataset(\"CMU-OSPO/protostar-climate-train-to-2018\", \"annual_indices\", split=\"train\")\n", "\n", "print(annual.shape, annual[\"Year\"].min(), annual[\"Year\"].max(), annual[\"ID\"].nunique(), \"cities\")" ] }, { "cell_type": "markdown", "id": "bee0cc3f", "metadata": {}, "source": [ "## Long format and the 355-day rule\n", "\n", "One row per city × year × metric. A year counts only if the station missed **10 days or fewer** (Tmax and Tmin for the temperature metrics and CDD, precipitation for `total_precip_in`)." ] }, { "cell_type": "code", "execution_count": 2, "id": "d848f6b4", "metadata": { "execution": { "iopub.execute_input": "2026-11-05T14:00:50.037480Z", "iopub.status.busy": "2026-11-05T14:00:50.037039Z", "iopub.status.idle": "2026-11-05T14:00:50.061945Z", "shell.execute_reply": "2026-11-05T14:00:50.061559Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
city_idyearvaluemetricvalid
0USW00014929189341.09annual_avg_tempFalse
1USW00014929189449.05annual_avg_tempFalse
2USW00014929189541.94annual_avg_tempFalse
3USW00014929189641.16annual_avg_tempTrue
4USW00014929189740.89annual_avg_tempFalse
\n", "
" ], "text/plain": [ " city_id year value metric valid\n", "0 USW00014929 1893 41.09 annual_avg_temp False\n", "1 USW00014929 1894 49.05 annual_avg_temp False\n", "2 USW00014929 1895 41.94 annual_avg_temp False\n", "3 USW00014929 1896 41.16 annual_avg_temp True\n", "4 USW00014929 1897 40.89 annual_avg_temp False" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "METRICS = { # metric code: (column, missing-day columns)\n", " \"annual_avg_temp\": (\"Avg Temp\", [\"Miss Tmax\", \"Miss Tmin\"]),\n", " \"total_precip_in\": (\"ToT Prcp\", [\"Miss Prcp\"]),\n", " \"hottest_day_temp\": (\"Max Tmax\", [\"Miss Tmax\", \"Miss Tmin\"]),\n", " \"cdd\": (\"cdd\", [\"Miss Tmax\", \"Miss Tmin\"]),\n", "}\n", "\n", "rows = []\n", "for metric, (col, miss) in METRICS.items():\n", " part = annual[[\"ID\", \"Year\", col]].rename(columns={\"ID\": \"city_id\", \"Year\": \"year\", col: \"value\"})\n", " part[\"metric\"] = metric\n", " part[\"valid\"] = (annual[miss] <= 10).all(axis=1) & part[\"value\"].notna()\n", " rows.append(part)\n", "long = pd.concat(rows, ignore_index=True)\n", "long.head()" ] }, { "cell_type": "markdown", "id": "e461f81d", "metadata": {}, "source": [ "## The model and the 30-year-average baseline\n", "\n", "`recent_average` is the whole model. `thirty_year_average` is the challenge's reference: the Score compares every forecast with it (0 = no better, 100 = perfect). `forecast` repeats a single value for every year, since both are flat lines." ] }, { "cell_type": "code", "execution_count": 3, "id": "2afc0bea", "metadata": { "execution": { "iopub.execute_input": "2026-11-05T14:00:50.062779Z", "iopub.status.busy": "2026-11-05T14:00:50.062675Z", "iopub.status.idle": "2026-11-05T14:00:50.065409Z", "shell.execute_reply": "2026-11-05T14:00:50.065077Z" } }, "outputs": [], "source": [ "def recent_average(history, n_years=10):\n", " \"\"\"Our model: mean of each city-metric's last n valid years.\n", "\n", " \"Valid\" years follow the 355-day rule; skipping invalid years means a city\n", " with a gap still averages 10 real years, just reaching further back.\n", " \"\"\"\n", " v = history[history[\"valid\"]].sort_values(\"year\")\n", " return v.groupby([\"city_id\", \"metric\"])[\"value\"].apply(lambda s: s.tail(n_years).mean())\n", "\n", "\n", "def thirty_year_average(history, last_year):\n", " \"\"\"Baseline: mean of the valid years in the 30 years up to last_year.\"\"\"\n", " v = history[history[\"valid\"] & history[\"year\"].between(last_year - 29, last_year)]\n", " return v.groupby([\"city_id\", \"metric\"])[\"value\"].mean()\n", "\n", "\n", "def forecast(point, years):\n", " \"\"\"Repeat one value per city-metric for every forecast year.\"\"\"\n", " out = point.rename(\"predicted_value\").reset_index()\n", " return out.merge(pd.DataFrame({\"year\": years}), how=\"cross\")" ] }, { "cell_type": "markdown", "id": "82315d4c", "metadata": {}, "source": [ "## Practice run: train up to 2010, predict 2011–2018\n", "\n", "Before forecasting the unknown years, test the idea on years we know: pretend it is the end of 2010, forecast 2011–2018, and compare with what happened. This is how to check any model without using data after 2018.\n", "\n", "Scored like the challenge: MAE per metric, skill $S_m = 1 - \\mathrm{MAE}_{\\text{model}} / \\mathrm{MAE}_{\\text{30-year average}}$, and Score $= 100 \\times \\max(0, \\text{mean of the four } S_m)$." ] }, { "cell_type": "code", "execution_count": 4, "id": "fd771b9d", "metadata": { "execution": { "iopub.execute_input": "2026-11-05T14:00:50.066876Z", "iopub.status.busy": "2026-11-05T14:00:50.066623Z", "iopub.status.idle": "2026-11-05T14:00:50.126495Z", "shell.execute_reply": "2026-11-05T14:00:50.126039Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
MAE 30-year averageMAE our modelskill S_m
metric
annual_avg_temp1.6571.5130.087
cdd212.636184.0590.134
hottest_day_temp2.5632.568-0.002
total_precip_in6.1986.207-0.001
\n", "
" ], "text/plain": [ " MAE 30-year average MAE our model skill S_m\n", "metric \n", "annual_avg_temp 1.657 1.513 0.087\n", "cdd 212.636 184.059 0.134\n", "hottest_day_temp 2.563 2.568 -0.002\n", "total_precip_in 6.198 6.207 -0.001" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "train = long[long[\"year\"] <= 2010]\n", "test = long[long[\"year\"].between(2011, 2018) & long[\"valid\"]]\n", "years = list(range(2011, 2019))\n", "\n", "def mae_per_metric(pred):\n", " m = test.merge(pred, on=[\"city_id\", \"metric\", \"year\"])\n", " return (m[\"predicted_value\"] - m[\"value\"]).abs().groupby(m[\"metric\"]).mean()\n", "\n", "mae_ref = mae_per_metric(forecast(thirty_year_average(train, 2010), years))\n", "mae_model = mae_per_metric(forecast(recent_average(train), years))\n", "\n", "skill = 1 - mae_model / mae_ref\n", "score = 100 * max(0, skill.mean())\n", "pd.DataFrame({\"MAE 30-year average\": mae_ref, \"MAE our model\": mae_model, \"skill S_m\": skill}).round(3)" ] }, { "cell_type": "code", "execution_count": 5, "id": "42cf8379", "metadata": { "execution": { "iopub.execute_input": "2026-11-05T14:00:50.127368Z", "iopub.status.busy": "2026-11-05T14:00:50.127254Z", "iopub.status.idle": "2026-11-05T14:00:50.129206Z", "shell.execute_reply": "2026-11-05T14:00:50.128839Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Practice-run Score: 5.5 (0 = no better than the 30-year average, 100 = perfect)\n" ] } ], "source": [ "print(f\"Practice-run Score: {score:.1f} (0 = no better than the 30-year average, 100 = perfect)\")" ] }, { "cell_type": "markdown", "id": "a546bdf5", "metadata": {}, "source": [ "Read the table per metric: a positive skill means the 10-year average beat the 30-year average on that metric. Expect most of the gain on temperature and CDD, little or none on precipitation and hottest day. The practice run is one 8-year window; the real test years (2019–2025) can behave differently." ] }, { "cell_type": "markdown", "id": "b59df177", "metadata": {}, "source": [ "## Refit on everything up to 2018 and write `submission.csv`\n", "\n", "Same model, now using every year up to 2018. A few cities have no valid recent years for a metric; they fall back to their long-term average, so all 5,880 rows get a number." ] }, { "cell_type": "code", "execution_count": 6, "id": "a581cd97", "metadata": { "execution": { "iopub.execute_input": "2026-11-05T14:00:50.130301Z", "iopub.status.busy": "2026-11-05T14:00:50.130151Z", "iopub.status.idle": "2026-11-05T14:00:50.189571Z", "shell.execute_reply": "2026-11-05T14:00:50.189078Z" } }, "outputs": [ { "data": { "text/html": [ "
\n", "\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
city_idyearmetricpredicted_value
0USC000428632019annual_avg_temp66.40
1USC000428632019total_precip_in11.06
2USC000428632019hottest_day_temp103.89
3USC000428632019cdd1571.40
4USC000428632020annual_avg_temp66.40
5USC000428632020total_precip_in11.06
6USC000428632020hottest_day_temp103.89
7USC000428632020cdd1571.40
\n", "
" ], "text/plain": [ " city_id year metric predicted_value\n", "0 USC00042863 2019 annual_avg_temp 66.40\n", "1 USC00042863 2019 total_precip_in 11.06\n", "2 USC00042863 2019 hottest_day_temp 103.89\n", "3 USC00042863 2019 cdd 1571.40\n", "4 USC00042863 2020 annual_avg_temp 66.40\n", "5 USC00042863 2020 total_precip_in 11.06\n", "6 USC00042863 2020 hottest_day_temp 103.89\n", "7 USC00042863 2020 cdd 1571.40" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "cities = sorted(annual[\"ID\"].unique())\n", "grid = pd.MultiIndex.from_product([cities, range(2019, 2026), METRICS], names=[\"city_id\", \"year\", \"metric\"]).to_frame(index=False)\n", "\n", "point = recent_average(long)\n", "fallback = long.groupby([\"city_id\", \"metric\"])[\"value\"].mean() # cities with no valid recent years\n", "point = point.reindex(fallback.index).fillna(fallback)\n", "\n", "submission = grid.merge(point.rename(\"predicted_value\").reset_index(), on=[\"city_id\", \"metric\"], how=\"left\")\n", "submission[\"predicted_value\"] = submission[\"predicted_value\"].round(2)\n", "\n", "# Run from the dataset's code/ folder: submission.csv goes to the dataset root\n", "out = Path(\"..\") if Path.cwd().name == \"code\" else Path(\"example_submission\")\n", "out.mkdir(exist_ok=True)\n", "submission.to_csv(out / \"submission.csv\", index=False)\n", "submission.head(8)" ] }, { "cell_type": "markdown", "id": "ad9655ef", "metadata": {}, "source": [ "## Check the file before submitting" ] }, { "cell_type": "code", "execution_count": 7, "id": "1a3e1909", "metadata": { "execution": { "iopub.execute_input": "2026-11-05T14:00:50.190667Z", "iopub.status.busy": "2026-11-05T14:00:50.190545Z", "iopub.status.idle": "2026-11-05T14:00:50.198543Z", "shell.execute_reply": "2026-11-05T14:00:50.198229Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "submission.csv OK: 5880 rows. Copy it to your Hugging Face dataset, with your README.\n" ] } ], "source": [ "s = pd.read_csv(out / \"submission.csv\")\n", "assert list(s.columns) == [\"city_id\", \"year\", \"metric\", \"predicted_value\"]\n", "assert len(s) == 210 * 7 * 4 == 5880\n", "assert not s.duplicated([\"city_id\", \"year\", \"metric\"]).any()\n", "assert set(s[\"metric\"]) == set(METRICS) and set(s[\"year\"]) == set(range(2019, 2026))\n", "assert s[\"predicted_value\"].notna().all()\n", "print(\"submission.csv OK:\", len(s), \"rows. Copy it to your Hugging Face dataset, with your README.\")" ] } ], "metadata": { "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.14.8" } }, "nbformat": 4, "nbformat_minor": 5 }