File size: 72,099 Bytes
3656aff | 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 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 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 | """Classical intensity baselines on storm-grouped, train-selected features.
``run_from_config`` assigns storms with ``src.splits.assign_storms`` when
``split.strategy`` is ``storm_wise``. ``recorded`` keeps the ``split`` column
already on the manifest and does not redraw it. An official competition side
stays in ``source_split`` and is never the modeling split. Models are fit on
train storms and scored on val storms. The test split is never passed to a
headline fit and is never scored.
Learned models are sklearn ``Pipeline`` objects. Inner ``StratifiedGroupKFold``
is a comparison diagnostic. The default pool is the training storms and the
default group is ``storm_id``. ``baselines.cv_pool: train_val`` uses train and
val together, still excluding test, and ``baselines.cv_group_column`` names
the group that must stay inside one fold. It is not a license to tune on the
locked test storms.
SMOTE, when enabled, resamples the current training fold and never the
validation rows. Otherwise those classifiers use class weights inside the
fold. Regression does not use SMOTE. Persistence is a reference baseline:
the previous frame's best-track label, not the imagery. It is not a feature
and it is not fit. Image-only models cannot be compared against it.
ADT, SATCON, and Dvorak columns
are left empty until those products are actually joined.
Regression scores also write ``per_class_metrics.csv`` on the validation
split only. Intervals resample storm IDs. A ``wind_averaging`` column is
grouped when present. An ``on_fix`` column adds the rows on a best-track
fix. The test split is not scored in that table.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import logging
import shlex
import subprocess
import sys
from dataclasses import dataclass
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.base import BaseEstimator, ClassifierMixin, RegressorMixin
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LinearRegression, LogisticRegression, Ridge
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.svm import SVC, SVR
from src.config import load_config
from src.data_loader import load_manifest
from src.features import FeatureSpec, extract_feature_table, model_matrix, select_features
from src.metrics import classification_metrics, metrics_by_class, regression_metrics
from src.plots import save_confusion_matrix, save_feature_importance, save_regression_scatter
from src.schema import DEFAULT_NAMES, FORBIDDEN_FEATURES, parse_is_synthetic, wind_to_imd5
from src.splits import (
LeakageError,
assert_no_forbidden_inputs,
assert_no_group_leakage,
assign_storms,
observation_order,
)
logger = logging.getLogger(__name__)
BANNER = (
"Software check only. Do not quote these numbers as experimental results. "
"Operational baselines (ADT, SATCON, Dvorak) are not joined. "
"The locked test split was not used for fitting, selection, or SMOTE. "
"This is not a forecast or a warning."
)
PERSISTENCE_NOTE = (
"Persistence is a reference baseline. It uses the previous frame's "
"best-track label, not the imagery. Image-only models cannot be compared against it."
)
REFERENCE_ROLE = "reference_baseline"
IMAGE_ROLE = "image_features"
OPERATIONAL_COLUMNS = ("adt_mae_kt", "satcon_mae_kt", "dvorak_mae_kt")
COMPARISON_COLUMNS = (
"task",
"model",
"role",
"split_protocol",
"inner_cv",
"n_train_rows",
"n_val_rows",
"n_train_storms",
"n_val_storms",
"n_features",
"mae_kt",
"rmse_kt",
"bias_kt",
"cv_mae_kt_mean",
"cv_mae_kt_std",
*[f"mae_{name}" for name in DEFAULT_NAMES],
"macro_f1",
"cv_macro_f1_mean",
"cv_macro_f1_std",
*[f"recall_{name}" for name in DEFAULT_NAMES],
*OPERATIONAL_COLUMNS,
"fit_notes",
"quote_as_result",
"synthetic",
)
class BaselineDataError(ValueError):
"""The frame cannot support a leak-free baseline comparison."""
class MeanRegressor(BaseEstimator, RegressorMixin):
"""Predict the mean of the labels it was fit on."""
def fit(self, X, y):
target = np.asarray(y, dtype=np.float64).ravel()
self.mean_ = float(np.mean(target))
self.n_features_in_ = int(np.asarray(X).shape[1])
return self
def predict(self, X):
return np.full(np.asarray(X).shape[0], self.mean_, dtype=np.float64)
class MostFrequentClassifier(BaseEstimator, ClassifierMixin):
"""Predict the most common training class. Ties take the sorted label."""
def fit(self, X, y):
labels, counts = np.unique(np.asarray(y).ravel(), return_counts=True)
self.classes_ = labels
self.constant_ = labels[int(np.argmax(counts))]
self.n_features_in_ = int(np.asarray(X).shape[1])
return self
def predict(self, X):
return np.full(np.asarray(X).shape[0], self.constant_)
_MAJORITY_CLASSIFIERS = frozenset({"most_frequent", "mean"})
PER_CLASS_COLUMNS = (
"task",
"model",
"split",
"subset",
"wind_averaging",
"row_kind",
"intensity_class",
"storm_id",
"n_rows",
"n_storms",
"rmse_kt",
"mae_kt",
"bias_kt",
"rmse_kt_ci_low",
"rmse_kt_ci_high",
"mae_kt_ci_low",
"mae_kt_ci_high",
"bias_kt_ci_low",
"bias_kt_ci_high",
"ci_level",
"n_resamples",
"seed",
"resample",
"status",
"quote_as_result",
"synthetic",
)
_PER_CLASS_MD_COLUMNS = (
"model",
"subset",
"wind_averaging",
"row_kind",
"intensity_class",
"storm_id",
"n_rows",
"n_storms",
"rmse_kt",
"rmse_kt_ci_low",
"rmse_kt_ci_high",
"mae_kt",
"mae_kt_ci_low",
"mae_kt_ci_high",
"bias_kt",
"bias_kt_ci_low",
"bias_kt_ci_high",
"status",
"quote_as_result",
)
_MARKDOWN_COLUMNS = (
"task",
"model",
"role",
"n_train_rows",
"n_val_rows",
"n_train_storms",
"n_val_storms",
"mae_kt",
"rmse_kt",
"bias_kt",
"macro_f1",
"fit_notes",
"quote_as_result",
"synthetic",
)
def persistence_predictions(frame: pd.DataFrame) -> np.ndarray:
"""Previous ``wind_speed_kt`` inside the same storm.
Order is ``timestamp`` when that column exists, otherwise
``relative_time_s``, otherwise the given row order. The first row of
each storm is NaN. Wind from another storm is never used. This is a
baseline, not a model feature.
"""
if "storm_id" not in frame.columns or "wind_speed_kt" not in frame.columns:
raise ValueError("persistence needs storm_id and wind_speed_kt")
winds = pd.to_numeric(frame["wind_speed_kt"], errors="coerce").to_numpy(dtype=np.float64)
table = pd.DataFrame(
{
"storm_id": frame["storm_id"].astype(str).to_numpy(),
"wind": winds,
"order": observation_order(frame).to_numpy(),
"row": np.arange(len(frame)),
}
)
table = table.sort_values(["storm_id", "order", "row"], kind="mergesort")
table["prediction"] = table.groupby("storm_id", sort=False)["wind"].shift(1)
table = table.sort_values("row", kind="mergesort")
return table["prediction"].to_numpy(dtype=np.float64)
def persistence_class_predictions(frame: pd.DataFrame) -> np.ndarray:
"""Previous same-storm wind, mapped with this project's five bins."""
winds = persistence_predictions(frame)
classes = np.empty(len(winds), dtype=object)
for index, value in enumerate(winds):
if not np.isfinite(value):
classes[index] = None
else:
classes[index] = wind_to_imd5(float(value))
return classes
def _known_class_mask(truth: np.ndarray, predicted: np.ndarray) -> np.ndarray:
known = set(DEFAULT_NAMES)
return np.asarray(
[item in known and guess in known for item, guess in zip(truth, predicted, strict=True)],
dtype=bool,
)
@dataclass(frozen=True)
class BaselineReport:
comparison: pd.DataFrame
selected_features: tuple[str, ...]
train_storms: frozenset[str]
val_storms: frozenset[str]
test_storms: frozenset[str]
fitted_storms: frozenset[str]
n_rows_used_for_selection: int
out_dir: Path
def xgboost_available() -> bool:
try:
import xgboost # noqa: F401
except ImportError:
return False
return True
_BASELINE_KEYS = (
"n_splits",
"seed",
"regression_models",
"classification_models",
"use_smote",
"ridge_alpha",
"knn_neighbors",
"svr_c",
"svc_c",
"rf_estimators",
"rf_max_depth",
"xgb_estimators",
"xgb_max_depth",
"xgb_learning_rate",
"max_iter",
"bootstrap_resamples",
"per_storm_breakdown",
"cv_pool",
"cv_group_column",
"cv_collapse_rare",
"cv_assign",
)
def baseline_params(config: dict) -> dict:
"""Hyperparameters from ``baselines`` in the YAML config. No fallbacks."""
raw = config.get("baselines")
if not isinstance(raw, dict):
raise KeyError("config baselines is required")
missing = [key for key in _BASELINE_KEYS if key not in raw]
if missing:
raise KeyError(f"config baselines missing {missing}")
return {key: raw[key] for key in _BASELINE_KEYS}
def selection_params(config: dict) -> dict:
"""Feature-selection hyperparameters from ``features.selection``."""
raw = config["features"]["selection"]
return {
"correlation_threshold": float(raw["correlation_threshold"]),
"max_features": int(raw["max_features"]),
"method": str(raw["method"]),
"n_estimators": int(raw["n_estimators"]),
"seed": int(raw["seed"]),
}
def iter_stratified_group_folds(y_strat, groups, n_splits: int, seed: int):
"""Yield train/val indices. A storm never sits on both sides of a fold."""
labels = np.asarray(y_strat).ravel()
group_ids = np.asarray(groups).ravel()
if len(labels) != len(group_ids):
raise BaselineDataError("stratify labels and groups must align")
if n_splits < 2:
raise BaselineDataError("n_splits must be at least 2")
table = pd.DataFrame({"y": labels.astype(str), "g": group_ids.astype(str)})
for label, part in table.groupby("y"):
n_groups = int(part["g"].nunique())
if n_groups < n_splits:
raise BaselineDataError(
f"class {label} is in {n_groups} storms but n_splits={n_splits}"
)
from sklearn.model_selection import StratifiedGroupKFold
splitter = StratifiedGroupKFold(
n_splits=n_splits, shuffle=True, random_state=seed
)
yield from splitter.split(np.zeros(len(labels)), table["y"], table["g"])
def _require_cv_pool(params: dict) -> str:
pool = params["cv_pool"]
if not isinstance(pool, str) or pool.strip().lower() not in {"train", "train_val"}:
raise BaselineDataError("cv_pool must be train or train_val")
return pool.strip().lower()
def _require_cv_bool(params: dict) -> bool:
value = params["cv_collapse_rare"]
if not isinstance(value, bool):
raise BaselineDataError("cv_collapse_rare must be true or false")
return value
def _cv_group_ids(frame: pd.DataFrame, params: dict) -> np.ndarray:
column = params["cv_group_column"]
if not isinstance(column, str) or not column.strip():
raise BaselineDataError("cv_group_column must name a column")
column = column.strip()
if column not in frame.columns:
raise BaselineDataError(f"cv_group_column {column} is not on the frame")
return frame[column].astype(str).to_numpy()
def collapse_rare_stratify_labels(
labels: np.ndarray,
groups: np.ndarray,
n_splits: int,
enabled: bool,
) -> tuple[np.ndarray, str]:
"""Fold-assignment labels. The scored target is not changed here.
When ``enabled`` is false the labels are unchanged. A label that sits in
fewer groups than ``n_splits`` is mapped onto the most common label that
already has enough groups, and only for the fold splitter.
"""
text = np.asarray(labels).astype(str)
group_ids = np.asarray(groups).astype(str)
if not enabled:
return text, ""
table = pd.DataFrame({"y": text, "g": group_ids})
counts = table.groupby("y")["g"].nunique()
rare = [label for label, count in counts.items() if int(count) < n_splits]
if not rare:
return text, ""
eligible = [label for label, count in counts.items() if int(count) >= n_splits]
if not eligible:
raise BaselineDataError(f"every stratify label is in fewer than {n_splits} groups")
host = str(table.loc[table["y"].isin(eligible), "y"].value_counts().index[0])
collapsed = text.copy()
for label in rare:
collapsed[collapsed == str(label)] = host
note = "stratify_collapsed:" + ",".join(
f"{label}->{host}" for label in sorted(str(label) for label in rare)
)
return collapsed, note
def _require_cv_assign(params: dict) -> str:
method = params["cv_assign"]
if not isinstance(method, str) or method.strip().lower() not in {"stratified", "round_robin"}:
raise BaselineDataError("cv_assign must be stratified or round_robin")
return method.strip().lower()
def round_robin_group_folds(frame: pd.DataFrame, params: dict) -> pd.DataFrame:
"""Train+val storms only. One row per storm: ``storm_id``, ``fold``.
Co-occurrence groups are sorted, shuffled with ``baselines.seed``, and
dealt round-robin across ``n_splits`` folds. Every storm in a group
gets that group's fold. Test storms are omitted. This is the same deal
as a seed-42 group shuffle with the configured fold count.
"""
if _require_cv_pool(params) != "train_val":
raise BaselineDataError("round_robin folds are assigned on train and val only")
column = str(params["cv_group_column"]).strip()
if column not in frame.columns:
raise BaselineDataError(f"cv_group_column {column} is not on the frame")
n_folds = int(params["n_splits"])
if n_folds < 2:
raise BaselineDataError("n_splits must be at least 2")
pool = frame.loc[frame["split"].astype(str).isin(["train", "val"])].copy()
if pool.empty:
raise BaselineDataError("round_robin folds need train and val rows")
pool["storm_id"] = pool["storm_id"].astype(str)
if bool((pool.groupby("storm_id")["split"].nunique() > 1).any()):
raise LeakageError("a storm is in more than one split")
group_ids = pool[column].map(lambda value: str(int(value)))
if bool((pool.groupby(group_ids)["split"].nunique() > 1).any()):
raise LeakageError("a co-occurrence group is in more than one split")
storms = pool.groupby("storm_id", as_index=False).agg(
group=(column, "first"),
split=("split", "first"),
)
groups = sorted({int(value) for value in storms["group"].tolist()})
order = np.random.default_rng(int(params["seed"])).permutation(len(groups))
shuffled = [groups[int(index)] for index in order]
group_fold = {group: index % n_folds for index, group in enumerate(shuffled)}
folds = pd.DataFrame(
{
"storm_id": storms["storm_id"].astype(str).tolist(),
"fold": [int(group_fold[int(value)]) for value in storms["group"].tolist()],
}
)
test_ids = set(frame.loc[frame["split"].astype(str) == "test", "storm_id"].astype(str))
if set(folds["storm_id"]) & test_ids:
raise LeakageError("round_robin folds include a test storm")
return folds.sort_values(["fold", "storm_id"]).reset_index(drop=True)[["storm_id", "fold"]]
def attach_round_robin_folds(frame: pd.DataFrame, params: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Add ``cv_fold`` on train and val rows. The returned table is the CSV."""
folds = round_robin_group_folds(frame, params)
work = frame.copy()
work["storm_id"] = work["storm_id"].astype(str)
if "cv_fold" in work.columns:
work = work.drop(columns=["cv_fold"])
work = work.merge(folds, on="storm_id", how="left")
work = work.rename(columns={"fold": "cv_fold"})
held = work["split"].astype(str).isin(["train", "val"])
if work.loc[held, "cv_fold"].isna().any():
raise BaselineDataError("a train or val storm has no cv_fold")
if work.loc[work["split"].astype(str) == "test", "cv_fold"].notna().any():
raise LeakageError("a test storm was given a cv_fold")
return work, folds
def _preassigned_folds(frame: pd.DataFrame) -> list[tuple[np.ndarray, np.ndarray]] | None:
if "cv_fold" not in frame.columns or not frame["cv_fold"].notna().all():
return None
folds = frame["cv_fold"].astype(int).to_numpy()
pairs = []
for fold in sorted(set(folds.tolist())):
val_index = np.flatnonzero(folds == fold)
train_index = np.flatnonzero(folds != fold)
if val_index.size == 0 or train_index.size == 0:
raise BaselineDataError(f"cv_fold {fold} does not leave both sides non-empty")
pairs.append((train_index, val_index))
if len(pairs) < 2:
raise BaselineDataError("cv_fold needs at least 2 folds")
return pairs
def cv_pool_frame(
train: pd.DataFrame,
val: pd.DataFrame,
test: pd.DataFrame,
params: dict,
) -> pd.DataFrame:
"""Rows for the grouped CV. ``train_val`` never includes the test split."""
pool = _require_cv_pool(params)
if pool == "train":
source = train.copy()
if source.empty:
raise BaselineDataError("CV pool train is empty")
if set(source["split"].astype(str)) - {"train"}:
raise LeakageError("train CV pool includes a non-train row")
return source.reset_index(drop=True)
source = pd.concat([train, val], ignore_index=True)
if source.empty:
raise BaselineDataError("CV pool train_val is empty")
if set(source["split"].astype(str)) - {"train", "val"}:
raise LeakageError("train_val CV pool includes a row outside train and val")
if set(test["storm_id"].astype(str)) & set(source["storm_id"].astype(str)):
raise LeakageError("train_val CV includes a test storm")
column = str(params["cv_group_column"]).strip()
if column in source.columns and column in test.columns:
assert_no_group_leakage(source, test, group_col=column)
return source
def impute_train_val(X_train: np.ndarray, X_val: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Median imputer fit on the training fold only."""
imputer = SimpleImputer(strategy="median", keep_empty_features=True)
train = np.asarray(imputer.fit_transform(X_train), dtype=np.float64)
val = np.asarray(imputer.transform(X_val), dtype=np.float64)
return (
np.where(np.isfinite(train), train, 0.0),
np.where(np.isfinite(val), val, 0.0),
)
def resample_training_fold(
X_train: np.ndarray, y_train: np.ndarray, seed: int, enabled: bool
) -> tuple[np.ndarray, np.ndarray, str]:
"""SMOTE the training fold only. Validation rows are not an argument."""
if not enabled:
return X_train, y_train, "class_weight"
try:
from imblearn.over_sampling import SMOTE
except ImportError:
return X_train, y_train, "class_weight_imblearn_missing"
labels, counts = np.unique(y_train, return_counts=True)
if len(labels) < 2:
return X_train, y_train, "class_weight_single_class"
minority = int(counts.min())
if minority < 2:
return X_train, y_train, "class_weight_minority_lt_2"
sampler = SMOTE(k_neighbors=min(5, minority - 1), random_state=seed)
try:
resampled_x, resampled_y = sampler.fit_resample(X_train, y_train)
except ValueError:
return X_train, y_train, "class_weight_smote_failed"
return np.asarray(resampled_x), np.asarray(resampled_y), "smote"
def _balanced_weights(y: np.ndarray) -> np.ndarray:
labels, counts = np.unique(y, return_counts=True)
total = len(y)
n_class = len(labels)
table = {
label: total / (n_class * count) for label, count in zip(labels, counts, strict=True)
}
return np.asarray([table[label] for label in y], dtype=np.float64)
def _make_estimator(name: str, task: str, params: dict, class_weight: str | None, n_train: int, seed: int):
weight = "balanced" if class_weight == "balanced" else None
neighbors = max(1, min(int(params["knn_neighbors"]), int(n_train)))
if task == "regression":
if name == "mean":
return MeanRegressor()
if name == "lr":
return LinearRegression()
if name == "ridge":
return Ridge(alpha=float(params["ridge_alpha"]))
if name == "knn":
return KNeighborsRegressor(n_neighbors=neighbors)
if name == "svr":
return SVR(C=float(params["svr_c"]), kernel="rbf")
if name == "rf":
return RandomForestRegressor(
n_estimators=int(params["rf_estimators"]),
max_depth=int(params["rf_max_depth"]),
random_state=seed,
n_jobs=1,
)
if name == "xgboost":
from xgboost import XGBRegressor
return XGBRegressor(
n_estimators=int(params["xgb_estimators"]),
max_depth=int(params["xgb_max_depth"]),
learning_rate=float(params["xgb_learning_rate"]),
random_state=seed,
n_jobs=1,
verbosity=0,
tree_method="hist",
)
else:
if name in _MAJORITY_CLASSIFIERS:
return MostFrequentClassifier()
if name == "logreg":
return LogisticRegression(max_iter=int(params["max_iter"]), class_weight=weight)
if name == "knn":
return KNeighborsClassifier(n_neighbors=neighbors)
if name == "svc":
return SVC(C=float(params["svc_c"]), kernel="rbf", class_weight=weight)
if name == "rf":
return RandomForestClassifier(
n_estimators=int(params["rf_estimators"]),
max_depth=int(params["rf_max_depth"]),
random_state=seed,
n_jobs=1,
class_weight=weight,
)
if name == "xgboost":
from xgboost import XGBClassifier
return XGBClassifier(
n_estimators=int(params["xgb_estimators"]),
max_depth=int(params["xgb_max_depth"]),
learning_rate=float(params["xgb_learning_rate"]),
random_state=seed,
n_jobs=1,
verbosity=0,
tree_method="hist",
)
raise BaselineDataError(f"unknown model {name} for {task}")
def fit_numeric_pipeline(
X_train: np.ndarray,
y_train: np.ndarray,
X_val: np.ndarray,
*,
task: str,
model_name: str,
params: dict,
seed: int,
train_storms,
fitted_storms: set[str],
) -> tuple[np.ndarray, Pipeline, str]:
"""Fit on training rows and predict validation rows.
``train_storms`` is recorded so a caller can prove val and test storms
never entered a fit. SMOTE sees only the imputed training matrix.
"""
fitted_storms.update(str(storm) for storm in np.asarray(train_storms).ravel())
X_train_imp, X_val_imp = impute_train_val(X_train, X_val)
note = "no_smote"
X_fit, y_fit = X_train_imp, np.asarray(y_train).ravel()
if task == "classification" and model_name not in _MAJORITY_CLASSIFIERS:
X_fit, y_fit, note = resample_training_fold(
X_train_imp,
y_fit,
seed,
enabled=bool(params["use_smote"]),
)
if model_name == "knn" and note != "smote":
note = "unweighted_knn"
elif task == "classification":
note = "majority_train_class"
class_weight = None
if (
task == "classification"
and model_name not in _MAJORITY_CLASSIFIERS | {"knn"}
and note != "smote"
):
class_weight = "balanced"
estimator = _make_estimator(
model_name, task, params, class_weight, n_train=len(X_fit), seed=seed
)
sample_weight = None
if model_name == "xgboost" and class_weight == "balanced":
sample_weight = _balanced_weights(y_fit)
estimator = _make_estimator(
model_name, task, params, None, n_train=len(X_fit), seed=seed
)
note = f"{note},xgb_sample_weight"
encoder = None
y_model = y_fit
if task == "classification" and model_name == "xgboost":
encoder = LabelEncoder()
y_model = encoder.fit_transform(np.asarray(y_fit).ravel())
pipeline = Pipeline([("scaler", StandardScaler()), ("model", estimator)])
if sample_weight is None:
pipeline.fit(X_fit, y_model)
else:
pipeline.fit(X_fit, y_model, model__sample_weight=sample_weight)
raw = np.asarray(pipeline.predict(X_val_imp)).ravel()
if encoder is not None:
raw = encoder.inverse_transform(raw.astype(int))
elif task == "regression":
raw = raw.astype(np.float64)
return raw, pipeline, note
def _synthetic_flag(frame: pd.DataFrame) -> str:
"""Track synthetic rows. A missing column is unknown, never a silent no.
Ambiguous values raise. They are not coerced to real observations.
"""
if "is_synthetic" not in frame.columns:
return "unknown"
flags = [parse_is_synthetic(value) for value in frame["is_synthetic"].tolist()]
if not flags:
return "unknown"
if all(flags):
return "yes"
if any(flags):
return "mixed"
return "no"
def _inner_cv_name(params: dict) -> str:
return "round_robin" if _require_cv_assign(params) == "round_robin" else "StratifiedGroupKFold"
def _empty_metric_row(
task: str,
model: str,
note: str,
synthetic: str,
n_features: int,
inner_cv: str = "StratifiedGroupKFold",
) -> dict:
row = {column: np.nan for column in COMPARISON_COLUMNS}
row.update(
{
"task": task,
"model": model,
"role": REFERENCE_ROLE if model == "persistence" else IMAGE_ROLE,
"split_protocol": "train_fit_val_score_test_locked",
"inner_cv": inner_cv,
"n_features": n_features,
"fit_notes": note,
"quote_as_result": "no",
"synthetic": synthetic,
}
)
for column in OPERATIONAL_COLUMNS:
row[column] = np.nan
return row
def _cross_val(
train: pd.DataFrame,
selected: tuple[str, ...],
*,
task: str,
model_name: str,
params: dict,
fitted_storms: set[str],
) -> tuple[float, float, str]:
matrix = model_matrix(train, selected)
groups = _cv_group_ids(train, params)
storms = train["storm_id"].astype(str).to_numpy()
n_splits = int(params["n_splits"])
preassigned = _preassigned_folds(train)
collapse_note = ""
if preassigned is None:
if task == "regression":
stratify = (
train["imd5_class"]
.astype(object)
.where(train["imd5_class"].notna(), "below")
.astype(str)
.to_numpy()
)
else:
stratify = train["imd5_class"].astype(str).to_numpy()
stratify, collapse_note = collapse_rare_stratify_labels(
stratify, groups, n_splits, _require_cv_bool(params)
)
folds = list(
iter_stratified_group_folds(
stratify, groups, n_splits=n_splits, seed=int(params["seed"])
)
)
else:
folds = preassigned
if task == "regression":
target = train["wind_speed_kt"].to_numpy(dtype=np.float64)
else:
target = train["imd5_class"].astype(str).to_numpy()
scores: list[float] = []
notes: list[str] = []
for fold_index, (train_index, val_index) in enumerate(folds):
if set(groups[train_index]) & set(groups[val_index]):
raise LeakageError("a CV group is on both sides of a fold")
predicted, _pipeline, note = fit_numeric_pipeline(
matrix[train_index],
target[train_index],
matrix[val_index],
task=task,
model_name=model_name,
params=params,
seed=int(params["seed"]) + fold_index + 1,
train_storms=storms[train_index],
fitted_storms=fitted_storms,
)
notes.append(note)
if task == "regression":
scores.append(regression_metrics(target[val_index], predicted)["mae_kt"])
else:
scores.append(
classification_metrics(target[val_index], predicted, DEFAULT_NAMES)["macro_f1"]
)
pool = _require_cv_pool(params)
column = str(params["cv_group_column"]).strip()
assign = _require_cv_assign(params)
prefix = f"cv_pool:{pool};cv_group:{column};cv_assign:{assign}"
if collapse_note:
prefix = f"{prefix};{collapse_note}"
return float(np.mean(scores)), float(np.std(scores)), prefix + ";inner_cv:" + "|".join(notes)
def _persistence_metric(frame: pd.DataFrame, task: str) -> float | None:
if frame.empty:
return None
if task == "regression":
predicted = persistence_predictions(frame)
mask = np.isfinite(predicted)
if int(mask.sum()) == 0:
return None
truth = frame["wind_speed_kt"].to_numpy(dtype=np.float64)[mask]
return regression_metrics(truth, predicted[mask])["mae_kt"]
truth = frame["imd5_class"].astype(object).to_numpy()
predicted = persistence_class_predictions(frame)
mask = _known_class_mask(truth, predicted)
if int(mask.sum()) == 0:
return None
return classification_metrics(truth[mask], predicted[mask], DEFAULT_NAMES)["macro_f1"]
def _persistence_cv(frame: pd.DataFrame, task: str, params: dict) -> tuple[float, float, str]:
groups = _cv_group_ids(frame, params)
n_splits = int(params["n_splits"])
preassigned = _preassigned_folds(frame)
collapse_note = ""
if preassigned is None:
stratify = (
frame["imd5_class"]
.astype(object)
.where(frame["imd5_class"].notna(), "below")
.astype(str)
.to_numpy()
)
stratify, collapse_note = collapse_rare_stratify_labels(
stratify, groups, n_splits, _require_cv_bool(params)
)
folds = list(
iter_stratified_group_folds(
stratify, groups, n_splits=n_splits, seed=int(params["seed"])
)
)
else:
folds = preassigned
scores: list[float] = []
for train_index, val_index in folds:
if set(groups[train_index]) & set(groups[val_index]):
raise LeakageError("a CV group is on both sides of a fold")
score = _persistence_metric(frame.iloc[val_index], task)
if score is not None:
scores.append(score)
pool = _require_cv_pool(params)
column = str(params["cv_group_column"]).strip()
assign = _require_cv_assign(params)
prefix = f"cv_pool:{pool};cv_group:{column};cv_assign:{assign}"
if collapse_note:
prefix = f"{prefix};{collapse_note}"
if not scores:
return float("nan"), float("nan"), f"{prefix};inner_cv:no_previous_frame"
return (
float(np.mean(scores)),
float(np.std(scores)),
f"{prefix};inner_cv:previous_same_storm_wind",
)
def _format_cell(value: object) -> str:
if isinstance(value, (float, np.floating)):
number = float(value)
if not np.isfinite(number):
return ""
return f"{number:.4f}"
try:
if pd.isna(value):
return ""
except (TypeError, ValueError):
pass
return str(value).replace("|", "/")
def _markdown_table(frame: pd.DataFrame, columns: tuple[str, ...]) -> str:
header = "| " + " | ".join(columns) + " |"
rule = "| " + " | ".join("---" for _ in columns) + " |"
body = [
"| " + " | ".join(_format_cell(row[column]) for column in columns) + " |"
for _, row in frame.iterrows()
]
return "\n".join([header, rule, *body])
def _comparison_frame(rows: list[dict]) -> pd.DataFrame:
comparison = pd.DataFrame(rows, columns=list(COMPARISON_COLUMNS))
for column in OPERATIONAL_COLUMNS:
comparison[column] = np.nan
comparison["quote_as_result"] = "no"
return comparison
def write_comparison_files(
destination: Path, rows: list[dict], metadata: dict | None
) -> pd.DataFrame:
"""Write the CSV and markdown comparison. Numbers stay `quote_as_result=no`."""
comparison = _comparison_frame(rows)
destination.mkdir(parents=True, exist_ok=True)
comparison.to_csv(destination / "baseline_comparison.csv", index=False)
lines = [
"# Baseline comparison",
"",
BANNER,
"",
"Validation scores. The test split was not used for fitting, selection, or SMOTE.",
PERSISTENCE_NOTE,
"Learned models are sklearn pipelines. SMOTE and class weights stay inside the training fold.",
"The official competition side, when present, stays in `source_split`.",
"`quote_as_result` is no. This is not a forecast and not an operational-readiness claim.",
"Per-class validation RMSE, MAE, and bias are in `per_class_metrics.csv`.",
"Those intervals resample storm IDs. The test split is not in that table.",
"",
]
if metadata:
lines.extend(["## Run", ""])
for key, value in metadata.items():
lines.append(f"- {key}: `{value}`")
lines.append("")
lines.extend([_markdown_table(comparison, _MARKDOWN_COLUMNS), ""])
(destination / "baseline_comparison.md").write_text("\n".join(lines), encoding="utf-8")
(destination / "README.txt").write_text(BANNER + "\n", encoding="utf-8")
if metadata:
(destination / "run_record.json").write_text(
json.dumps(metadata, indent=2, sort_keys=True) + "\n", encoding="utf-8"
)
record = [
"# Baseline run",
"",
BANNER,
"",
"Official competition labels stay in `source_split`. The modeling split is storm-wise.",
"The test split was not fit. `quote_as_result` is no.",
PERSISTENCE_NOTE,
"Per-class validation metrics are in `per_class_metrics.csv`. Intervals resample storm IDs. The test split is not scored there.",
"A `wind_averaging` column, when present, is grouped and not converted. An `on_fix` column, when present, adds rows on a best-track fix.",
"Classes with fewer than 3 storms are marked indicative (n_storms<3).",
"",
]
if str(metadata.get("wind_averaging")) == "3-min" and str(metadata.get("wind_averaging_s")) == "180":
record.extend(
[
"All metrics use raw 3-minute IMD labels. wind_averaging is 3-min and wind_averaging_s is 180 on every row. There is no 1-minute conversion.",
"",
]
)
for key, value in metadata.items():
record.append(f"- {key}: `{value}`")
record.append("")
(destination / "RUN.md").write_text("\n".join(record), encoding="utf-8")
return comparison
def write_per_class_files(destination: Path, rows: list[dict]) -> pd.DataFrame:
"""Write the validation per-class table. Numbers stay ``quote_as_result=no``."""
frame = pd.DataFrame(rows, columns=list(PER_CLASS_COLUMNS))
if not frame.empty:
if not frame["split"].astype(str).eq("val").all():
raise LeakageError("per-class table contains a split other than val")
frame["quote_as_result"] = "no"
destination.mkdir(parents=True, exist_ok=True)
frame.to_csv(destination / "per_class_metrics.csv", index=False)
lines = [
"# Per-class validation metrics",
"",
BANNER,
"",
"Validation split only. The test split was not scored.",
"Bias is prediction minus true wind.",
"Intervals are 95% percentile bootstrap confidence intervals.",
"Each resample draws storm IDs with replacement and keeps every row of a drawn storm.",
"Rows are not resampled on their own.",
"Bins are this project's grouping, IMD-style names, not an IMD warning.",
"A `wind_averaging` column, when present, is copied through and grouped. Periods are not converted.",
"An `on_fix` column, when present, adds `subset=on_fix` for rows on a best-track fix.",
"Classes with fewer than 3 storms are marked `indicative (n_storms<3)`.",
"When per-storm breakdown is on, those classes also list each storm.",
"`quote_as_result` is no. This is not a forecast and not an operational-readiness claim.",
"",
]
if frame.empty:
lines.extend(["No regression validation rows were scored.", ""])
else:
lines.extend([_markdown_table(frame, _PER_CLASS_MD_COLUMNS), ""])
(destination / "per_class_metrics.md").write_text("\n".join(lines), encoding="utf-8")
return frame
def _bootstrap_settings(params: dict) -> tuple[int, int, bool]:
resamples = params["bootstrap_resamples"]
if isinstance(resamples, bool) or not isinstance(resamples, (int, np.integer)):
raise BaselineDataError("bootstrap_resamples must be a positive integer")
n_resamples = int(resamples)
if n_resamples < 1:
raise BaselineDataError("bootstrap_resamples must be a positive integer")
breakdown = params["per_storm_breakdown"]
if not isinstance(breakdown, bool):
raise BaselineDataError("per_storm_breakdown must be true or false")
return n_resamples, int(params["seed"]), breakdown
def _record_regression_classes(
rows: list[dict],
model_name: str,
frame: pd.DataFrame,
predicted: np.ndarray,
*,
n_resamples: int,
seed: int,
synthetic: str,
per_storm_breakdown: bool,
) -> None:
"""Score one regression model on the validation rows it was given."""
from src.evaluate import intensity_class_evaluation
if "split" not in frame.columns:
raise BaselineDataError("per-class evaluation needs a split column")
if len(frame) != len(np.asarray(predicted)):
raise BaselineDataError("per-class predictions must align with the validation rows")
observed = set(frame["split"].astype(str).unique())
if observed - {"val"}:
raise LeakageError(
"per-class evaluation scores the validation split only; "
f"refusing {sorted(observed - {'val'})}"
)
table = intensity_class_evaluation(
frame["wind_speed_kt"].to_numpy(dtype=np.float64),
np.asarray(predicted, dtype=np.float64),
frame["storm_id"].to_numpy(),
frame["imd5_class"].to_numpy(),
frame["split"].astype(str).to_numpy(),
wind_averaging=(
frame["wind_averaging"].to_numpy() if "wind_averaging" in frame.columns else None
),
on_fix=frame["on_fix"].to_numpy() if "on_fix" in frame.columns else None,
n_resamples=n_resamples,
seed=seed,
per_storm_breakdown=per_storm_breakdown,
)
for record in table.to_dict(orient="records"):
record["task"] = "regression"
record["model"] = model_name
record["split"] = "val"
record["quote_as_result"] = "no"
record["synthetic"] = synthetic
rows.append(record)
def _score_persistence(
train: pd.DataFrame,
val: pd.DataFrame,
task: str,
params: dict,
synthetic: str,
n_features: int,
destination: Path,
class_rows: list[dict] | None = None,
cv_frame: pd.DataFrame | None = None,
) -> dict:
"""Score the previous same-storm wind. Nothing is fit and val storms stay out.
The headline score uses ``val`` only. ``cv_frame`` is the grouped-CV pool.
"""
cv_mean, cv_std, cv_note = _persistence_cv(train if cv_frame is None else cv_frame, task, params)
note = (
"reference_baseline;previous_best_track_label;not_imagery;"
f"previous_same_storm_wind;not_a_feature;no_pipeline;{cv_note}"
)
row = _empty_metric_row(
task, "persistence", note, synthetic, n_features, inner_cv=_inner_cv_name(params)
)
if task == "regression":
train_pred = persistence_predictions(train)
val_pred = persistence_predictions(val)
train_mask = np.isfinite(train_pred)
val_mask = np.isfinite(val_pred)
if int(val_mask.sum()) == 0:
row["fit_notes"] = f"{note};no_previous_frame"
return row
truth = val["wind_speed_kt"].to_numpy(dtype=np.float64)[val_mask]
predicted = val_pred[val_mask]
scores = regression_metrics(truth, predicted)
by_class = metrics_by_class(truth, predicted, val["imd5_class"].to_numpy()[val_mask])
row.update(
{
"n_train_rows": int(train_mask.sum()),
"n_val_rows": int(val_mask.sum()),
"n_train_storms": int(train.iloc[np.flatnonzero(train_mask)]["storm_id"].nunique()),
"n_val_storms": int(val.iloc[np.flatnonzero(val_mask)]["storm_id"].nunique()),
"mae_kt": scores["mae_kt"],
"rmse_kt": scores["rmse_kt"],
"bias_kt": scores["bias_kt"],
"cv_mae_kt_mean": cv_mean,
"cv_mae_kt_std": cv_std,
}
)
for class_name in DEFAULT_NAMES:
class_scores = by_class.get(class_name)
row[f"mae_{class_name}"] = np.nan if class_scores is None else class_scores["mae_kt"]
save_regression_scatter(
truth,
predicted,
destination / "scatter_persistence.png",
title="persistence val scatter — not a forecast",
)
if class_rows is not None:
n_resamples, seed, breakdown = _bootstrap_settings(params)
scored = val.iloc[np.flatnonzero(val_mask)]
_record_regression_classes(
class_rows,
"persistence",
scored,
predicted,
n_resamples=n_resamples,
seed=seed,
synthetic=synthetic,
per_storm_breakdown=breakdown,
)
return row
train_truth = train["imd5_class"].astype(object).to_numpy()
val_truth = val["imd5_class"].astype(object).to_numpy()
train_pred = persistence_class_predictions(train)
val_pred = persistence_class_predictions(val)
train_mask = _known_class_mask(train_truth, train_pred)
val_mask = _known_class_mask(val_truth, val_pred)
if int(val_mask.sum()) == 0:
row["fit_notes"] = f"{note};no_previous_class"
return row
truth = val_truth[val_mask].astype(str)
predicted = val_pred[val_mask].astype(str)
scores = classification_metrics(truth, predicted, DEFAULT_NAMES)
row.update(
{
"n_train_rows": int(train_mask.sum()),
"n_val_rows": int(val_mask.sum()),
"n_train_storms": int(train.iloc[np.flatnonzero(train_mask)]["storm_id"].nunique()),
"n_val_storms": int(val.iloc[np.flatnonzero(val_mask)]["storm_id"].nunique()),
"macro_f1": scores["macro_f1"],
"cv_macro_f1_mean": cv_mean,
"cv_macro_f1_std": cv_std,
}
)
for class_name in DEFAULT_NAMES:
row[f"recall_{class_name}"] = scores[f"recall_{class_name}"]
save_confusion_matrix(
truth,
predicted,
destination / "confusion_persistence.png",
title="persistence val counts — not a forecast",
)
return row
def run_baselines(
frame: pd.DataFrame,
feature_names: tuple[str, ...] | list[str],
config: dict,
out_dir: str | Path,
metadata: dict | None = None,
) -> BaselineReport:
"""Select on train, compare models on val, and leave the test split locked."""
required = {"split", "storm_id", "wind_speed_kt", "imd5_class", "sample_id"}
missing = required - set(frame.columns)
if missing:
raise BaselineDataError(f"baseline frame is missing {sorted(missing)}")
unknown = set(frame["split"].astype(str).unique()) - {"train", "val", "test"}
if unknown:
raise BaselineDataError(f"unknown splits: {sorted(unknown)}")
names = tuple(feature_names)
assert_no_forbidden_inputs(names, "refusing to train on")
parts = [frame[frame["split"] == name] for name in ("train", "val", "test")]
assert_no_group_leakage(*parts)
train = parts[0].copy()
val = parts[1].copy()
test = parts[2].copy()
if train.empty or val.empty:
raise BaselineDataError("train and val must both be non-empty")
if train["storm_id"].nunique() < 3:
raise BaselineDataError("need at least 3 training storms")
params = baseline_params(config)
n_resamples, bootstrap_seed, per_storm_breakdown = _bootstrap_settings(params)
choose = selection_params(config)
selection = select_features(
train,
names,
train["wind_speed_kt"].to_numpy(dtype=np.float64),
source_split="train",
correlation_threshold=choose["correlation_threshold"],
max_features=choose["max_features"],
method=choose["method"],
n_estimators=choose["n_estimators"],
seed=choose["seed"],
)
if selection.train_storms != frozenset(train["storm_id"].astype(str)):
raise LeakageError("feature selection used storms outside the training split")
selected = selection.names
if not selected:
raise BaselineDataError("feature selection returned no columns")
destination = Path(out_dir)
destination.mkdir(parents=True, exist_ok=True)
synthetic = _synthetic_flag(frame)
fitted: set[str] = set()
cv_fitted: set[str] = set()
pool = _require_cv_pool(params)
cv_bucket = fitted if pool == "train" else cv_fitted
if _require_cv_assign(params) == "round_robin":
combined = pd.concat([train, val, test], ignore_index=True)
combined, fold_table = attach_round_robin_folds(combined, params)
fold_table.to_csv(destination / "cv_folds.csv", index=False)
train = combined.loc[combined["split"].astype(str) == "train"].reset_index(drop=True)
val = combined.loc[combined["split"].astype(str) == "val"].reset_index(drop=True)
test = combined.loc[combined["split"].astype(str) == "test"].reset_index(drop=True)
cv_reg = cv_pool_frame(train, val, test, params)
rows: list[dict] = []
class_rows: list[dict] = []
for model_name in list(params["regression_models"]):
logger.info("Regression baseline %s", model_name)
if model_name == "persistence":
rows.append(
_score_persistence(
train,
val,
"regression",
params,
synthetic,
len(selected),
destination,
class_rows,
cv_frame=cv_reg,
)
)
write_comparison_files(destination, rows, metadata)
write_per_class_files(destination, class_rows)
continue
if model_name == "xgboost" and not xgboost_available():
rows.append(
_empty_metric_row(
"regression",
model_name,
"not_installed",
synthetic,
len(selected),
inner_cv=_inner_cv_name(params),
)
)
write_comparison_files(destination, rows, metadata)
continue
cv_mean, cv_std, cv_note = _cross_val(
cv_reg, selected, task="regression", model_name=model_name, params=params, fitted_storms=cv_bucket
)
predicted, _pipeline, note = fit_numeric_pipeline(
model_matrix(train, selected),
train["wind_speed_kt"].to_numpy(dtype=np.float64),
model_matrix(val, selected),
task="regression",
model_name=model_name,
params=params,
seed=int(params["seed"]),
train_storms=train["storm_id"].astype(str),
fitted_storms=fitted,
)
scores = regression_metrics(val["wind_speed_kt"], predicted)
by_class = metrics_by_class(
val["wind_speed_kt"].to_numpy(), predicted, val["imd5_class"].to_numpy()
)
row = _empty_metric_row(
"regression",
model_name,
f"{note};{cv_note}",
synthetic,
len(selected),
inner_cv=_inner_cv_name(params),
)
row.update(
{
"n_train_rows": int(len(train)),
"n_val_rows": int(len(val)),
"n_train_storms": int(train["storm_id"].nunique()),
"n_val_storms": int(val["storm_id"].nunique()),
"mae_kt": scores["mae_kt"],
"rmse_kt": scores["rmse_kt"],
"bias_kt": scores["bias_kt"],
"cv_mae_kt_mean": cv_mean,
"cv_mae_kt_std": cv_std,
}
)
for class_name in DEFAULT_NAMES:
class_scores = by_class.get(class_name)
row[f"mae_{class_name}"] = np.nan if class_scores is None else class_scores["mae_kt"]
rows.append(row)
save_regression_scatter(
val["wind_speed_kt"].to_numpy(),
predicted,
destination / f"scatter_{model_name}.png",
title=f"{model_name} val scatter — not a forecast",
)
_record_regression_classes(
class_rows,
model_name,
val,
predicted,
n_resamples=n_resamples,
seed=bootstrap_seed,
synthetic=synthetic,
per_storm_breakdown=per_storm_breakdown,
)
write_comparison_files(destination, rows, metadata)
write_per_class_files(destination, class_rows)
train_cls = train[train["imd5_class"].notna()].copy()
val_cls = val[val["imd5_class"].notna()].copy()
if train_cls.empty or val_cls.empty:
raise BaselineDataError("classification needs labeled rows in train and val")
cv_cls = cv_pool_frame(train_cls, val_cls, test, params)
for model_name in list(params["classification_models"]):
logger.info("Classification baseline %s", model_name)
if model_name == "persistence":
rows.append(
_score_persistence(
train,
val,
"classification",
params,
synthetic,
len(selected),
destination,
cv_frame=cv_cls,
)
)
write_comparison_files(destination, rows, metadata)
continue
if model_name == "xgboost" and not xgboost_available():
rows.append(
_empty_metric_row(
"classification",
model_name,
"not_installed",
synthetic,
len(selected),
inner_cv=_inner_cv_name(params),
)
)
write_comparison_files(destination, rows, metadata)
continue
cv_mean, cv_std, cv_note = _cross_val(
cv_cls,
selected,
task="classification",
model_name=model_name,
params=params,
fitted_storms=cv_bucket,
)
predicted, _pipeline, note = fit_numeric_pipeline(
model_matrix(train_cls, selected),
train_cls["imd5_class"].astype(str).to_numpy(),
model_matrix(val_cls, selected),
task="classification",
model_name=model_name,
params=params,
seed=int(params["seed"]),
train_storms=train_cls["storm_id"].astype(str),
fitted_storms=fitted,
)
scores = classification_metrics(
val_cls["imd5_class"].astype(str).to_numpy(), predicted, DEFAULT_NAMES
)
row = _empty_metric_row(
"classification",
model_name,
f"{note};{cv_note}",
synthetic,
len(selected),
inner_cv=_inner_cv_name(params),
)
row.update(
{
"n_train_rows": int(len(train_cls)),
"n_val_rows": int(len(val_cls)),
"n_train_storms": int(train_cls["storm_id"].nunique()),
"n_val_storms": int(val_cls["storm_id"].nunique()),
"macro_f1": scores["macro_f1"],
"cv_macro_f1_mean": cv_mean,
"cv_macro_f1_std": cv_std,
}
)
for class_name in DEFAULT_NAMES:
row[f"recall_{class_name}"] = scores[f"recall_{class_name}"]
rows.append(row)
save_confusion_matrix(
val_cls["imd5_class"].astype(str).to_numpy(),
predicted,
destination / f"confusion_{model_name}.png",
title=f"{model_name} val counts — not a forecast",
)
write_comparison_files(destination, rows, metadata)
comparison = write_comparison_files(destination, rows, metadata)
write_per_class_files(destination, class_rows)
payload = {
"source_split": selection.source_split,
"names": list(selection.names),
"importances": selection.importances,
"dropped_variance": list(selection.dropped_variance),
"dropped_correlation": list(selection.dropped_correlation),
"train_storms": sorted(selection.train_storms),
"quote_as_result": "no",
}
(destination / "selected_features.json").write_text(
json.dumps(payload, indent=2), encoding="utf-8"
)
save_feature_importance(
selection.importances,
destination / "feature_importance.png",
title="Train-only selection scores — not a skill claim",
)
report = BaselineReport(
comparison=comparison,
selected_features=selected,
train_storms=frozenset(train["storm_id"].astype(str)),
val_storms=frozenset(val["storm_id"].astype(str)),
test_storms=frozenset(test["storm_id"].astype(str)),
fitted_storms=frozenset(fitted),
n_rows_used_for_selection=int(len(train)),
out_dir=destination,
)
leaked = report.fitted_storms & (report.val_storms | report.test_storms)
if leaked:
raise LeakageError(f"fit saw held-out storms: {sorted(leaked)}")
if not report.fitted_storms <= report.train_storms:
raise LeakageError("fit saw storms that are not in the training split")
if pool == "train_val":
cv_test = frozenset(cv_fitted) & report.test_storms
if cv_test:
raise LeakageError(f"grouped CV saw test storms: {sorted(cv_test)}")
return report
def frame_for_storm_split(frame: pd.DataFrame, config: dict) -> pd.DataFrame:
"""Assign a storm-wise split. Drop any incoming ``split`` column first.
``source_split`` is left untouched. It is the official competition side
and is not the modeling split.
"""
split_cfg = config["split"]
strategy = str(split_cfg["strategy"]).lower().strip()
if "year_holdout" in strategy:
raise BaselineDataError(
"year_holdout is not a baseline split and is not run; "
f"refusing split.strategy={strategy}"
)
if strategy != "storm_wise":
raise BaselineDataError(
"baselines use storm-wise splits only via src.splits.assign_storms; "
f"refusing split.strategy={strategy}"
)
work = frame.copy()
if "split" in work.columns:
work = work.drop(columns=["split"])
holdout_basin = split_cfg["holdout_basin"] or None
assigned = assign_storms(
work,
"storm_wise",
test_fraction=float(split_cfg["test_fraction"]),
val_fraction=float(split_cfg["val_fraction"]),
seed=int(split_cfg["seed"]),
holdout_years=[int(year) for year in (split_cfg["holdout_years"] or [])],
holdout_basin=None if holdout_basin in {None, ""} else str(holdout_basin),
)
if "source_split" in frame.columns and "source_split" not in assigned.columns:
raise BaselineDataError("source_split was dropped while assigning storms")
return assigned
def frame_for_recorded_split(frame: pd.DataFrame) -> pd.DataFrame:
"""Keep the manifest ``split`` column. Do not redraw storms.
A ``cv_group`` column must not cross modeling splits. ``source_split``
stays a reference.
"""
if "split" not in frame.columns:
raise BaselineDataError("recorded split needs a split column on the manifest")
work = frame.copy()
unknown = set(work["split"].astype(str).unique()) - {"train", "val", "test"}
if unknown:
raise BaselineDataError(f"recorded split has unknown values: {sorted(unknown)}")
parts = [work.loc[work["split"].astype(str) == name] for name in ("train", "val", "test")]
for name, part in zip(("train", "val", "test"), parts, strict=True):
if part.empty:
raise BaselineDataError(f"recorded split has no {name} rows")
assert_no_group_leakage(*parts)
if "cv_group" in work.columns:
assert_no_group_leakage(*parts, group_col="cv_group")
return work
def _git_commit() -> str:
try:
return subprocess.check_output(
["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL
).strip()
except (OSError, subprocess.CalledProcessError):
return "unknown"
def _assignment_digest(frame: pd.DataFrame, group_column: str) -> str:
groups = (
frame[group_column].astype(str)
if group_column in frame.columns
else pd.Series([""] * len(frame), index=frame.index)
)
lines = [
f"{sample}|{split}|{group}"
for sample, split, group in zip(
frame["sample_id"].astype(str), frame["split"].astype(str), groups, strict=True
)
]
return hashlib.sha256("\n".join(lines).encode()).hexdigest()
def _count_block(frame: pd.DataFrame, column: str) -> str:
parts = []
for name in sorted(frame[column].astype(str).unique()):
part = frame.loc[frame[column].astype(str) == name]
parts.append(f"{name}:rows={len(part)},storms={part['storm_id'].nunique()}")
return "; ".join(parts)
def _run_metadata(
assigned: pd.DataFrame,
table: pd.DataFrame,
config: dict,
*,
command: str | None,
manifest_command: str | None,
manifest: Path,
dropped: int,
workers: int,
) -> dict[str, str]:
both = 0
if "source_split" in assigned.columns:
sides = [
set(assigned.loc[assigned["source_split"].astype(str) == side, "storm_id"].astype(str))
for side in sorted(assigned["source_split"].astype(str).unique())
]
both = len(set.intersection(*sides)) if len(sides) > 1 else 0
strategy = str(config["split"]["strategy"]).strip().lower()
recorded = strategy == "recorded"
metadata = {
"command": command or "",
"manifest_command": manifest_command or "",
"manifest": str(manifest),
"git_commit": _git_commit(),
"split_strategy": strategy,
"split_seed": "not_used" if recorded else str(int(config["split"]["seed"])),
"baseline_seed": str(int(config["baselines"]["seed"])),
"feature_selection_seed": str(int(config["features"]["selection"]["seed"])),
"test_fraction": "not_used" if recorded else str(float(config["split"]["test_fraction"])),
"val_fraction": "not_used" if recorded else str(float(config["split"]["val_fraction"])),
"cv_pool": str(config["baselines"]["cv_pool"]),
"cv_group_column": str(config["baselines"]["cv_group_column"]),
"cv_collapse_rare": str(bool(config["baselines"]["cv_collapse_rare"])),
"cv_assign": str(config["baselines"]["cv_assign"]),
"workers": str(int(workers)),
"rows": str(int(len(assigned))),
"storms": str(int(assigned["storm_id"].nunique())),
"rows_after_features": str(int(len(table))),
"storms_after_features": str(int(table["storm_id"].nunique())),
"modeling_split": _count_block(assigned, "split"),
"dropped_cross_split_links": str(int(dropped)),
"use_smote": str(bool(config["baselines"]["use_smote"])),
"bootstrap_resamples": str(int(config["baselines"]["bootstrap_resamples"])),
"per_storm_breakdown": str(bool(config["baselines"]["per_storm_breakdown"])),
"per_class_eval_split": "val",
"per_class_resample": "storm_id",
"quote_as_result": "no",
"official_split_used_for_training": "no",
}
if "source_split" in assigned.columns:
metadata["source_split"] = _count_block(assigned, "source_split")
metadata["storms_on_both_source_sides"] = str(both)
if "wind_averaging" in assigned.columns:
metadata["wind_averaging"] = ",".join(
sorted({str(value) for value in assigned["wind_averaging"].tolist()})
)
if "wind_averaging_s" in assigned.columns:
metadata["wind_averaging_s"] = ",".join(
sorted({str(int(value)) for value in pd.to_numeric(assigned["wind_averaging_s"]).tolist()})
)
summary_path = manifest.with_suffix(manifest.suffix + ".summary.json")
if summary_path.is_file():
summary = json.loads(summary_path.read_text(encoding="utf-8"))
for key in (
"label_scope",
"comparability",
"metrics_use",
"on_fix_definition",
"augmented_dropped",
"default_excluded_originals",
"flagged_not_default_originals",
"drop_flagged",
"on_fix_rows",
"on_fix_false_rows",
"on_fix_unknown_rows",
"near_land_unknown_rows",
"distance_to_land_unknown_rows",
"frame_flags_source",
"originals_before_exclusions",
"rows_written",
"pixel_units",
"year_holdout_2019",
"zenodo_doi",
"zip_md5",
):
if key in summary:
metadata[key] = summary[key] if isinstance(summary[key], str) else json.dumps(summary[key])
return metadata
def _cache_key(manifest: Path, config: dict, frame: pd.DataFrame | None = None) -> dict[str, object]:
strategy = str(config["split"]["strategy"]).strip().lower()
if strategy == "recorded":
if frame is None:
raise BaselineDataError("recorded split cache key needs the assigned frame")
return {
"manifest": str(manifest.resolve()),
"strategy": "recorded",
"assignments": _assignment_digest(frame, str(config["baselines"]["cv_group_column"])),
"feature_seed": int(config["features"]["selection"]["seed"]),
"calibrated": bool(config["features"]["calibrated"]),
}
return {
"manifest": str(manifest.resolve()),
"strategy": "storm_wise",
"split_seed": int(config["split"]["seed"]),
"test_fraction": float(config["split"]["test_fraction"]),
"val_fraction": float(config["split"]["val_fraction"]),
"feature_seed": int(config["features"]["selection"]["seed"]),
}
def restrict_to_orig_size(
table: pd.DataFrame, manifest_path: str | Path, orig_size: int
) -> tuple[pd.DataFrame, dict[str, str]]:
"""Keep rows whose manifest ``orig_size`` matches. The ``split`` column stays.
The storm assignment is not recomputed. Storms that have no frame of this
size drop out of the scored table; the returned note lists them.
"""
raw = pd.read_csv(manifest_path, usecols=["sample_id", "orig_size"])
raw["sample_id"] = raw["sample_id"].astype(str)
sizes = raw.drop_duplicates("sample_id").set_index("sample_id")["orig_size"]
work = table.copy()
work["sample_id"] = work["sample_id"].astype(str)
if "split" not in work.columns:
raise BaselineDataError("orig_size filter needs the cached storm split")
parent_counts = {
name: {
"rows": int((work["split"].astype(str) == name).sum()),
"storms": int(work.loc[work["split"].astype(str) == name, "storm_id"].nunique()),
}
for name in ("train", "val", "test")
}
work["orig_size"] = pd.to_numeric(work["sample_id"].map(sizes), errors="coerce")
missing = int(work["orig_size"].isna().sum())
if missing:
raise BaselineDataError(f"{missing} feature rows have no orig_size on the manifest")
kept = work.loc[work["orig_size"].astype(int) == int(orig_size)].copy()
if kept.empty:
raise BaselineDataError(f"no rows with orig_size={orig_size}")
absent = {}
for name in ("train", "val", "test"):
parent = set(work.loc[work["split"].astype(str) == name, "storm_id"].astype(str))
scored = set(kept.loc[kept["split"].astype(str) == name, "storm_id"].astype(str))
absent[name] = sorted(parent - scored)
note = {
"orig_size_kept": str(int(orig_size)),
"parent_split": _count_block(work, "split"),
"scored_split": _count_block(kept, "split"),
"val_storms_in_parent_split": str(parent_counts["val"]["storms"]),
"val_storms_with_orig_size": str(
int(kept.loc[kept["split"].astype(str) == "val", "storm_id"].nunique())
),
"val_storms_without_orig_size": str(len(absent["val"])),
"val_storm_ids_without_orig_size": ",".join(absent["val"]),
"like_for_like": (
f"Phase 1 CNN trains only on orig_size {int(orig_size)} frames. "
"This table keeps the storm split already stored on the feature cache "
"and scores only those frames. Persistence remains a reference baseline "
"that uses the previous best-track label, not the imagery."
),
}
return kept, note
def run_from_config(
config_path: str | Path,
manifest_path: str | Path | None = None,
out_dir: str | Path | None = None,
workers: int = 1,
feature_cache: str | Path | None = None,
command: str | None = None,
manifest_command: str | None = None,
orig_size: int | None = None,
) -> BaselineReport:
"""Run the Phase 2 comparison. Does not download imagery.
``storm_wise`` redraws storms. ``recorded`` keeps the manifest split.
A ``source_split`` column is reference only. ``year_holdout`` is refused.
"""
config = load_config(config_path)
strategy = str(config["split"]["strategy"]).strip().lower()
if "year_holdout" in strategy:
raise BaselineDataError(
"year_holdout is not a baseline split and is not run; "
f"refusing split.strategy={strategy}"
)
manifest = Path(manifest_path or config["paths"]["manifest"])
if not manifest.is_file():
raise FileNotFoundError(
f"missing manifest {manifest}. Point paths.manifest at a local file. "
"This command does not download NASA, TCIR, or INSAT imagery."
)
destination = Path(out_dir) if out_dir else Path(config["paths"]["reports"]) / "baselines"
loaded = load_manifest(manifest)
if strategy == "recorded":
frame = frame_for_recorded_split(loaded)
elif strategy == "storm_wise":
frame = frame_for_storm_split(loaded, config)
else:
raise BaselineDataError(
"baselines accept storm_wise or recorded splits; "
f"refusing split.strategy={strategy}"
)
spec = FeatureSpec.from_config(config)
cache = Path(feature_cache) if feature_cache else None
meta_path = cache.with_suffix(cache.suffix + ".meta.json") if cache else None
key = _cache_key(manifest, config, frame)
table = None
dropped = 0
if cache and cache.is_file() and meta_path and meta_path.is_file():
saved = json.loads(meta_path.read_text(encoding="utf-8"))
if saved.get("key") == key:
table = pd.read_csv(cache)
dropped = int(saved.get("dropped_cross_split_links", 0))
logger.info("Loaded feature cache %s", cache)
if table is None:
checkpoint = cache.with_suffix(cache.suffix + ".images.csv") if cache else None
table, dropped = extract_table(
frame, manifest, spec, config, workers=workers, image_checkpoint=checkpoint
)
if cache:
cache.parent.mkdir(parents=True, exist_ok=True)
table.to_csv(cache, index=False)
meta_path.write_text(
json.dumps({"key": key, "dropped_cross_split_links": int(dropped)}, indent=2),
encoding="utf-8",
)
logger.info("Dropped %s cross-split temporal links", dropped)
if orig_size is not None:
table, size_note = restrict_to_orig_size(table, manifest, int(orig_size))
logger.info("Kept orig_size %s: %s", orig_size, size_note["scored_split"])
else:
size_note = {}
metadata = _run_metadata(
frame,
table,
config,
command=command,
manifest_command=manifest_command,
manifest=manifest,
dropped=dropped,
workers=workers,
)
metadata.update(size_note)
return run_baselines(table, spec.feature_names(), config, destination, metadata=metadata)
def extract_table(
frame,
manifest,
spec: FeatureSpec,
config: dict,
workers: int = 1,
image_checkpoint: str | Path | None = None,
):
return extract_feature_table(
frame,
manifest,
spec,
max_missing_fraction=float(config["data"]["max_missing_fraction"]),
workers=workers,
image_checkpoint=image_checkpoint,
)
def main(argv: list[str] | None = None) -> None:
logging.basicConfig(level=logging.INFO, format="%(message)s")
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--config", type=Path, required=True)
parser.add_argument("--manifest", type=Path, default=None)
parser.add_argument("--out", type=Path, default=None)
parser.add_argument("--workers", type=int, default=1)
parser.add_argument("--feature-cache", type=Path, default=None)
parser.add_argument(
"--manifest-command",
default="",
help="Exact command that built the manifest. Recorded in RUN.md. This command does not run it.",
)
parser.add_argument(
"--orig-size",
type=int,
default=None,
help="Score only frames with this manifest orig_size. Keeps the cached storm split.",
)
args = parser.parse_args(argv)
command = "python -m src.baselines " + " ".join(shlex.quote(arg) for arg in (argv if argv is not None else sys.argv[1:]))
report = run_from_config(
args.config,
args.manifest,
args.out,
workers=args.workers,
feature_cache=args.feature_cache,
command=command,
manifest_command=args.manifest_command or None,
orig_size=args.orig_size,
)
print(BANNER)
print(f"Wrote {report.out_dir / 'baseline_comparison.csv'}")
print(f"Wrote {report.out_dir / 'baseline_comparison.md'}")
print(f"Wrote {report.out_dir / 'per_class_metrics.csv'}")
print(f"Wrote {report.out_dir / 'per_class_metrics.md'}")
print("quote_as_result=no for every row. Test storms were not fit or scored.")
if __name__ == "__main__":
main()
|