Skip to content

Commit 5d8163d

Browse files
committed
Use mean fold validation scores and preserve repeated-CV artifacts
1 parent 0b36572 commit 5d8163d

17 files changed

Lines changed: 557 additions & 85 deletions

File tree

‎docs/docs/features/algorithms.md‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -233,16 +233,24 @@ and **300 rounds of patience**, subject to round and time limits. Round 1 is
233233
also a candidate so very short runs and boosters that exhaust possible splits
234234
can participate. The full booster, including patience rounds, is retained until
235235
all folds finish. Only checkpoints available in every fold are considered;
236-
shorter folds are not extended. Selection optimizes the existing **pooled OOF
237-
metric**, with the smaller count winning exact ties.
236+
shorter folds are not extended. Selection optimizes the **mean of the fold
237+
scores**, with the smaller count winning exact ties.
238238

239239
After selection, every fold model is reduced to the selected prefix. OOF
240240
predictions, validation scores, thresholds, reports and subsequent ensembles
241241
use that same prefix. `shared_boosting.json` and `shared_boosting_scores.csv`
242242
record the stopping counts and selection curve. Model reports and the
243-
leaderboard include the **mean fold score** alongside the pooled score.
244-
`metric_value` remains the pooled selection score; `mean_fold_metric_value`
245-
is the additional reported score for these models.
243+
leaderboard use the **mean fold score** for selection. The pooled score remains
244+
in the shared boosting report as a diagnostic.
245+
246+
For all newly trained models, `metric_value` is the arithmetic mean of the
247+
validation scores from every fold and repeat. Each fold has equal weight;
248+
sample weights, when provided, apply within each fold. Ensemble selection
249+
combines candidate predictions separately within each fold, then averages the
250+
fold scores in the same way. Predictions averaged across repeats are still
251+
available for stacking and additional reports, but do not determine the
252+
selection score. Individual fold predictions are saved in
253+
`predictions_validation_folds.csv` so this also works after reloading.
246254

247255
Counts refer to boosting rounds, which may contain multiple trees for
248256
multiclass models. XGBoost's zero-based `best_iteration` is stored as the count

‎supervised/algorithms/_pytabkit_compat.py‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import warnings
1414
from contextlib import ExitStack, contextmanager
1515

16+
import numpy as np
1617
from sklearn.utils.validation import check_array, check_X_y
1718

1819

@@ -48,6 +49,28 @@ def _leaf_spec():
4849
return tree_flatten(None)[1]
4950

5051

52+
class _WritableTensorTorch:
53+
"""Adapt only pytabkit's tensor conversions, without patching torch globally."""
54+
55+
def __init__(self, module):
56+
self._module = module
57+
self._thread = threading.get_ident()
58+
59+
def __getattr__(self, name):
60+
return getattr(self._module, name)
61+
62+
def as_tensor(self, data, *args, **kwargs):
63+
# pandas Copy-on-Write can return read-only arrays even after copying
64+
# the input frame. PyTorch must not share those arrays' storage.
65+
if (
66+
threading.get_ident() == self._thread
67+
and isinstance(data, np.ndarray)
68+
and not data.flags.writeable
69+
):
70+
data = data.copy()
71+
return self._module.as_tensor(data, *args, **kwargs)
72+
73+
5174
class _BackendLogFilter(logging.Filter):
5275
def __init__(self):
5376
super().__init__()
@@ -69,6 +92,7 @@ def backend_context():
6992
for module, name, replacement in [
7093
(sklearn_base, "check_X_y_wrapper", _check_X_y),
7194
(sklearn_base, "check_array_wrapper", _check_array),
95+
(sklearn_base, "torch", _WritableTensorTorch(sklearn_base.torch)),
7296
(_pytree, "LeafSpec", _leaf_spec),
7397
]:
7498
original = getattr(module, name)

‎supervised/callbacks/early_stopping.py‎

Lines changed: 19 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,11 @@
77
from supervised.callbacks.callback import Callback
88
from supervised.utils.config import LOG_LEVEL
99
from supervised.utils.metric import Metric
10+
from supervised.utils.validation_scores import (
11+
average_fold_predictions,
12+
collect_fold_predictions,
13+
mean_fold_score,
14+
)
1015

1116
logger = logging.getLogger(__name__)
1217
logger.setLevel(LOG_LEVEL)
@@ -29,9 +34,8 @@ def __init__(self, params):
2934
self.best_y_oof = (
3035
None # predictions computed on out of folds or on validation set
3136
)
32-
self.final_loss = (
33-
None # final score computed on combined predictions from all learners
34-
)
37+
self.final_loss = None # arithmetic mean of the completed fold scores
38+
self.validation_predictions = None
3539
# path to best model local copy, only used if cannot deep copy
3640
self.best_model_paths = {}
3741
self.multiple_target = False
@@ -61,41 +65,18 @@ def on_framework_train_end(self, logs):
6165
# aggregate predictions from all learners
6266
# it has two columns: 'prediction', 'target'
6367
logger.debug("early stopping on framework train end")
64-
self.best_y_oof = pd.concat(list(self.best_y_predicted.values()))
65-
self.best_y_oof.sort_index(inplace=True)
66-
# check for duplicates in index -> repeats of validation
67-
if np.sum(self.best_y_oof.index.duplicated()):
68-
# we need to aggregate predictions from multiple repeats
69-
target_cols = [c for c in self.best_y_oof.columns if "prediction" not in c]
70-
prediction_cols = [c for c in self.best_y_oof.columns if "prediction" in c]
71-
72-
aggs = {}
73-
for t in target_cols:
74-
aggs[t] = "first"
75-
for p in prediction_cols:
76-
aggs[p] = "mean"
77-
# aggregate predictions from repeats
78-
self.best_y_oof = self.best_y_oof.groupby(
79-
target_cols + prediction_cols, level=0
80-
).agg(aggs)
81-
82-
sample_weight = None
83-
if "sample_weight" in self.best_y_oof.columns:
84-
sample_weight = self.best_y_oof["sample_weight"]
85-
86-
if "prediction" in self.best_y_oof:
87-
self.final_loss = self.metric(
88-
self.best_y_oof[self.target_columns],
89-
self.best_y_oof["prediction"],
90-
sample_weight=sample_weight,
91-
)
92-
else:
93-
prediction_cols = [c for c in self.best_y_oof.columns if "prediction" in c]
94-
self.final_loss = self.metric(
95-
self.best_y_oof[self.target_columns],
96-
self.best_y_oof[prediction_cols],
97-
sample_weight=sample_weight,
98-
)
68+
self.validation_predictions = collect_fold_predictions(
69+
list(self.best_y_predicted.values())
70+
)
71+
frame = self.validation_predictions
72+
prediction_cols = [c for c in frame if "prediction" in c]
73+
predictions = frame[prediction_cols]
74+
if len(prediction_cols) == 1:
75+
predictions = predictions.iloc[:, 0]
76+
self.final_loss = mean_fold_score(
77+
self.metric, frame[self.target_columns], predictions, frame.get("sample_weight")
78+
)
79+
self.best_y_oof = average_fold_predictions(frame)
9980

10081
def on_iteration_end(self, logs, predictions):
10182
train_loss = 0

‎supervised/ensemble.py‎

Lines changed: 76 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
from supervised.utils.config import LOG_LEVEL
2222
from supervised.utils.jsonencoder import MLJSONEncoder
2323
from supervised.utils.metric import Metric
24+
from supervised.utils.validation_scores import (
25+
average_fold_predictions, has_fold_index, mean_fold_score,
26+
)
2427

2528
logger = logging.getLogger(__name__)
2629
logger.setLevel(LOG_LEVEL)
@@ -69,6 +72,7 @@ def __init__(
6972
self._scores = []
7073
self.oof_predictions = None
7174
self._oof_predictions_fname = None
75+
self._validation_predictions_fname = None
7276
self._single_prediction_time = None # prediction time on single sample
7377
self._max_single_prediction_time = max_single_prediction_time
7478
self.model_prediction_time = {}
@@ -127,6 +131,22 @@ def get_metric_name(self):
127131
def get_metric(self):
128132
return self.metric
129133

134+
def get_validation_predictions(self):
135+
if self.total_best_sum is not None:
136+
frame = self.total_best_sum.copy(deep=True)
137+
frame[self.target.columns] = self.target
138+
if self.sample_weight is not None:
139+
frame["sample_weight"] = self.sample_weight
140+
if self.sensitive_features is not None:
141+
frame[self.sensitive_features.columns] = self.sensitive_features
142+
return frame
143+
if self._validation_predictions_fname is not None:
144+
return pd.read_csv(
145+
self._validation_predictions_fname, index_col=[0, 1],
146+
float_precision="round_trip",
147+
)
148+
return None
149+
130150
def get_out_of_folds(self):
131151
"""Needed when ensemble is treated as model and we want to compute additional metrics for it"""
132152
# single prediction (in case of binary classification and regression)
@@ -137,19 +157,8 @@ def get_out_of_folds(self):
137157
self.oof_predictions = pd.read_csv(self._oof_predictions_fname)
138158
return self.oof_predictions.copy(deep=True)
139159

140-
ensemble_oof = pd.DataFrame(
141-
data=self.total_best_sum, columns=self.total_best_sum.columns
142-
)
143-
ensemble_oof["target"] = self.target
144-
if self.sample_weight is not None:
145-
ensemble_oof["sample_weight"] = self.sample_weight
146-
147-
# if self.sensitive_features is not None:
148-
# for col in self.sensitive_features.columns:
149-
# ensemble_oof[col] = self.sensitive_features[col]
150-
151-
self.oof_predictions = ensemble_oof
152-
return ensemble_oof
160+
self.oof_predictions = average_fold_predictions(self.get_validation_predictions())
161+
return self.oof_predictions.copy(deep=True)
153162

154163
def _get_mean(self, oof_selected, best_sum, best_count):
155164
resp = copy.deepcopy(oof_selected)
@@ -193,6 +202,8 @@ def get_oof_matrix(self, models, stacked_models=None):
193202

194203
oofs = {}
195204
sensitive_features = None
205+
fold_scoring = None
206+
reference = None
196207
for m in models:
197208
# do not use model with RandomFeature
198209
if "RandomFeature" in m.get_name():
@@ -201,7 +212,25 @@ def get_oof_matrix(self, models, stacked_models=None):
201212
# ensemble only the same level of stack
202213
# if m._is_stacked != self._is_stacked:
203214
# continue
204-
oof = m.get_out_of_folds()
215+
get_folds = getattr(m, "get_validation_predictions", lambda: None)
216+
oof = get_folds()
217+
has_folds = oof is not None and has_fold_index(oof)
218+
if fold_scoring is not None and has_folds != fold_scoring:
219+
raise NotTrainedException(
220+
"Cannot mix legacy averaged predictions with fold-level validation "
221+
"predictions. Retrain the candidates in a new results directory."
222+
)
223+
fold_scoring = has_folds
224+
if oof is None:
225+
oof = m.get_out_of_folds()
226+
target_cols = [c for c in oof if "target" in c]
227+
if reference is not None and (
228+
not oof.index.equals(reference.index)
229+
# Inverse target scaling can introduce harmless round-off.
230+
or not np.allclose(oof[target_cols], reference[target_cols], rtol=1e-7, atol=1e-8)
231+
):
232+
raise NotTrainedException("Ensemble candidates must use the same validation folds and rows.")
233+
reference = oof
205234
prediction_cols = [c for c in oof.columns if "prediction" in c]
206235
oofs[m.get_name()] = oof[prediction_cols] # oof["prediction"]
207236
if self.target is None:
@@ -248,7 +277,8 @@ def get_additional_metrics(self):
248277
oof_preds,
249278
sample_weight,
250279
self._ml_task,
251-
self.sensitive_features,
280+
(oof_predictions[[c for c in oof_predictions if "sensitive" in c]]
281+
if self.sensitive_features is not None else None),
252282
self._fairness_metric
253283
if self._ml_task != REGRESSION
254284
else f"{self._fairness_metric}@{self.get_metric_name()}",
@@ -357,6 +387,10 @@ def _prediction_cost(self, names):
357387

358388
def fit(self, oofs, y, sample_weight=None, sensitive_features=None):
359389
logger.debug("Ensemble.fit")
390+
self.target = y if isinstance(y, pd.DataFrame) else pd.DataFrame(
391+
{"target": np.asarray(y).ravel()}, index=next(iter(oofs.values())).index
392+
)
393+
self.sample_weight = sample_weight
360394
self.sensitive_features = sensitive_features
361395
start_time = time.time()
362396
selected_algs_cnt = 0 # number of selected algorithms
@@ -385,7 +419,7 @@ def fit(self, oofs, y, sample_weight=None, sensitive_features=None):
385419
):
386420
continue
387421
y_ens = self._get_mean(oofs[model_name], best_sum, j + 1)
388-
score = self.metric(y, y_ens, sample_weight)
422+
score = mean_fold_score(self.metric, y, y_ens, sample_weight)
389423
if self.metric.improvement(previous=min_score, current=score):
390424
min_score = score
391425
best_model = model_name
@@ -530,6 +564,17 @@ def save(self, results_path, model_subpath):
530564
self._oof_predictions_fname = resolve_artifact_path(results_path, predictions_fname)
531565
predictions.to_csv(self._oof_predictions_fname, index=False)
532566

567+
fold_predictions = self.get_validation_predictions()
568+
validation_predictions_fname = None
569+
if fold_predictions is not None and has_fold_index(fold_predictions):
570+
validation_predictions_fname = portable_artifact_path(
571+
model_subpath, "predictions_validation_folds.csv"
572+
)
573+
self._validation_predictions_fname = resolve_artifact_path(
574+
results_path, validation_predictions_fname
575+
)
576+
fold_predictions.to_csv(self._validation_predictions_fname)
577+
533578
with open(os.path.join(model_path, "ensemble.json"), "w") as fout:
534579
ms = []
535580
for selected in self.selected_models:
@@ -541,6 +586,8 @@ def save(self, results_path, model_subpath):
541586
"optimize_metric": self._optimize_metric,
542587
"selected_models": ms,
543588
"predictions_fname": predictions_fname,
589+
"validation_predictions_fname": validation_predictions_fname,
590+
"validation_score_aggregation": "mean_fold" if validation_predictions_fname else "pooled_oof",
544591
"metric_name": self.get_metric_name(),
545592
"final_loss": self.get_final_loss(),
546593
"train_time": self.get_train_time(),
@@ -571,6 +618,14 @@ def model_markdown(self):
571618
]
572619
desc = f"# Summary of {self.get_name()}\n\n"
573620
desc += "[<< Go back](../README.md)\n\n"
621+
if self._validation_predictions_fname is not None:
622+
sign = -1 if Metric.optimize_negative(self.metric.name) else 1
623+
desc += f"Mean fold {self.metric.name}: **{sign * self.get_final_loss():.6f}**.\n\n"
624+
desc += (
625+
"Selection uses the arithmetic mean of the ensemble scores from "
626+
"all folds and repeats. Additional metrics below use predictions "
627+
"averaged across repeats.\n"
628+
)
574629
desc += "\n## Ensemble structure\n"
575630
selected = pd.DataFrame(select_models_desc)
576631
desc += tabulate(selected.values, ["Model", "Weight"], tablefmt="pipe")
@@ -598,6 +653,11 @@ def load(results_path, model_subpath, models_map):
598653
ensemble.best_loss = None if final_loss is None else float(final_loss)
599654
ensemble.train_time = json_desc.get("train_time", ensemble.train_time)
600655
ensemble._is_stacked = json_desc.get("is_stacked", ensemble._is_stacked)
656+
fold_predictions_fname = json_desc.get("validation_predictions_fname")
657+
if fold_predictions_fname is not None:
658+
ensemble._validation_predictions_fname = resolve_artifact_path(
659+
results_path, fold_predictions_fname
660+
)
601661
predictions_fname = json_desc.get("predictions_fname")
602662
if predictions_fname is not None:
603663
ensemble._oof_predictions_fname = resolve_artifact_path(

0 commit comments

Comments
 (0)