mmhsi 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. mmhsi/__init__.py +81 -0
  2. mmhsi/cli/__init__.py +58 -0
  3. mmhsi/cli/download.py +154 -0
  4. mmhsi/cli/test.py +52 -0
  5. mmhsi/cli/train.py +98 -0
  6. mmhsi/configs/_base_/datasets/indian_pines_patch15.py +62 -0
  7. mmhsi/configs/_base_/datasets/pavia_u_patch13.py +62 -0
  8. mmhsi/configs/_base_/datasets/salinas_patch15.py +62 -0
  9. mmhsi/configs/_base_/default_runtime.py +33 -0
  10. mmhsi/configs/_base_/schedules/schedule_100e.py +25 -0
  11. mmhsi/configs/hybridsn/hybridsn_patch13_pavia_u.py +26 -0
  12. mmhsi/configs/hybridsn/hybridsn_patch15_indian_pines.py +26 -0
  13. mmhsi/configs/hybridsn/hybridsn_patch15_salinas.py +26 -0
  14. mmhsi/datasets/__init__.py +27 -0
  15. mmhsi/datasets/base_hsi_dataset.py +256 -0
  16. mmhsi/datasets/benchmark_datasets.py +198 -0
  17. mmhsi/datasets/transforms/__init__.py +17 -0
  18. mmhsi/datasets/transforms/augmentations.py +138 -0
  19. mmhsi/evaluation/__init__.py +5 -0
  20. mmhsi/evaluation/metrics/__init__.py +5 -0
  21. mmhsi/evaluation/metrics/hsi_metric.py +142 -0
  22. mmhsi/models/__init__.py +21 -0
  23. mmhsi/models/attentions/__init__.py +5 -0
  24. mmhsi/models/attentions/spectral_attention.py +77 -0
  25. mmhsi/models/backbones/__init__.py +5 -0
  26. mmhsi/models/backbones/hybrid_sn.py +126 -0
  27. mmhsi/models/classifiers/__init__.py +5 -0
  28. mmhsi/models/classifiers/hsi_classifier.py +127 -0
  29. mmhsi/models/data_preprocessors/__init__.py +5 -0
  30. mmhsi/models/data_preprocessors/hsi_preprocessor.py +74 -0
  31. mmhsi/models/heads/__init__.py +5 -0
  32. mmhsi/models/heads/cls_head.py +98 -0
  33. mmhsi/models/losses/__init__.py +6 -0
  34. mmhsi/models/losses/focal_loss.py +65 -0
  35. mmhsi/models/losses/spectral_losses.py +60 -0
  36. mmhsi/models/necks/__init__.py +5 -0
  37. mmhsi/models/necks/spectral_reduction.py +44 -0
  38. mmhsi/registry.py +87 -0
  39. mmhsi/structures/__init__.py +5 -0
  40. mmhsi/structures/data_sample.py +78 -0
  41. mmhsi/utils/__init__.py +5 -0
  42. mmhsi/utils/checkpoint.py +39 -0
  43. mmhsi/version.py +3 -0
  44. mmhsi-0.1.0.dist-info/METADATA +159 -0
  45. mmhsi-0.1.0.dist-info/RECORD +49 -0
  46. mmhsi-0.1.0.dist-info/WHEEL +5 -0
  47. mmhsi-0.1.0.dist-info/entry_points.txt +4 -0
  48. mmhsi-0.1.0.dist-info/licenses/LICENSE +176 -0
  49. mmhsi-0.1.0.dist-info/top_level.txt +1 -0
mmhsi/__init__.py ADDED
@@ -0,0 +1,81 @@
1
+ """MMHSI: OpenMMLab-style Hyperspectral Imaging Toolbox based on MMEngine."""
2
+
3
+ from .datasets import (
4
+ BaseHSIDataset,
5
+ IndianPinesDataset,
6
+ PackHSIInputs,
7
+ PaviaUDataset,
8
+ RandomBandDropout,
9
+ RandomFlipHSI,
10
+ RandomSpectralNoise,
11
+ SalinasDataset,
12
+ )
13
+ from .evaluation import HSIAccuracy
14
+ from .models import (
15
+ HSIClsHead,
16
+ HSIDataPreprocessor,
17
+ HSIFocalLoss,
18
+ HSIPatchClassifier,
19
+ HybridSN,
20
+ SpatialSpectralCBAM,
21
+ SpectralAngleLoss,
22
+ SpectralAttention,
23
+ SpectralReductionNeck,
24
+ )
25
+ from .registry import (
26
+ DATA_SAMPLERS,
27
+ DATASETS,
28
+ HOOKS,
29
+ LOOPS,
30
+ METRICS,
31
+ MODELS,
32
+ OPTIM_WRAPPER_CONSTRUCTORS,
33
+ OPTIM_WRAPPERS,
34
+ OPTIMIZERS,
35
+ PARAM_SCHEDULERS,
36
+ RUNNERS,
37
+ TRANSFORMS,
38
+ VISUALIZERS,
39
+ )
40
+ from .structures import HSIDataSample
41
+ from .utils import register_checkpoint_loader
42
+ from .version import __version__
43
+
44
+ # Make MMEngine checkpoints loadable on PyTorch >= 2.6 (see mmhsi/utils/checkpoint.py)
45
+ register_checkpoint_loader()
46
+
47
+ __all__ = [
48
+ "DATASETS",
49
+ "DATA_SAMPLERS",
50
+ "HOOKS",
51
+ "LOOPS",
52
+ "METRICS",
53
+ "MODELS",
54
+ "OPTIMIZERS",
55
+ "OPTIM_WRAPPERS",
56
+ "OPTIM_WRAPPER_CONSTRUCTORS",
57
+ "PARAM_SCHEDULERS",
58
+ "RUNNERS",
59
+ "TRANSFORMS",
60
+ "VISUALIZERS",
61
+ "BaseHSIDataset",
62
+ "HSIAccuracy",
63
+ "HSIClsHead",
64
+ "HSIDataPreprocessor",
65
+ "HSIDataSample",
66
+ "HSIFocalLoss",
67
+ "HSIPatchClassifier",
68
+ "HybridSN",
69
+ "IndianPinesDataset",
70
+ "PackHSIInputs",
71
+ "PaviaUDataset",
72
+ "RandomBandDropout",
73
+ "RandomFlipHSI",
74
+ "RandomSpectralNoise",
75
+ "SalinasDataset",
76
+ "SpatialSpectralCBAM",
77
+ "SpectralAngleLoss",
78
+ "SpectralAttention",
79
+ "SpectralReductionNeck",
80
+ "__version__",
81
+ ]
mmhsi/cli/__init__.py ADDED
@@ -0,0 +1,58 @@
1
+ """Command-line entry points: ``mmhsi-train``, ``mmhsi-test``, ``mmhsi-download``."""
2
+
3
+ import os.path as osp
4
+ from pathlib import Path
5
+
6
+ CONFIG_ROOT = Path(__file__).resolve().parent.parent / "configs"
7
+
8
+
9
+ def resolve_config(config: str) -> str:
10
+ """Return a config file path from a path or a bundled config name.
11
+
12
+ Accepts, in order:
13
+ 1. An existing file path, e.g. ``my_configs/exp.py``.
14
+ 2. A path relative to the bundled configs, with or without ``.py``,
15
+ e.g. ``hybridsn/hybridsn_patch15_indian_pines``.
16
+ 3. A bare bundled config name, e.g. ``hybridsn_patch15_indian_pines``.
17
+ """
18
+ if osp.isfile(config):
19
+ return config
20
+
21
+ name = config if config.endswith(".py") else f"{config}.py"
22
+ # Tolerate the repo-style prefix "configs/..." or "mmhsi/configs/..."
23
+ for prefix in ("mmhsi/configs/", "configs/"):
24
+ if name.startswith(prefix):
25
+ name = name[len(prefix) :]
26
+ break
27
+
28
+ candidate = CONFIG_ROOT / name
29
+ if candidate.is_file():
30
+ return str(candidate)
31
+
32
+ matches = [
33
+ p for p in CONFIG_ROOT.rglob(Path(name).name) if "_base_" not in p.parts
34
+ ]
35
+ if len(matches) == 1:
36
+ return str(matches[0])
37
+
38
+ available = sorted(
39
+ str(p.relative_to(CONFIG_ROOT).with_suffix(""))
40
+ for p in CONFIG_ROOT.rglob("*.py")
41
+ if "_base_" not in p.parts
42
+ )
43
+ raise FileNotFoundError(
44
+ f"Config '{config}' not found as a file or a bundled config. "
45
+ f"Bundled configs: {', '.join(available)}"
46
+ )
47
+
48
+
49
+ def list_configs() -> list[str]:
50
+ """Names of the bundled (non-base) configs."""
51
+ return sorted(
52
+ str(p.relative_to(CONFIG_ROOT).with_suffix(""))
53
+ for p in CONFIG_ROOT.rglob("*.py")
54
+ if "_base_" not in p.parts
55
+ )
56
+
57
+
58
+ __all__ = ["CONFIG_ROOT", "list_configs", "resolve_config"]
mmhsi/cli/download.py ADDED
@@ -0,0 +1,154 @@
1
+ """Download standard HSI benchmark datasets with fallback mirrors (``mmhsi-download``)."""
2
+
3
+ import argparse
4
+ import os
5
+ import urllib.request
6
+
7
+ # Multi-mirror dataset definitions (HuggingFace + GitHub mirrors)
8
+ DATASET_MIRRORS = {
9
+ "indian_pines": {
10
+ "dir": "indian_pines",
11
+ "files": [
12
+ {
13
+ "name": "Indian_pines_corrected.mat",
14
+ "urls": [
15
+ "https://huggingface.co/datasets/danaroth/indian_pines/resolve/main/Indian_pines_corrected.mat",
16
+ "https://github.com/GiorgioMorales/HSI-BandSelection/raw/master/Data/Indian_pines_corrected.mat",
17
+ ],
18
+ },
19
+ {
20
+ "name": "Indian_pines_gt.mat",
21
+ "urls": [
22
+ "https://huggingface.co/datasets/danaroth/indian_pines/resolve/main/Indian_pines_gt.mat",
23
+ "https://github.com/GiorgioMorales/HSI-BandSelection/raw/master/Data/Indian_pines_gt.mat",
24
+ ],
25
+ },
26
+ ],
27
+ },
28
+ "salinas": {
29
+ "dir": "salinas",
30
+ "files": [
31
+ {
32
+ "name": "Salinas_corrected.mat",
33
+ "urls": [
34
+ "https://github.com/GiorgioMorales/HSI-BandSelection/raw/master/Data/Salinas_corrected.mat",
35
+ ],
36
+ },
37
+ {
38
+ "name": "Salinas_gt.mat",
39
+ "urls": [
40
+ "https://github.com/GiorgioMorales/HSI-BandSelection/raw/master/Data/Salinas_gt.mat",
41
+ ],
42
+ },
43
+ ],
44
+ },
45
+ "pavia_u": {
46
+ "dir": "pavia_u",
47
+ "files": [
48
+ {
49
+ "name": "PaviaU.mat",
50
+ "urls": [
51
+ "https://huggingface.co/datasets/Tanishq165/HSI_Datasets/resolve/main/Pavia%20University/PaviaU_data.mat",
52
+ ],
53
+ },
54
+ {
55
+ "name": "PaviaU_gt.mat",
56
+ "urls": [
57
+ "https://huggingface.co/datasets/Tanishq165/HSI_Datasets/resolve/main/Pavia%20University/PaviaU_gt.mat",
58
+ ],
59
+ },
60
+ ],
61
+ },
62
+ }
63
+
64
+
65
+ def download_file(urls: list[str], dest_path: str):
66
+ """Download a file with fallback mirrors and progress reporting."""
67
+ if os.path.exists(dest_path) and os.path.getsize(dest_path) > 1024:
68
+ print(
69
+ f" [Exists] {dest_path} ({os.path.getsize(dest_path) / (1024 * 1024):.2f} MB)"
70
+ )
71
+ return True
72
+
73
+ os.makedirs(os.path.dirname(dest_path), exist_ok=True)
74
+
75
+ for url in urls:
76
+ print(f" [Attempting] {url}")
77
+ try:
78
+ req = urllib.request.Request(
79
+ url, headers={"User-Agent": "Mozilla/5.0 (X11; Linux x86_64)"}
80
+ )
81
+ with (
82
+ urllib.request.urlopen(req, timeout=30) as response,
83
+ open(dest_path, "wb") as out_file,
84
+ ):
85
+ total_size = int(response.info().get("Content-Length", -1))
86
+ downloaded = 0
87
+ block_size = 64 * 1024
88
+
89
+ while True:
90
+ buffer = response.read(block_size)
91
+ if not buffer:
92
+ break
93
+ downloaded += len(buffer)
94
+ out_file.write(buffer)
95
+ if total_size > 0:
96
+ percent = downloaded / total_size * 100
97
+ print(
98
+ f"\r Progress: {percent:.1f}% ({downloaded / (1024 * 1024):.1f}/{total_size / (1024 * 1024):.1f} MB)",
99
+ end="",
100
+ flush=True,
101
+ )
102
+ else:
103
+ print(
104
+ f"\r Downloaded: {downloaded / (1024 * 1024):.1f} MB",
105
+ end="",
106
+ flush=True,
107
+ )
108
+ print(f"\n [Success] Saved to {dest_path}")
109
+ return True
110
+ except Exception as e:
111
+ print(f"\n [Failed] {e}. Trying next mirror if available...")
112
+ if os.path.exists(dest_path):
113
+ try:
114
+ os.remove(dest_path)
115
+ except OSError:
116
+ pass
117
+
118
+ return False
119
+
120
+
121
+ def main(argv=None):
122
+ parser = argparse.ArgumentParser(description="Download HSI benchmark datasets")
123
+ parser.add_argument(
124
+ "--dataset",
125
+ type=str,
126
+ default="all",
127
+ choices=["all", "indian_pines", "salinas", "pavia_u"],
128
+ help="Target dataset to download",
129
+ )
130
+ parser.add_argument(
131
+ "--data-root",
132
+ type=str,
133
+ default="data",
134
+ help="Directory to download into; the bundled configs expect 'data' "
135
+ "relative to where you run training. Default: data",
136
+ )
137
+ args = parser.parse_args(argv)
138
+
139
+ targets = list(DATASET_MIRRORS.keys()) if args.dataset == "all" else [args.dataset]
140
+
141
+ for name in targets:
142
+ cfg = DATASET_MIRRORS[name]
143
+ print(f"\n=== Processing Dataset: {name.upper()} ===")
144
+ for item in cfg["files"]:
145
+ dest = os.path.join(args.data_root, cfg["dir"], item["name"])
146
+ success = download_file(item["urls"], dest)
147
+ if not success:
148
+ print(f" [Warning] All download mirrors failed for {item['name']}.")
149
+
150
+ print("\nDownload process completed.")
151
+
152
+
153
+ if __name__ == "__main__":
154
+ main()
mmhsi/cli/test.py ADDED
@@ -0,0 +1,52 @@
1
+ """Evaluate an HSI model checkpoint with the MMEngine Runner (``mmhsi-test``)."""
2
+
3
+ import os
4
+
5
+ os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib")
6
+
7
+ import argparse
8
+ import os.path as osp
9
+
10
+ from mmengine.config import Config, DictAction
11
+ from mmengine.runner import Runner
12
+
13
+ import mmhsi # noqa: F401 (registers components and the checkpoint loader)
14
+ from mmhsi.cli import resolve_config
15
+
16
+
17
+ def parse_args(argv=None):
18
+ parser = argparse.ArgumentParser(description="Test an HSI model checkpoint")
19
+ parser.add_argument(
20
+ "config", help="Config file path or bundled config name"
21
+ )
22
+ parser.add_argument("checkpoint", help="Checkpoint file path to evaluate")
23
+ parser.add_argument("--work-dir", help="Directory to save evaluation results")
24
+ parser.add_argument(
25
+ "--cfg-options", nargs="+", action=DictAction, help="Override config options"
26
+ )
27
+ return parser.parse_args(argv)
28
+
29
+
30
+ def main(argv=None):
31
+ args = parse_args(argv)
32
+
33
+ config_path = resolve_config(args.config)
34
+ cfg = Config.fromfile(config_path)
35
+ if args.cfg_options is not None:
36
+ cfg.merge_from_dict(args.cfg_options)
37
+
38
+ if args.work_dir is not None:
39
+ cfg.work_dir = args.work_dir
40
+ elif cfg.get("work_dir", None) is None:
41
+ cfg.work_dir = osp.join(
42
+ "./work_dirs", osp.splitext(osp.basename(config_path))[0]
43
+ )
44
+
45
+ cfg.load_from = args.checkpoint
46
+
47
+ runner = Runner.from_cfg(cfg)
48
+ runner.test()
49
+
50
+
51
+ if __name__ == "__main__":
52
+ main()
mmhsi/cli/train.py ADDED
@@ -0,0 +1,98 @@
1
+ """Train an HSI model with the MMEngine Runner (``mmhsi-train``).
2
+
3
+ Each run gets its own folder: ``work_dirs/<config>/run_<YYYYMMDD_HHMMSS>[_<run-name>]/``.
4
+ """
5
+
6
+ import os
7
+
8
+ os.environ.setdefault("MPLCONFIGDIR", "/tmp/matplotlib")
9
+
10
+ import argparse
11
+ import os.path as osp
12
+ import time
13
+
14
+ from mmengine.config import Config, DictAction
15
+ from mmengine.runner import Runner
16
+
17
+ import mmhsi # noqa: F401 (registers components and the checkpoint loader)
18
+ from mmhsi.cli import list_configs, resolve_config
19
+
20
+
21
+ def parse_args(argv=None):
22
+ parser = argparse.ArgumentParser(description="Train an HSI model using MMHSI")
23
+ parser.add_argument(
24
+ "config",
25
+ nargs="?",
26
+ help="Config file path or bundled config name "
27
+ "(e.g. hybridsn_patch15_indian_pines)",
28
+ )
29
+ parser.add_argument(
30
+ "--list-configs", action="store_true", help="List bundled configs and exit"
31
+ )
32
+ parser.add_argument(
33
+ "--work-dir",
34
+ help="Explicit directory to save logs and models (overrides auto run dir)",
35
+ )
36
+ parser.add_argument(
37
+ "--run-name",
38
+ type=str,
39
+ default=None,
40
+ help="Optional descriptive name for this specific run (appended to timestamped run folder)",
41
+ )
42
+ parser.add_argument(
43
+ "--resume",
44
+ nargs="?",
45
+ type=str,
46
+ const="auto",
47
+ help="Resume from latest checkpoint automatically or from specified path",
48
+ )
49
+ parser.add_argument(
50
+ "--cfg-options",
51
+ nargs="+",
52
+ action=DictAction,
53
+ help="Override settings in config, e.g., --cfg-options train_dataloader.batch_size=128",
54
+ )
55
+ args = parser.parse_args(argv)
56
+ if not args.list_configs and args.config is None:
57
+ parser.error("the following arguments are required: config")
58
+ return args
59
+
60
+
61
+ def main(argv=None):
62
+ args = parse_args(argv)
63
+ if args.list_configs:
64
+ print("\n".join(list_configs()))
65
+ return
66
+
67
+ config_path = resolve_config(args.config)
68
+ cfg = Config.fromfile(config_path)
69
+ if args.cfg_options is not None:
70
+ cfg.merge_from_dict(args.cfg_options)
71
+
72
+ # Hydra-style run directory isolation:
73
+ # Generates work_dirs/<model_dataset>/run_YYYYMMDD_HHMMSS[_tag]/
74
+ if args.work_dir is not None:
75
+ cfg.work_dir = args.work_dir
76
+ elif cfg.get("work_dir", None) is None or cfg.work_dir.startswith("./work_dirs"):
77
+ base_exp = osp.splitext(osp.basename(config_path))[0]
78
+ timestamp = time.strftime("%Y%m%d_%H%M%S", time.localtime())
79
+ run_folder = (
80
+ f"run_{timestamp}_{args.run_name}" if args.run_name else f"run_{timestamp}"
81
+ )
82
+ cfg.work_dir = osp.join("./work_dirs", base_exp, run_folder)
83
+
84
+ if args.resume == "auto":
85
+ cfg.resume = True
86
+ cfg.load_from = None
87
+ elif args.resume:
88
+ cfg.resume = True
89
+ cfg.load_from = args.resume
90
+
91
+ print(f"\n[MMHSI] Experiment Run Directory: {cfg.work_dir}\n")
92
+
93
+ runner = Runner.from_cfg(cfg)
94
+ runner.train()
95
+
96
+
97
+ if __name__ == "__main__":
98
+ main()
@@ -0,0 +1,62 @@
1
+ # Indian Pines Dataset with 15x15 Patches
2
+ dataset_type = "IndianPinesDataset"
3
+ data_root = "data/indian_pines"
4
+
5
+ train_pipeline = [
6
+ {"type": "RandomFlipHSI", "prob": 0.5, "direction": "both"},
7
+ {"type": "RandomSpectralNoise", "std": 0.005, "prob": 0.3},
8
+ {"type": "PackHSIInputs"},
9
+ ]
10
+
11
+ test_pipeline = [{"type": "PackHSIInputs"}]
12
+
13
+ train_dataloader = {
14
+ "batch_size": 64,
15
+ "num_workers": 2,
16
+ "sampler": {"type": "DefaultSampler", "shuffle": True},
17
+ "dataset": {
18
+ "type": dataset_type,
19
+ "data_root": data_root,
20
+ "patch_size": 15,
21
+ "split": "train",
22
+ "train_ratio": 0.10,
23
+ "val_ratio": 0.10,
24
+ "seed": 42,
25
+ "pipeline": train_pipeline,
26
+ },
27
+ }
28
+
29
+ val_dataloader = {
30
+ "batch_size": 64,
31
+ "num_workers": 2,
32
+ "sampler": {"type": "DefaultSampler", "shuffle": False},
33
+ "dataset": {
34
+ "type": dataset_type,
35
+ "data_root": data_root,
36
+ "patch_size": 15,
37
+ "split": "val",
38
+ "train_ratio": 0.10,
39
+ "val_ratio": 0.10,
40
+ "seed": 42,
41
+ "pipeline": test_pipeline,
42
+ },
43
+ }
44
+
45
+ test_dataloader = {
46
+ "batch_size": 64,
47
+ "num_workers": 2,
48
+ "sampler": {"type": "DefaultSampler", "shuffle": False},
49
+ "dataset": {
50
+ "type": dataset_type,
51
+ "data_root": data_root,
52
+ "patch_size": 15,
53
+ "split": "test",
54
+ "train_ratio": 0.10,
55
+ "val_ratio": 0.10,
56
+ "seed": 42,
57
+ "pipeline": test_pipeline,
58
+ },
59
+ }
60
+
61
+ val_evaluator = {"type": "HSIAccuracy"}
62
+ test_evaluator = {"type": "HSIAccuracy"}
@@ -0,0 +1,62 @@
1
+ # Pavia University Dataset with 13x13 Patches
2
+ dataset_type = "PaviaUDataset"
3
+ data_root = "data/pavia_u"
4
+
5
+ train_pipeline = [
6
+ {"type": "RandomFlipHSI", "prob": 0.5, "direction": "both"},
7
+ {"type": "RandomSpectralNoise", "std": 0.005, "prob": 0.3},
8
+ {"type": "PackHSIInputs"},
9
+ ]
10
+
11
+ test_pipeline = [{"type": "PackHSIInputs"}]
12
+
13
+ train_dataloader = {
14
+ "batch_size": 64,
15
+ "num_workers": 2,
16
+ "sampler": {"type": "DefaultSampler", "shuffle": True},
17
+ "dataset": {
18
+ "type": dataset_type,
19
+ "data_root": data_root,
20
+ "patch_size": 13,
21
+ "split": "train",
22
+ "train_ratio": 0.10,
23
+ "val_ratio": 0.10,
24
+ "seed": 42,
25
+ "pipeline": train_pipeline,
26
+ },
27
+ }
28
+
29
+ val_dataloader = {
30
+ "batch_size": 64,
31
+ "num_workers": 2,
32
+ "sampler": {"type": "DefaultSampler", "shuffle": False},
33
+ "dataset": {
34
+ "type": dataset_type,
35
+ "data_root": data_root,
36
+ "patch_size": 13,
37
+ "split": "val",
38
+ "train_ratio": 0.10,
39
+ "val_ratio": 0.10,
40
+ "seed": 42,
41
+ "pipeline": test_pipeline,
42
+ },
43
+ }
44
+
45
+ test_dataloader = {
46
+ "batch_size": 64,
47
+ "num_workers": 2,
48
+ "sampler": {"type": "DefaultSampler", "shuffle": False},
49
+ "dataset": {
50
+ "type": dataset_type,
51
+ "data_root": data_root,
52
+ "patch_size": 13,
53
+ "split": "test",
54
+ "train_ratio": 0.10,
55
+ "val_ratio": 0.10,
56
+ "seed": 42,
57
+ "pipeline": test_pipeline,
58
+ },
59
+ }
60
+
61
+ val_evaluator = {"type": "HSIAccuracy"}
62
+ test_evaluator = {"type": "HSIAccuracy"}
@@ -0,0 +1,62 @@
1
+ # Salinas Dataset with 15x15 Patches
2
+ dataset_type = "SalinasDataset"
3
+ data_root = "data/salinas"
4
+
5
+ train_pipeline = [
6
+ {"type": "RandomFlipHSI", "prob": 0.5, "direction": "both"},
7
+ {"type": "RandomSpectralNoise", "std": 0.005, "prob": 0.3},
8
+ {"type": "PackHSIInputs"},
9
+ ]
10
+
11
+ test_pipeline = [{"type": "PackHSIInputs"}]
12
+
13
+ train_dataloader = {
14
+ "batch_size": 64,
15
+ "num_workers": 2,
16
+ "sampler": {"type": "DefaultSampler", "shuffle": True},
17
+ "dataset": {
18
+ "type": dataset_type,
19
+ "data_root": data_root,
20
+ "patch_size": 15,
21
+ "split": "train",
22
+ "train_ratio": 0.10,
23
+ "val_ratio": 0.10,
24
+ "seed": 42,
25
+ "pipeline": train_pipeline,
26
+ },
27
+ }
28
+
29
+ val_dataloader = {
30
+ "batch_size": 64,
31
+ "num_workers": 2,
32
+ "sampler": {"type": "DefaultSampler", "shuffle": False},
33
+ "dataset": {
34
+ "type": dataset_type,
35
+ "data_root": data_root,
36
+ "patch_size": 15,
37
+ "split": "val",
38
+ "train_ratio": 0.10,
39
+ "val_ratio": 0.10,
40
+ "seed": 42,
41
+ "pipeline": test_pipeline,
42
+ },
43
+ }
44
+
45
+ test_dataloader = {
46
+ "batch_size": 64,
47
+ "num_workers": 2,
48
+ "sampler": {"type": "DefaultSampler", "shuffle": False},
49
+ "dataset": {
50
+ "type": dataset_type,
51
+ "data_root": data_root,
52
+ "patch_size": 15,
53
+ "split": "test",
54
+ "train_ratio": 0.10,
55
+ "val_ratio": 0.10,
56
+ "seed": 42,
57
+ "pipeline": test_pipeline,
58
+ },
59
+ }
60
+
61
+ val_evaluator = {"type": "HSIAccuracy"}
62
+ test_evaluator = {"type": "HSIAccuracy"}
@@ -0,0 +1,33 @@
1
+ # MMHSI Default Runtime Configuration
2
+ default_scope = 'mmhsi'
3
+
4
+ default_hooks = dict(
5
+ timer=dict(type='IterTimerHook'),
6
+ logger=dict(type='LoggerHook', interval=10),
7
+ param_scheduler=dict(type='ParamSchedulerHook'),
8
+ checkpoint=dict(
9
+ type='CheckpointHook',
10
+ interval=10,
11
+ save_best='hsi/OA',
12
+ rule='greater',
13
+ max_keep_ckpts=3
14
+ ),
15
+ sampler_seed=dict(type='DistSamplerSeedHook'),
16
+ )
17
+
18
+ env_cfg = dict(
19
+ cudnn_benchmark=True,
20
+ mp_cfg=dict(mp_start_method='fork', opencv_num_threads=0),
21
+ dist_cfg=dict(backend='nccl'),
22
+ )
23
+
24
+ log_processor = dict(
25
+ type='LogProcessor',
26
+ window_size=10,
27
+ by_epoch=True
28
+ )
29
+
30
+ log_level = 'INFO'
31
+ load_from = None
32
+ resume = False
33
+ visualizer = dict(type='Visualizer', name='visualizer')
@@ -0,0 +1,25 @@
1
+ # MMHSI Standard 100-Epoch Training Schedule
2
+ train_cfg = dict(type='EpochBasedTrainLoop', max_epochs=100, val_interval=5)
3
+ val_cfg = dict(type='ValLoop')
4
+ test_cfg = dict(type='TestLoop')
5
+
6
+ # Optimizer: Adam with lr=1e-3
7
+ optim_wrapper = dict(
8
+ type='OptimWrapper',
9
+ optimizer=dict(
10
+ type='Adam',
11
+ lr=1e-3,
12
+ weight_decay=1e-4
13
+ )
14
+ )
15
+
16
+ # Learning Rate Scheduler: Cosine Annealing
17
+ param_scheduler = [
18
+ dict(
19
+ type='CosineAnnealingLR',
20
+ T_max=100,
21
+ by_epoch=True,
22
+ begin=0,
23
+ end=100
24
+ )
25
+ ]