diff --git a/src/actinet/evaluate.py b/src/actinet/evaluate.py index 4444bc4..36dabb8 100644 --- a/src/actinet/evaluate.py +++ b/src/actinet/evaluate.py @@ -6,6 +6,7 @@ f1_score, cohen_kappa_score, ) +import copy import numpy as np import pandas as pd import os @@ -26,6 +27,10 @@ def evaluate_preprocessing( weights_path: str = "models/weights.pt", verbose: bool = True, ) -> np.ndarray: + if classifier.model_weights is not None: + raise ValueError("Cross-validation requires a classifier without fitted weights.") + initial_classifier = classifier + skf = StratifiedGroupKFold(n_splits=5) le = LabelEncoder().fit(Y) @@ -34,6 +39,7 @@ def evaluate_preprocessing( Y_preds = np.empty_like(Y_encoded) for fold, (train_index, test_index) in enumerate(skf.split(X, Y_encoded, groups)): + classifier = copy.deepcopy(initial_classifier) X_train, X_test = X[train_index], X[test_index] y_train, y_test = Y_encoded[train_index], Y_encoded[test_index] groups_train = safe_indexer(groups, train_index) @@ -82,6 +88,10 @@ def evaluate_models( out_dir: Optional[str] = None, verbose: bool = True, ) -> Tuple[pd.DataFrame, pd.DataFrame]: + if actinet_classifier.model_weights is not None: + raise ValueError("Cross-validation requires a classifier without fitted weights.") + initial_classifier = actinet_classifier + skf = StratifiedGroupKFold(n_splits=5) le = LabelEncoder().fit(Y_rf) @@ -97,6 +107,7 @@ def evaluate_models( for fold, (train_index, test_index) in enumerate( skf.split(X_rf, Y_encoded_rf, groups_rf) ): + actinet_classifier = copy.deepcopy(initial_classifier) if verbose: print(f"======== Evalating Fold {fold+1} ========") # Ensure the same train and test split for groups are used in both models in each fold diff --git a/tests/test_prepare_and_evaluate.py b/tests/test_prepare_and_evaluate.py index 548559f..896705b 100644 --- a/tests/test_prepare_and_evaluate.py +++ b/tests/test_prepare_and_evaluate.py @@ -214,8 +214,11 @@ def split(self, X, y, groups): def test_evaluate_preprocessing_runs_group_folds(monkeypatch, capsys): monkeypatch.setattr(evaluate, "StratifiedGroupKFold", lambda n_splits: FixedSplitter()) - classifier = MagicMock() - classifier.predict.side_effect = [np.array([0, 1]), np.array([0, 1])] + classifier = MagicMock(model_weights=None) + fold_classifiers = [MagicMock(model_weights=None) for _ in range(2)] + classifier.__deepcopy__ = MagicMock(side_effect=fold_classifiers) + for fold_classifier in fold_classifiers: + fold_classifier.predict.return_value = np.array([0, 1]) X = np.arange(8).reshape(4, 2) y = np.array(["a", "b", "a", "b"]) groups = np.array(["g1", "g1", "g2", "g2"]) @@ -223,15 +226,22 @@ def test_evaluate_preprocessing_runs_group_folds(monkeypatch, capsys): classifier, X, y, groups, np.arange(4), weights_path="weights-{}.pt", verbose=True ) np.testing.assert_array_equal(result, y) - assert classifier.fit.call_count == 2 + classifier.fit.assert_not_called() + classifier.predict.assert_not_called() + for fold_classifier in fold_classifiers: + fold_classifier.fit.assert_called_once() + fold_classifier.predict.assert_called_once() assert "Fold 1 Test Scores" in capsys.readouterr().out def test_evaluate_models_returns_and_saves_fold_results(tmp_path, monkeypatch, capsys): monkeypatch.setattr(evaluate, "StratifiedGroupKFold", lambda n_splits: FixedSplitter()) - actinet_classifier = MagicMock() + actinet_classifier = MagicMock(model_weights=None) + fold_classifiers = [MagicMock(model_weights=None) for _ in range(2)] + actinet_classifier.__deepcopy__ = MagicMock(side_effect=fold_classifiers) + for fold_classifier in fold_classifiers: + fold_classifier.predict.return_value = np.array([0, 1]) rf_classifier = MagicMock() - actinet_classifier.predict.side_effect = [np.array([0, 1]), np.array([0, 1])] rf_classifier.predict.side_effect = [np.array([0, 1]), np.array([0, 1])] X = np.arange(8).reshape(4, 2) y = np.array(["a", "b", "a", "b"]) @@ -253,6 +263,11 @@ def test_evaluate_models_returns_and_saves_fold_results(tmp_path, monkeypatch, c verbose=True, ) assert len(actinet_result) == len(rf_result) == 2 + actinet_classifier.fit.assert_not_called() + actinet_classifier.predict.assert_not_called() + for fold_classifier in fold_classifiers: + fold_classifier.fit.assert_called_once() + fold_classifier.predict.assert_called_once() assert (tmp_path / "actinet_results.pkl").exists() assert (tmp_path / "rf_results.pkl").exists() assert "Actinet performance" in capsys.readouterr().out