Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 7 additions & 13 deletions deeptab/models/_mixins/predict.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ class _PredictMixin:
the input columns match those seen during ``fit``.
* ``encode`` — returns dense embedding vectors from the model backbone
for a given input DataFrame.
* ``_score`` — internal helper used by ``optimize_hparams`` to evaluate
validation loss with the best checkpoint loaded.
* ``_score`` — internal helper behind the regressors' ``score()``; it
applies a metric to the ``predict`` output of the current model.
"""

if TYPE_CHECKING:
Expand Down Expand Up @@ -135,11 +135,12 @@ def _validate_predict_input(self, X, method="predict"):
return validate_input_features(self, X)

def _score(self, X, y, embeddings, metric):
"""Evaluate *metric* on *X* / *y* using the best-checkpoint weights.
"""Evaluate *metric* on *X* / *y* using the estimator's current weights.

Reloads the best model checkpoint before running ``predict`` so that
the score reflects the best validation state rather than the last
epoch's weights.
``fit()`` already restores the best checkpoint before returning, so the
score reflects the same model that ``predict`` uses. The checkpoint file
is not read again, so scoring neither depends on it still existing nor
discards changes made to the model after fitting.

Parameters
----------
Expand All @@ -159,13 +160,6 @@ def _score(self, X, y, embeddings, metric):
float
The metric value computed on the predictions.
"""
# Explicitly load the best model state if needed
best_model_path = getattr(self, "_best_model_path", None)
if hasattr(self, "_trainer") and best_model_path:
torch.serialization.add_safe_globals([type(self.config)])
checkpoint = torch.load(best_model_path, weights_only=False)
self._task_model.load_state_dict(checkpoint["state_dict"]) # type: ignore

predictions = self.predict(X, embeddings)

return metric(y, predictions)
Expand Down
31 changes: 31 additions & 0 deletions tests/integration/test_fit_lifecycle.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,37 @@ def _raise_mid_fit(self, *args, **kwargs):
reg.predict(X)


class TestRegressorScoreUsesCurrentModel:
"""score() must evaluate the in-memory model, like predict(), without
reloading the training checkpoint from disk."""

def test_score_works_after_checkpoint_directory_is_removed(self, tmp_path):
import shutil

from sklearn.metrics import r2_score

X, y = _make_reg_data()
checkpoint_dir = tmp_path / "checkpoints"
reg = MLPRegressor().fit(X, y, random_state=RANDOM_STATE, checkpoint_path=str(checkpoint_dir), **FIT_KWARGS)
assert reg._best_model_path
shutil.rmtree(checkpoint_dir)
assert reg.score(X, y) == pytest.approx(r2_score(y, reg.predict(X)))

def test_score_does_not_replace_current_weights(self):
import torch
from sklearn.metrics import r2_score

X, y = _make_reg_data()
reg = MLPRegressor().fit(X, y, random_state=RANDOM_STATE, **FIT_KWARGS)
assert reg._task_model is not None
with torch.no_grad():
for parameter in reg._task_model.parameters():
parameter.add_(0.5)
predictions = reg.predict(X)
assert reg.score(X, y) == pytest.approx(r2_score(y, predictions))
np.testing.assert_array_equal(reg.predict(X), predictions)


class _RecordingCallback(Callback):
def __init__(self):
self.epoch_ends = 0
Expand Down
Loading