-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Fix AutoRunner to honor num_fold when generating folds #9110
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mattlin1124
wants to merge
1
commit into
Project-MONAI:dev
Choose a base branch
from
mattlin1124:fix-7206-num-fold
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+101
−3
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| # Copyright (c) MONAI Consortium | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import logging | ||
| import tempfile | ||
| import unittest | ||
| from pathlib import Path | ||
|
|
||
| from parameterized import parameterized | ||
|
|
||
| from monai.apps.auto3dseg import AutoRunner | ||
| from monai.utils import optional_import | ||
|
|
||
| _, has_sklearn = optional_import("sklearn.model_selection", name="KFold") | ||
| _, has_yaml = optional_import("yaml") | ||
|
|
||
|
|
||
| @unittest.skipUnless(has_sklearn and has_yaml, "scikit-learn and PyYAML required") | ||
| class TestAutoRunnerNumFold(unittest.TestCase): | ||
| def setUp(self): | ||
| temp_dir = tempfile.TemporaryDirectory() | ||
| self.addCleanup(temp_dir.cleanup) | ||
| self.tmp_path = Path(temp_dir.name) | ||
|
|
||
| def test_autorunner_generates_configured_num_fold(self): | ||
| tmp_path = self.tmp_path | ||
| datalist_path = tmp_path / "datalist.json" | ||
| datalist_path.write_text( | ||
| json.dumps({"training": [{"image": f"image_{i}.nii.gz", "label": f"label_{i}.nii.gz"} for i in range(10)]}), | ||
| encoding="utf-8", | ||
| ) | ||
| runner = AutoRunner( | ||
| work_dir=str(tmp_path / "work"), | ||
| input={"modality": "CT", "dataroot": str(tmp_path), "datalist": str(datalist_path), "num_fold": 2}, | ||
| analyze=False, | ||
| algo_gen=False, | ||
| train=False, | ||
| ensemble=False, | ||
| ) | ||
| with open(runner.datalist_filename, encoding="utf-8") as f: | ||
| generated = json.load(f) | ||
|
|
||
| assert runner.num_fold == 2 | ||
| assert {item["fold"] for item in generated["training"]} == {0, 1} | ||
|
|
||
| @parameterized.expand([("default",), ("existing_folds",), ("validation",), ("six_folds",)]) | ||
| def test_autorunner_fold_compatibility(self, case): | ||
| tmp_path = self.tmp_path | ||
| training = [{"image": f"image_{i}.nii.gz", "label": f"label_{i}.nii.gz"} for i in range(10)] | ||
| datalist = {"training": training} | ||
| datalist_path = tmp_path / "datalist.json" | ||
| config = {"modality": "CT", "dataroot": str(tmp_path), "datalist": str(datalist_path)} | ||
| expected_training = None | ||
| expected_num_fold = 5 | ||
|
|
||
| if case == "existing_folds": | ||
| for i, item in enumerate(training): | ||
| item["fold"] = i % 5 | ||
| config["num_fold"] = expected_num_fold = 2 | ||
| expected_training = training | ||
| elif case == "validation": | ||
| # Avoid an existing malformed INFO message in the validation merge path. | ||
| logger = logging.getLogger("monai.apps.auto3dseg.auto_runner") | ||
| self.addCleanup(logger.setLevel, logger.level) | ||
| logger.setLevel(logging.WARNING) | ||
| # Include an overlapping case and a validation-only case to check merging. | ||
| datalist["validation"] = [training[0].copy(), {"image": "val.nii.gz", "label": "val_label.nii.gz"}] | ||
| config["num_fold"] = expected_num_fold = 1 | ||
| expected_training = [dict(item, fold=0 if i == 0 else 1) for i, item in enumerate(training)] | ||
| expected_training.append(dict(datalist["validation"][1], fold=0)) | ||
| elif case == "six_folds": | ||
| config["num_fold"] = expected_num_fold = 6 | ||
|
|
||
| datalist_path.write_text(json.dumps(datalist), encoding="utf-8") | ||
| runner = AutoRunner( | ||
| work_dir=str(tmp_path / "work"), input=config, analyze=False, algo_gen=False, train=False, ensemble=False | ||
| ) | ||
| with open(runner.datalist_filename, encoding="utf-8") as f: | ||
| generated = json.load(f) | ||
|
|
||
| assert runner.num_fold == expected_num_fold | ||
| if expected_training is not None: | ||
| assert generated["training"] == expected_training | ||
| else: | ||
| assert len(generated["training"]) == 10 | ||
| assert {item["fold"] for item in generated["training"]} == set(range(expected_num_fold)) | ||
| assert json.loads(datalist_path.read_text(encoding="utf-8")) == datalist |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
Repository: Project-MONAI/MONAI
Length of output: 459
🏁 Script executed:
Repository: Project-MONAI/MONAI
Length of output: 189
🤖 get_repo_knowledge executed:
get_repo_knowledge Project-MONAI/MONAI /tmp/coderabbit-repo-knowledge/project-monai-monai-43c44fde/conventionsLength of output: 1363
🏁 Script executed:
Repository: Project-MONAI/MONAI
Length of output: 15664
🏁 Script executed:
Repository: Project-MONAI/MONAI
Length of output: 4620
Validate automatic fold counts before
KFold.When the datalist has no folds or validation items, validate
2 <= num_fold <= len(datalist["training"])before constructingKFold. Otherwise, invalid values fail beforeAutoRunner.set_num_fold()runs. Add tests for both boundaries.Proposed fix
else: num_fold = int(self.data_src_cfg.get("num_fold", 5)) + if not 2 <= num_fold <= len(datalist["training"]): + raise ValueError( + "num_fold must be at least 2 and no greater than the number of training items " + "when AutoRunner generates folds." + ) warnings.warn(📝 Committable suggestion
🤖 Prompt for AI Agents