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
11 changes: 11 additions & 0 deletions src/actinet/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
f1_score,
cohen_kappa_score,
)
import copy
import numpy as np
import pandas as pd
import os
Expand All @@ -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)
Expand All @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down
25 changes: 20 additions & 5 deletions tests/test_prepare_and_evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,24 +214,34 @@ 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"])
result = evaluate.evaluate_preprocessing(
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"])
Expand All @@ -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
Loading