hazardfuse 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.
- hazardfuse/__init__.py +39 -0
- hazardfuse/__main__.py +3 -0
- hazardfuse/calibration.py +64 -0
- hazardfuse/cli.py +129 -0
- hazardfuse/config.py +47 -0
- hazardfuse/groups.py +21 -0
- hazardfuse/io.py +80 -0
- hazardfuse/metrics.py +76 -0
- hazardfuse/model.py +348 -0
- hazardfuse/nn.py +87 -0
- hazardfuse/site.py +145 -0
- hazardfuse/split.py +80 -0
- hazardfuse/synthetic.py +24 -0
- hazardfuse-0.1.0.dist-info/METADATA +36 -0
- hazardfuse-0.1.0.dist-info/RECORD +19 -0
- hazardfuse-0.1.0.dist-info/WHEEL +5 -0
- hazardfuse-0.1.0.dist-info/entry_points.txt +2 -0
- hazardfuse-0.1.0.dist-info/licenses/LICENSE +21 -0
- hazardfuse-0.1.0.dist-info/top_level.txt +1 -0
hazardfuse/__init__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""HazardFuse: hazard-index-guided band attention and spatial embedding fusion for mapping leached-metal-associated
|
|
2
|
+
hazard from satellite and geospatial data.
|
|
3
|
+
|
|
4
|
+
Quick start::
|
|
5
|
+
|
|
6
|
+
from hazardfuse import HazardFuse, Site
|
|
7
|
+
|
|
8
|
+
site = Site.from_folder("data/glen_lyn", features="glen_lyn_Features", labels="glen_lyn_Label",
|
|
9
|
+
hi="glen_lyn_HI", name="Glen Lyn")
|
|
10
|
+
model = HazardFuse(seed=42).fit(site)
|
|
11
|
+
print(model.report()) # accuracy, kappa, class-wise precision, recall and F1
|
|
12
|
+
print(model.confusion_matrix(split="test"))
|
|
13
|
+
print(model.band_attention().head(15))
|
|
14
|
+
model.to_geotiffs("results/glen_lyn")
|
|
15
|
+
model.save("results/glen_lyn/HazardFuse")
|
|
16
|
+
|
|
17
|
+
new = Site.from_folder("data/bremo", features="bremo_Features", reference=model.schema, name="Bremo")
|
|
18
|
+
model.to_geotiffs("results/bremo", site=new)
|
|
19
|
+
"""
|
|
20
|
+
__version__ = "0.1.0"
|
|
21
|
+
|
|
22
|
+
from .config import DEFAULT_DATA, DEFAULT_MODEL, DEFAULT_SPLIT # noqa: E402
|
|
23
|
+
from .groups import FEATURE_GROUPS, group_of # noqa: E402
|
|
24
|
+
from .metrics import evaluate # noqa: E402
|
|
25
|
+
from .site import Site # noqa: E402
|
|
26
|
+
from .split import block_split # noqa: E402
|
|
27
|
+
|
|
28
|
+
__all__ = ["HazardFuse", "build_hazardfuse", "Site", "block_split", "evaluate", "FEATURE_GROUPS", "group_of",
|
|
29
|
+
"DEFAULT_MODEL", "DEFAULT_DATA", "DEFAULT_SPLIT", "__version__"]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def __getattr__(name): # TensorFlow is imported only when the model is used
|
|
33
|
+
if name == "HazardFuse":
|
|
34
|
+
from .model import HazardFuse
|
|
35
|
+
return HazardFuse
|
|
36
|
+
if name == "build_hazardfuse":
|
|
37
|
+
from .nn import build_hazardfuse
|
|
38
|
+
return build_hazardfuse
|
|
39
|
+
raise AttributeError(f"module 'hazardfuse' has no attribute {name!r}")
|
hazardfuse/__main__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Calibration of the class-1 score (notebook section 4, `calibrate`).
|
|
2
|
+
|
|
3
|
+
The score is oriented with the training labels (class-1 pixels must score higher), converted to its rank among the
|
|
4
|
+
valid pixels and mapped piecewise-linearly so that the training cut rank becomes 0.5. The cut rank follows the rule:
|
|
5
|
+
"prevalence" (1 - class-1 share of the labelled pixels), "balanced_acc" (cut that maximises balanced accuracy on the
|
|
6
|
+
labelled pixels) or "fixed" (0.5). The map is therefore a calibrated rank score with the decision threshold at 0.5."""
|
|
7
|
+
import numpy as np
|
|
8
|
+
from sklearn.metrics import balanced_accuracy_score
|
|
9
|
+
|
|
10
|
+
from .config import THRESHOLD
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _rank_to_prob(r, cut):
|
|
14
|
+
return np.where(r < cut, 0.5 * r / cut, 0.5 + 0.5 * (r - cut) / (1.0 - cut))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def calibrate(score_map, Y, valid, label_mask, rule="prevalence", orient=True):
|
|
18
|
+
"""Calibrated map (NaN outside `valid`) and its parameters {"flipped", "train_cut_rank", "rule"}."""
|
|
19
|
+
lm = np.asarray(label_mask, dtype=bool)
|
|
20
|
+
s = np.array(score_map, dtype=np.float64, copy=True)
|
|
21
|
+
y_tr = Y[lm]
|
|
22
|
+
if orient:
|
|
23
|
+
flipped = bool(np.nanmean(s[lm][y_tr == 1]) < np.nanmean(s[lm][y_tr == 0]))
|
|
24
|
+
else:
|
|
25
|
+
flipped = bool((s[valid] > np.nanmedian(s[valid])).mean() > 0.5)
|
|
26
|
+
if flipped:
|
|
27
|
+
s = -s
|
|
28
|
+
ranks = np.full(valid.shape, np.nan, dtype=np.float64)
|
|
29
|
+
v = s[valid]
|
|
30
|
+
ranks[valid] = np.argsort(np.argsort(v)) / max(len(v) - 1, 1)
|
|
31
|
+
p_tr = ranks[lm]
|
|
32
|
+
if rule == "balanced_acc":
|
|
33
|
+
cut = float(max(np.linspace(0.02, 0.98, 97), key=lambda t: balanced_accuracy_score(y_tr, (p_tr >= t).astype(int))))
|
|
34
|
+
elif rule == "prevalence":
|
|
35
|
+
cut = float(np.clip(1.0 - y_tr.mean(), 0.02, 0.98))
|
|
36
|
+
else:
|
|
37
|
+
cut = float(THRESHOLD)
|
|
38
|
+
prob = np.full(valid.shape, np.nan, dtype=np.float32)
|
|
39
|
+
prob[valid] = _rank_to_prob(ranks[valid], cut)
|
|
40
|
+
return prob, {"flipped": flipped, "train_cut_rank": cut, "rule": rule}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def apply_calibration(score_valid, valid, info, rule="source_cut", prevalence=None):
|
|
44
|
+
"""Map of a new site from its raw scores at the valid pixels (row-major order).
|
|
45
|
+
|
|
46
|
+
rule "raw": the model probability itself (oriented); "source_cut": ranks at this site, cut at the training cut rank
|
|
47
|
+
of the source site; "prevalence": cut at 1 - `prevalence` (expected class-1 share at this site)."""
|
|
48
|
+
s_valid = np.asarray(score_valid, dtype=np.float64)
|
|
49
|
+
prob = np.full(valid.shape, np.nan, dtype=np.float32)
|
|
50
|
+
if rule == "raw":
|
|
51
|
+
prob[valid] = 1.0 - s_valid if info["flipped"] else s_valid
|
|
52
|
+
return prob
|
|
53
|
+
s = -s_valid if info["flipped"] else s_valid
|
|
54
|
+
r = np.argsort(np.argsort(s)) / max(len(s) - 1, 1)
|
|
55
|
+
if rule == "source_cut":
|
|
56
|
+
cut = info["train_cut_rank"]
|
|
57
|
+
elif rule == "prevalence":
|
|
58
|
+
if prevalence is None:
|
|
59
|
+
raise ValueError("rule='prevalence' needs the expected class-1 share `prevalence`")
|
|
60
|
+
cut = float(np.clip(1.0 - prevalence, 0.02, 0.98))
|
|
61
|
+
else:
|
|
62
|
+
raise ValueError(f"unknown rule {rule!r}")
|
|
63
|
+
prob[valid] = _rank_to_prob(r, cut)
|
|
64
|
+
return prob
|
hazardfuse/cli.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Command-line interface.
|
|
2
|
+
|
|
3
|
+
hazardfuse fit CONFIG.yaml [--out DIR] [--seed N] [--smoke]
|
|
4
|
+
hazardfuse predict MODEL_DIR SITE.yaml [--out DIR] [--rule source_cut|prevalence|raw] [--prevalence P]
|
|
5
|
+
[--normalisation source|target]
|
|
6
|
+
hazardfuse info MODEL_DIR
|
|
7
|
+
|
|
8
|
+
CONFIG.yaml (fit) has the section `site` (arguments of Site.from_folder) and optionally `data`, `split`, `model`, `seed`
|
|
9
|
+
and `output`. SITE.yaml (predict) has the section `site` and optionally `output`. See configs/ in the repository."""
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import sys
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
SMOKE = dict(epochs=2, patience=2)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _yaml(path):
|
|
19
|
+
import yaml
|
|
20
|
+
with open(path) as f:
|
|
21
|
+
return yaml.safe_load(f) or {}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _site(cfg, reference=None, base=None):
|
|
25
|
+
from .site import Site
|
|
26
|
+
s = dict(cfg["site"])
|
|
27
|
+
folder = Path(s.pop("folder"))
|
|
28
|
+
if not folder.is_absolute() and base is not None:
|
|
29
|
+
folder = (base / folder).resolve()
|
|
30
|
+
data = {} if reference is not None else (cfg.get("data") or {})
|
|
31
|
+
return Site.from_folder(folder, reference=reference, **s, **data)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _out(a, cfg, base):
|
|
35
|
+
if a.out:
|
|
36
|
+
return Path(a.out)
|
|
37
|
+
o = Path(cfg.get("output") or "results")
|
|
38
|
+
return o if o.is_absolute() else (base / o).resolve()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _json(obj, path):
|
|
42
|
+
Path(path).write_text(json.dumps(obj, indent=2, default=lambda o: o.item() if hasattr(o, "item") else str(o)))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _line(name, e):
|
|
46
|
+
s = (f"{name}: accuracy {e['Accuracy']:.4f} | kappa {e['Kappa']:.4f}")
|
|
47
|
+
if "Kappa_lo" in e:
|
|
48
|
+
s += f" [{e['Kappa_lo']:.3f}, {e['Kappa_hi']:.3f}]"
|
|
49
|
+
return s + f" | F1 class 0 {e['F1_0']:.4f} | F1 class 1 {e['F1_1']:.4f}"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def cmd_fit(a):
|
|
53
|
+
from .model import HazardFuse
|
|
54
|
+
cfg = _yaml(a.config)
|
|
55
|
+
base = Path(a.config).resolve().parent
|
|
56
|
+
out = _out(a, cfg, base)
|
|
57
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
58
|
+
settings = dict(cfg.get("model") or {})
|
|
59
|
+
if a.smoke:
|
|
60
|
+
settings.update(SMOKE)
|
|
61
|
+
split = dict(cfg.get("split") or {})
|
|
62
|
+
if "frac" in split:
|
|
63
|
+
split["frac"] = tuple(split["frac"])
|
|
64
|
+
site = _site(cfg, base=base)
|
|
65
|
+
print(site)
|
|
66
|
+
model = HazardFuse(seed=a.seed if a.seed is not None else cfg.get("seed", 42), **settings)
|
|
67
|
+
model.fit(site, split=split)
|
|
68
|
+
model.save(out / "HazardFuse")
|
|
69
|
+
model.to_geotiffs(out)
|
|
70
|
+
model.split_summary().to_csv(out / "split_summary.csv")
|
|
71
|
+
model.history_.to_csv(out / "history.csv", index=False)
|
|
72
|
+
scores = {s: model.evaluate(split=s) for s in ("train", "val", "test") if model.masks_[s].any()}
|
|
73
|
+
_json(scores, out / "metrics.json")
|
|
74
|
+
model.report().to_csv(out / "metrics.csv")
|
|
75
|
+
model.confusion_matrix(split="test").to_csv(out / "confusion_matrix_test.csv")
|
|
76
|
+
if model.cfg["band_attention"] and model.cfg["center_branch"]:
|
|
77
|
+
model.band_attention(split="test").to_csv(out / "band_attention.csv", index=False)
|
|
78
|
+
print(f"Saved to {out}: HazardFuse/, HazardFuse_score.tif, HazardFuse_class.tif, metrics.json, metrics.csv")
|
|
79
|
+
if "test" in scores:
|
|
80
|
+
print(_line("test", scores["test"]))
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def cmd_predict(a):
|
|
84
|
+
from .model import HazardFuse
|
|
85
|
+
model = HazardFuse.load(a.model)
|
|
86
|
+
cfg = _yaml(a.site)
|
|
87
|
+
base = Path(a.site).resolve().parent
|
|
88
|
+
site = _site(cfg, reference=model.schema, base=base)
|
|
89
|
+
print(site)
|
|
90
|
+
out = _out(a, cfg, base)
|
|
91
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
92
|
+
kw = dict(rule=a.rule, prevalence=a.prevalence, normalisation=a.normalisation)
|
|
93
|
+
paths = model.to_geotiffs(out, site=site, **kw)
|
|
94
|
+
print("Written:", ", ".join(str(p) for p in paths))
|
|
95
|
+
if site.Y is not None:
|
|
96
|
+
e = model.evaluate(site=site, **kw)
|
|
97
|
+
_json(e, out / "metrics.json")
|
|
98
|
+
print(_line(site.name, e))
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def cmd_info(a):
|
|
102
|
+
from .model import HazardFuse
|
|
103
|
+
print(json.dumps(HazardFuse.load(a.model, verbose=False).summary(), indent=2, default=str))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def main(argv=None):
|
|
107
|
+
p = argparse.ArgumentParser(prog="hazardfuse", description="HazardFuse: band attention and spatial embedding "
|
|
108
|
+
"fusion for hazard mapping")
|
|
109
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
110
|
+
f = sub.add_parser("fit", help="fit on a labelled site and write the model, maps and scores")
|
|
111
|
+
f.add_argument("config"); f.add_argument("--out"); f.add_argument("--seed", type=int)
|
|
112
|
+
f.add_argument("--smoke", action="store_true", help="two epochs: checks the pipeline in minutes")
|
|
113
|
+
f.set_defaults(func=cmd_fit)
|
|
114
|
+
q = sub.add_parser("predict", help="map hazard at a site with a fitted model")
|
|
115
|
+
q.add_argument("model", help="folder written by `hazardfuse fit` (or HazardFuse.save)")
|
|
116
|
+
q.add_argument("site"); q.add_argument("--out")
|
|
117
|
+
q.add_argument("--rule", default="source_cut", choices=["source_cut", "prevalence", "raw"])
|
|
118
|
+
q.add_argument("--prevalence", type=float, help="expected class-1 share at the site (rule prevalence)")
|
|
119
|
+
q.add_argument("--normalisation", default="source", choices=["source", "target"])
|
|
120
|
+
q.set_defaults(func=cmd_predict)
|
|
121
|
+
i = sub.add_parser("info", help="settings, size and scores of a saved model")
|
|
122
|
+
i.add_argument("model")
|
|
123
|
+
i.set_defaults(func=cmd_info)
|
|
124
|
+
a = p.parse_args(argv)
|
|
125
|
+
a.func(a)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
if __name__ == "__main__":
|
|
129
|
+
sys.exit(main())
|
hazardfuse/config.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Default settings. They reproduce the HazardFuse model of the paper notebook (section 0: `HAZARDFUSE`, the band
|
|
2
|
+
cleaning and the split settings). Override any of them through the keyword arguments of :class:`hazardfuse.HazardFuse`
|
|
3
|
+
and :class:`hazardfuse.Site`, or through a YAML configuration file of the command-line interface."""
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
|
|
6
|
+
# ---- model: architecture and training protocol (notebook HAZARDFUSE)
|
|
7
|
+
DEFAULT_MODEL = dict(
|
|
8
|
+
# architecture
|
|
9
|
+
patch=21, # patch size (pixels); the class is predicted for the center pixel
|
|
10
|
+
dropout=0.30, # dropout of the center, spatial and joint embeddings
|
|
11
|
+
band_attention=True, # sigmoid band-attention weights on the center-pixel spectrum
|
|
12
|
+
fusion_gate=True, # gated fusion of the center and spatial embeddings
|
|
13
|
+
center_branch=True, # ablation switches: remove one branch
|
|
14
|
+
spatial_branch=True,
|
|
15
|
+
drop_bands=["QA60"], # bands left out of the model input (after the band cleaning)
|
|
16
|
+
# training
|
|
17
|
+
epochs=100, batch=256, lr=1e-3,
|
|
18
|
+
patience=20, # early stopping on the validation loss; learning rate halved after max(patience // 3, 2)
|
|
19
|
+
early_stop_on="val", # "val": early stopping on the validation blocks; "none": fixed `epochs`
|
|
20
|
+
predict_batch=2048,
|
|
21
|
+
# calibration of the class-1 score: "prevalence" (cut rank = 1 - class-1 share of the training labels),
|
|
22
|
+
# "balanced_acc" (cut that maximises balanced accuracy on the training pixels) or "fixed" (0.5)
|
|
23
|
+
threshold_rule="prevalence",
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
# ---- input data: band cleaning (notebook section 0 and section 2)
|
|
27
|
+
DEFAULT_DATA = dict(
|
|
28
|
+
feature_cleaning=True,
|
|
29
|
+
drop_bands=["QA60", "DW_LandCover"], # QA band and the land-cover class code (the class probabilities stay)
|
|
30
|
+
circular_bands=["Aspect_deg"], # replaced by sine and cosine
|
|
31
|
+
near_constant_share=0.99, # bands where one value covers this share of the valid pixels are removed
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
# ---- spatial block split with buffer (notebook section 3)
|
|
35
|
+
DEFAULT_SPLIT = dict(block_size=32, frac=(0.70, 0.15, 0.15), buffer_px=8, n_trials=500, seed=42)
|
|
36
|
+
|
|
37
|
+
THRESHOLD = 0.5
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def merged(defaults, overrides=None):
|
|
41
|
+
"""Copy of `defaults` updated with `overrides` (nested dictionaries are merged one level deep)."""
|
|
42
|
+
out = deepcopy(defaults)
|
|
43
|
+
for k, v in (overrides or {}).items():
|
|
44
|
+
if k not in out:
|
|
45
|
+
raise KeyError(f"unknown setting {k!r}; valid settings: {sorted(out)}")
|
|
46
|
+
out[k] = {**out[k], **v} if isinstance(out[k], dict) and isinstance(v, dict) else v
|
|
47
|
+
return out
|
hazardfuse/groups.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Feature groups of the static stack (notebook section 11: band attention and feature-group ablation)."""
|
|
2
|
+
_INDICES = ("NDVI", "MTCI", "SAVI", "CIRE", "NDRE1", "NDRE2", "LAI", "LCC", "CCC")
|
|
3
|
+
|
|
4
|
+
FEATURE_GROUPS = {
|
|
5
|
+
"Sentinel-2 bands": ["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B8A", "B9", "B11", "B12"],
|
|
6
|
+
"Vegetation indices": list(_INDICES),
|
|
7
|
+
"CSTV": [f"CSTV_{v}_Diff" for v in _INDICES],
|
|
8
|
+
"Rate of change": [f"{v}_Rate" for v in _INDICES],
|
|
9
|
+
"Topographic": ["DEM", "Slope_deg", "Aspect_deg", "Aspect_deg_sin", "Aspect_deg_cos", "Curvature"],
|
|
10
|
+
"Soil": ["Moisture", "pH", "Sand_pct_0_5cm", "Silt_pct_0_5cm", "Clay_pct_0_5cm"],
|
|
11
|
+
"Climate": ["Temperature", "Humidity"],
|
|
12
|
+
"Hydrologic": ["PrecipJJA_mm_mean", "UpstreamArea_km2", "HAND_m", "TWI"],
|
|
13
|
+
"Land cover": ["DW_Vegetation", "DW_LandCover", "DW_Snow", "DW_Built", "DW_Shrubs", "DW_Bare", "DW_Crops",
|
|
14
|
+
"DW_FloodedVeg", "DW_Grass", "DW_Trees", "DW_Water"],
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def group_of(names, groups=None, other="Other"):
|
|
19
|
+
"""Feature group of every band name (case-insensitive); bands of no group get `other`."""
|
|
20
|
+
low = {b.lower(): g for g, bs in (groups or FEATURE_GROUPS).items() for b in bs}
|
|
21
|
+
return [low.get(str(n).lower(), other) for n in names]
|
hazardfuse/io.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Raster input and output, band cleaning and band alignment."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def find_tif(folder, stem):
|
|
8
|
+
"""Path of `<stem>.tif` (or .tiff) in `folder`."""
|
|
9
|
+
for ext in (".tif", ".tiff", ".TIF", ".TIFF"):
|
|
10
|
+
p = Path(folder) / f"{stem}{ext}"
|
|
11
|
+
if p.exists():
|
|
12
|
+
return p
|
|
13
|
+
raise FileNotFoundError(f"No {stem}.tif/.tiff in {folder}")
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def read_raster(path):
|
|
17
|
+
"""(bands, rows, cols) float32 array with nodata as NaN, the raster profile and the band descriptions."""
|
|
18
|
+
import rasterio
|
|
19
|
+
with rasterio.open(path) as src:
|
|
20
|
+
return src.read(masked=True).astype("float32").filled(np.nan), src.profile.copy(), list(src.descriptions)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def write_geotiff(path, arr, profile, dtype="float32", nodata=np.nan):
|
|
24
|
+
"""Single-band GeoTIFF on the grid of `profile` (LZW compressed)."""
|
|
25
|
+
import rasterio
|
|
26
|
+
meta = {"driver": "GTiff", "height": arr.shape[0], "width": arr.shape[1], "count": 1, "dtype": dtype,
|
|
27
|
+
"crs": profile.get("crs"), "transform": profile.get("transform"), "nodata": nodata, "compress": "lzw"}
|
|
28
|
+
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
29
|
+
with rasterio.open(path, "w", **meta) as dst:
|
|
30
|
+
dst.write(np.asarray(arr).astype(dtype), 1)
|
|
31
|
+
return Path(path)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def clean_bands(arrays, names, valid, drop_bands, circular_bands, near_constant_share):
|
|
35
|
+
"""The same cleaning for a list of (H, W, B) arrays with common band names: drop `drop_bands`, drop bands where one
|
|
36
|
+
value covers >= `near_constant_share` of the valid pixels (pooled over the arrays), replace `circular_bands` (degrees)
|
|
37
|
+
by their sine and cosine. Returns (arrays, names, log)."""
|
|
38
|
+
log = {"bands_in": len(names), "dropped": [], "near_constant": [], "circular": []}
|
|
39
|
+
low = [str(n).lower() for n in names]
|
|
40
|
+
keep = np.ones(len(names), dtype=bool)
|
|
41
|
+
for n in drop_bands:
|
|
42
|
+
if n.lower() in low:
|
|
43
|
+
keep[low.index(n.lower())] = False
|
|
44
|
+
log["dropped"].append(names[low.index(n.lower())])
|
|
45
|
+
for i in np.flatnonzero(keep):
|
|
46
|
+
v = np.concatenate([a[..., i][valid] for a in arrays])
|
|
47
|
+
v = v[np.isfinite(v)]
|
|
48
|
+
if v.size == 0 or np.unique(v, return_counts=True)[1].max() / v.size >= near_constant_share:
|
|
49
|
+
keep[i] = False
|
|
50
|
+
log["near_constant"].append(names[i])
|
|
51
|
+
out_names = [names[i] for i in np.flatnonzero(keep)]
|
|
52
|
+
out, nm = [], list(out_names)
|
|
53
|
+
for a in arrays:
|
|
54
|
+
cols = [a[..., i] for i in np.flatnonzero(keep)]
|
|
55
|
+
nm = list(out_names)
|
|
56
|
+
for n in circular_bands:
|
|
57
|
+
if n in nm:
|
|
58
|
+
j = nm.index(n)
|
|
59
|
+
rad = np.deg2rad(cols.pop(j)); nm.pop(j)
|
|
60
|
+
cols += [np.sin(rad), np.cos(rad)]; nm += [f"{n}_sin", f"{n}_cos"]
|
|
61
|
+
out.append(np.stack(cols, axis=-1).astype("float32"))
|
|
62
|
+
log["circular"] = [n for n in circular_bands if n in out_names]
|
|
63
|
+
return out, nm, log
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def align_bands(arr, names, wanted):
|
|
67
|
+
"""(H, W, B) bands of `arr` in the order `wanted` (matched by name, case-insensitive); `<band>_sin` / `<band>_cos`
|
|
68
|
+
are derived from `<band>` in degrees; absent bands are NaN. Returns (array, missing names)."""
|
|
69
|
+
low = {str(n).lower(): i for i, n in enumerate(names)}
|
|
70
|
+
out, missing = [], []
|
|
71
|
+
for w in wanted:
|
|
72
|
+
wl = str(w).lower()
|
|
73
|
+
if wl in low:
|
|
74
|
+
out.append(arr[..., low[wl]])
|
|
75
|
+
elif wl.endswith(("_sin", "_cos")) and wl[:-4] in low:
|
|
76
|
+
rad = np.deg2rad(arr[..., low[wl[:-4]]])
|
|
77
|
+
out.append(np.sin(rad) if wl.endswith("_sin") else np.cos(rad))
|
|
78
|
+
else:
|
|
79
|
+
out.append(np.full(arr.shape[:2], np.nan, dtype=np.float32)); missing.append(w)
|
|
80
|
+
return np.stack(out, axis=-1).astype(np.float32), missing
|
hazardfuse/metrics.py
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"""Evaluation metrics (notebook section 1): accuracy, Cohen's kappa and class-wise precision, recall and F1, with the
|
|
2
|
+
threshold-free ROC-AUC and PR-AUC, and a block-bootstrap interval for kappa."""
|
|
3
|
+
import numpy as np
|
|
4
|
+
from sklearn.metrics import average_precision_score, roc_auc_score
|
|
5
|
+
|
|
6
|
+
from .config import THRESHOLD
|
|
7
|
+
|
|
8
|
+
MAIN_METRICS = ["Accuracy", "Kappa", "Precision_0", "Recall_0", "F1_0", "Precision_1", "Recall_1", "F1_1"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def metrics_from_counts(tn, fp, fn, tp):
|
|
12
|
+
"""Threshold metrics from confusion counts (vectorised)."""
|
|
13
|
+
tn, fp, fn, tp = (np.asarray(v, dtype=float) for v in (tn, fp, fn, tp))
|
|
14
|
+
n = tn + fp + fn + tp
|
|
15
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
16
|
+
rec1, rec0 = tp / (tp + fn), tn / (tn + fp)
|
|
17
|
+
pre1, pre0 = tp / (tp + fp), tn / (tn + fn)
|
|
18
|
+
f1_1, f1_0 = 2 * tp / (2 * tp + fp + fn), 2 * tn / (2 * tn + fn + fp)
|
|
19
|
+
po = (tp + tn) / n
|
|
20
|
+
pe = ((tp + fp) * (tp + fn) + (tn + fn) * (tn + fp)) / n ** 2
|
|
21
|
+
kappa = (po - pe) / (1 - pe)
|
|
22
|
+
iou1, iou0 = tp / (tp + fp + fn), tn / (tn + fn + fp)
|
|
23
|
+
return {"Accuracy": po, "Balanced_Acc": (rec0 + rec1) / 2,
|
|
24
|
+
"Precision_0": pre0, "Recall_0": rec0, "F1_0": f1_0, "Precision_1": pre1, "Recall_1": rec1, "F1_1": f1_1,
|
|
25
|
+
"Macro_Precision": (pre0 + pre1) / 2, "Macro_Recall": (rec0 + rec1) / 2, "Macro_F1": (f1_0 + f1_1) / 2,
|
|
26
|
+
"Kappa": kappa, "IoU_0": iou0, "IoU_1": iou1, "mIoU": (iou0 + iou1) / 2}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def kappa_se(tn, fp, fn, tp):
|
|
30
|
+
"""Large-sample SE of Cohen's kappa (Fleiss, Cohen and Everitt, 1969)."""
|
|
31
|
+
p = np.array([[tn, fp], [fn, tp]], dtype=float)
|
|
32
|
+
n = p.sum()
|
|
33
|
+
if n == 0:
|
|
34
|
+
return np.nan
|
|
35
|
+
p /= n
|
|
36
|
+
row, col = p.sum(1), p.sum(0)
|
|
37
|
+
po, pe = np.trace(p), float(row @ col)
|
|
38
|
+
if np.isclose(pe, 1.0):
|
|
39
|
+
return np.nan
|
|
40
|
+
k = (po - pe) / (1 - pe)
|
|
41
|
+
A = np.sum(np.diag(p) * (1 - (row + col) * (1 - k)) ** 2)
|
|
42
|
+
B = (1 - k) ** 2 * np.sum(p * (1 - np.eye(2)) * (col[None, :] + row[:, None]) ** 2)
|
|
43
|
+
var = (A + B - (k - pe * (1 - k)) ** 2) / (n * (1 - pe) ** 2)
|
|
44
|
+
return float(np.sqrt(var)) if var > 0 else (0.0 if var > -1e-12 else np.nan)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def evaluate(y, prob, threshold=THRESHOLD):
|
|
48
|
+
"""Scores of a calibrated probability against 0/1 labels (decision: prob >= threshold)."""
|
|
49
|
+
y, p = np.asarray(y).astype(int), np.asarray(prob, dtype=float)
|
|
50
|
+
pred = p >= threshold
|
|
51
|
+
tn, fp, fn, tp = (int(((y == a) & (pred == b)).sum()) for a, b in ((0, 0), (0, 1), (1, 0), (1, 1)))
|
|
52
|
+
m = {k: float(v) for k, v in metrics_from_counts(tn, fp, fn, tp).items()}
|
|
53
|
+
two = len(np.unique(y)) == 2
|
|
54
|
+
m.update(Kappa_SE=kappa_se(tn, fp, fn, tp),
|
|
55
|
+
ROC_AUC=roc_auc_score(y, p) if two else np.nan,
|
|
56
|
+
PR_AUC_1=average_precision_score(y, p) if two else np.nan,
|
|
57
|
+
PR_AUC_0=average_precision_score(1 - y, 1 - p) if two else np.nan,
|
|
58
|
+
Pred_Pos_Rate=float(pred.mean()), Ref_Pos_Rate=float(y.mean()), TN=tn, FP=fp, FN=fn, TP=tp, N=len(y))
|
|
59
|
+
return m
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def block_counts(y, pred, blocks):
|
|
63
|
+
"""TN, FP, FN, TP per block."""
|
|
64
|
+
ub, inv = np.unique(blocks, return_inverse=True)
|
|
65
|
+
out = np.zeros((len(ub), 4))
|
|
66
|
+
for j, cond in enumerate([(y == 0) & ~pred, (y == 0) & pred, (y == 1) & ~pred, (y == 1) & pred]):
|
|
67
|
+
out[:, j] = np.bincount(inv, weights=cond.astype(float), minlength=len(ub))
|
|
68
|
+
return ub, out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def block_bootstrap(y, prob, blocks, n_boot=2000, seed=42, threshold=THRESHOLD, metrics=("Kappa",)):
|
|
72
|
+
"""95% block-bootstrap interval (2.5th, 97.5th percentile) of each metric: blocks resampled with replacement."""
|
|
73
|
+
counts = block_counts(np.asarray(y).astype(int), np.asarray(prob) >= threshold, blocks)[1]
|
|
74
|
+
draws = np.random.default_rng(seed).integers(0, len(counts), size=(n_boot, len(counts)))
|
|
75
|
+
boot = metrics_from_counts(*counts[draws].sum(1).T)
|
|
76
|
+
return {m: tuple(np.nanpercentile(boot[m], [2.5, 97.5])) for m in metrics}
|
hazardfuse/model.py
ADDED
|
@@ -0,0 +1,348 @@
|
|
|
1
|
+
"""The HazardFuse model: fit on a labelled site, map hazard at that site or at new sites, save and load."""
|
|
2
|
+
import json
|
|
3
|
+
import random
|
|
4
|
+
import tempfile
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import pandas as pd
|
|
9
|
+
import tensorflow as tf
|
|
10
|
+
from tensorflow.keras import Model
|
|
11
|
+
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
|
|
12
|
+
|
|
13
|
+
from . import __version__
|
|
14
|
+
from .calibration import apply_calibration, calibrate
|
|
15
|
+
from .config import DEFAULT_DATA, DEFAULT_MODEL, THRESHOLD, merged
|
|
16
|
+
from .groups import group_of
|
|
17
|
+
from .io import write_geotiff
|
|
18
|
+
from .metrics import MAIN_METRICS, block_bootstrap, evaluate
|
|
19
|
+
from .nn import Patches, network_from_cfg
|
|
20
|
+
from .split import block_split, split_summary
|
|
21
|
+
|
|
22
|
+
FORMAT = "hazardfuse-model"
|
|
23
|
+
META, WEIGHTS = "hazardfuse.json", "hazardfuse.weights.h5"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _to_map(values, valid):
|
|
27
|
+
m = np.full(valid.shape, np.nan, dtype=np.float32)
|
|
28
|
+
m[valid] = np.asarray(values, dtype=np.float32)
|
|
29
|
+
return m
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _jsonable(o):
|
|
33
|
+
if isinstance(o, dict):
|
|
34
|
+
return {str(k): _jsonable(v) for k, v in o.items()}
|
|
35
|
+
if isinstance(o, (list, tuple)):
|
|
36
|
+
return [_jsonable(v) for v in o]
|
|
37
|
+
if isinstance(o, np.ndarray):
|
|
38
|
+
return o.tolist()
|
|
39
|
+
if isinstance(o, (np.floating, np.integer, np.bool_)):
|
|
40
|
+
return o.item()
|
|
41
|
+
return o
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class HazardFuse:
|
|
45
|
+
"""Hazard-index-guided band attention and spatial embedding fusion.
|
|
46
|
+
|
|
47
|
+
For every pixel, a 21 x 21 patch of the standardised static bands enters two branches:
|
|
48
|
+
a center-pixel branch that weights the spectrum of the center pixel with sigmoid band-attention weights, and a
|
|
49
|
+
spatial branch (two 3 x 3 convolutions with batch normalisation, max pooling, a separable convolution and global
|
|
50
|
+
average pooling). A gated fusion joins the two embeddings, and a sigmoid unit gives the class-1 (higher-HI)
|
|
51
|
+
probability. Training: Adam, class-weighted binary cross-entropy, rotation and flip augmentation, early stopping
|
|
52
|
+
and learning-rate reduction on the validation blocks, best weights restored. The class-1 score is calibrated on
|
|
53
|
+
the training pixels (decision threshold 0.5).
|
|
54
|
+
|
|
55
|
+
Parameters: seed; verbose; any setting of :data:`hazardfuse.config.DEFAULT_MODEL` as a keyword argument
|
|
56
|
+
(e.g. ``epochs=50, fusion_gate=False``)."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, seed=42, verbose=True, **settings):
|
|
59
|
+
self.cfg = merged(DEFAULT_MODEL, settings)
|
|
60
|
+
self.seed = int(seed)
|
|
61
|
+
self.verbose = verbose
|
|
62
|
+
self.net_ = None
|
|
63
|
+
self.site_ = None
|
|
64
|
+
|
|
65
|
+
def _log(self, msg):
|
|
66
|
+
if self.verbose:
|
|
67
|
+
print(msg)
|
|
68
|
+
|
|
69
|
+
# ------------------------------------------------------------------------------------------------ fitting
|
|
70
|
+
def fit(self, site, masks=None, label_mask=None, split=None):
|
|
71
|
+
"""Fit on `site` (a :class:`hazardfuse.Site` with labels).
|
|
72
|
+
|
|
73
|
+
masks: split masks (dict with "train", "val", "test"); default: spatial block split with buffer of the site
|
|
74
|
+
(settings `split`, see :data:`hazardfuse.config.DEFAULT_SPLIT`). label_mask: labelled pixels used for
|
|
75
|
+
training and calibration (default: the training blocks). Early stopping uses the validation blocks."""
|
|
76
|
+
cfg = self.cfg
|
|
77
|
+
if site.Y is None:
|
|
78
|
+
raise ValueError("the site has no labels; build it with labels=... to fit a model")
|
|
79
|
+
masks = masks or block_split(site.Y, site.valid, **(split or {}))
|
|
80
|
+
lm = masks["train"] if label_mask is None else np.asarray(label_mask, dtype=bool)
|
|
81
|
+
if cfg["early_stop_on"] == "val" and not masks["val"].any():
|
|
82
|
+
raise ValueError("early_stop_on='val' needs validation pixels; use early_stop_on='none'")
|
|
83
|
+
random.seed(self.seed)
|
|
84
|
+
np.random.seed(self.seed)
|
|
85
|
+
stats = site.compute_stats(masks["train"]) # statistics of the training blocks
|
|
86
|
+
X = site.prepare(stats)
|
|
87
|
+
keep = [i for i, n in enumerate(site.band_names) if n not in cfg["drop_bands"]]
|
|
88
|
+
p, nb = cfg["patch"], len(keep)
|
|
89
|
+
if p % 2 == 0:
|
|
90
|
+
raise ValueError("the patch size must be odd")
|
|
91
|
+
tf.keras.backend.clear_session()
|
|
92
|
+
tf.keras.utils.set_random_seed(self.seed)
|
|
93
|
+
patches = Patches(X[..., keep], p)
|
|
94
|
+
y_l = site.Y[lm]
|
|
95
|
+
w_pos, w_neg = len(y_l) / (2 * max(y_l.sum(), 1)), len(y_l) / (2 * max(len(y_l) - y_l.sum(), 1))
|
|
96
|
+
net = network_from_cfg(cfg, nb)
|
|
97
|
+
net.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=cfg["lr"]), loss="binary_crossentropy",
|
|
98
|
+
metrics=["accuracy"])
|
|
99
|
+
self._log(f"{site.name}: {nb} input bands, patch {p} x {p}, {int(lm.sum()):,} training pixels "
|
|
100
|
+
f"(class-1 fraction {y_l.mean():.3f}), {net.count_params():,} parameters")
|
|
101
|
+
train_ds = lambda: patches.train_dataset(lm, site.Y, (w_neg, w_pos), cfg["batch"], True, self.seed)
|
|
102
|
+
if cfg["early_stop_on"] == "val":
|
|
103
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
104
|
+
ckpt = str(Path(tmp) / "best.weights.h5")
|
|
105
|
+
cb = [EarlyStopping(monitor="val_loss", patience=cfg["patience"], restore_best_weights=True),
|
|
106
|
+
ReduceLROnPlateau(monitor="val_loss", factor=0.5, patience=max(cfg["patience"] // 3, 2),
|
|
107
|
+
min_lr=1e-6),
|
|
108
|
+
ModelCheckpoint(ckpt, monitor="val_loss", save_best_only=True, save_weights_only=True)]
|
|
109
|
+
h = net.fit(train_ds(),
|
|
110
|
+
validation_data=patches.train_dataset(masks["val"], site.Y, (w_neg, w_pos), cfg["batch"],
|
|
111
|
+
False, self.seed),
|
|
112
|
+
epochs=cfg["epochs"], callbacks=cb, verbose=0)
|
|
113
|
+
net.load_weights(ckpt)
|
|
114
|
+
else:
|
|
115
|
+
h = net.fit(train_ds(), epochs=cfg["epochs"], verbose=0)
|
|
116
|
+
self.net_, self.keep_ = net, keep
|
|
117
|
+
self.schema_ = {"band_names": list(site.band_names), "input_bands": [site.band_names[i] for i in keep]}
|
|
118
|
+
self.stats_, self.data_ = stats, site.data
|
|
119
|
+
self.split_settings_ = masks.get("settings", {})
|
|
120
|
+
self.history_ = pd.DataFrame({"epoch": np.arange(1, len(h.history["loss"]) + 1),
|
|
121
|
+
**{k: [float(v) for v in vals] for k, vals in h.history.items()}})
|
|
122
|
+
self.n_params_ = int(net.count_params())
|
|
123
|
+
self.score_map_ = _to_map(self._raw_scores(X, site.valid), site.valid)
|
|
124
|
+
self.prob_map_, self.calibration_ = calibrate(self.score_map_, site.Y, site.valid, lm, cfg["threshold_rule"])
|
|
125
|
+
self.site_, self.masks_, self.label_mask_ = site, masks, lm
|
|
126
|
+
self.metrics_ = {k: evaluate(site.Y[masks[k]], self.prob_map_[masks[k]]) for k in ("train", "val", "test")
|
|
127
|
+
if masks[k].any()}
|
|
128
|
+
best = int(np.argmin(h.history["val_loss"])) + 1 if "val_loss" in h.history else len(h.history["loss"])
|
|
129
|
+
self._log(f"trained {len(h.history['loss'])} epochs (best epoch {best})")
|
|
130
|
+
if "test" in self.metrics_:
|
|
131
|
+
e = self.metrics_["test"]
|
|
132
|
+
self._log(f"test blocks: accuracy {e['Accuracy']:.4f} | kappa {e['Kappa']:.4f} | "
|
|
133
|
+
f"F1 class 0 {e['F1_0']:.4f} | F1 class 1 {e['F1_1']:.4f}")
|
|
134
|
+
return self
|
|
135
|
+
|
|
136
|
+
def _raw_scores(self, X, valid):
|
|
137
|
+
patches = Patches(X[..., self.keep_], self.cfg["patch"])
|
|
138
|
+
ds = patches.predict_dataset(valid, self.cfg["predict_batch"])
|
|
139
|
+
return self.net_.predict(ds, verbose=0).ravel().astype(np.float64)
|
|
140
|
+
|
|
141
|
+
def _check(self):
|
|
142
|
+
if self.net_ is None:
|
|
143
|
+
raise RuntimeError("the model is not fitted; call fit() or HazardFuse.load()")
|
|
144
|
+
|
|
145
|
+
def _own(self, site):
|
|
146
|
+
if site is None or site is self.site_:
|
|
147
|
+
if self.site_ is None:
|
|
148
|
+
raise ValueError("this model was loaded from a file: give the site to map")
|
|
149
|
+
return True
|
|
150
|
+
return False
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def schema(self):
|
|
154
|
+
"""Band names of the training site: build new sites with ``Site.from_folder(..., reference=model.schema)``."""
|
|
155
|
+
self._check()
|
|
156
|
+
return self.schema_
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def keras_model(self):
|
|
160
|
+
"""The fitted Keras network."""
|
|
161
|
+
self._check()
|
|
162
|
+
return self.net_
|
|
163
|
+
|
|
164
|
+
# ------------------------------------------------------------------------------------------------ prediction
|
|
165
|
+
def _prepare(self, site, normalisation):
|
|
166
|
+
if list(site.band_names) != list(self.schema_["band_names"]):
|
|
167
|
+
raise ValueError("the site bands differ from the model; build the site with "
|
|
168
|
+
"Site.from_folder(..., reference=model.schema)")
|
|
169
|
+
return site.prepare(stats=self.stats_ if normalisation == "source" else None)
|
|
170
|
+
|
|
171
|
+
def predict_scores(self, site=None, normalisation="source"):
|
|
172
|
+
"""Network class-1 probability at every valid pixel of `site` (map, NaN outside the site). At the training
|
|
173
|
+
site (site=None): the scores of the fit. At a new site (built with ``reference=model.schema``):
|
|
174
|
+
normalisation "source" (statistics of the training blocks) or "target" (statistics of the new site)."""
|
|
175
|
+
self._check()
|
|
176
|
+
if self._own(site):
|
|
177
|
+
return self.score_map_
|
|
178
|
+
return _to_map(self._raw_scores(self._prepare(site, normalisation), site.valid), site.valid)
|
|
179
|
+
|
|
180
|
+
def predict_proba(self, site=None, rule="source_cut", prevalence=None, normalisation="source"):
|
|
181
|
+
"""Calibrated class-1 (higher-hazard) map; class 1 where >= 0.5.
|
|
182
|
+
|
|
183
|
+
At the training site: the calibration of the training pixels. At a new site, `rule`: "source_cut" (ranks at
|
|
184
|
+
the new site cut at the training cut rank), "prevalence" (cut at 1 - `prevalence`, the expected class-1 share)
|
|
185
|
+
or "raw" (the network probability)."""
|
|
186
|
+
self._check()
|
|
187
|
+
if self._own(site):
|
|
188
|
+
return self.prob_map_
|
|
189
|
+
s = self.predict_scores(site, normalisation)
|
|
190
|
+
return apply_calibration(s[site.valid], site.valid, self.calibration_, rule, prevalence)
|
|
191
|
+
|
|
192
|
+
def predict(self, site=None, **kwargs):
|
|
193
|
+
"""Class map: 1 = higher hazard, 0 = lower hazard, 255 = no data."""
|
|
194
|
+
p = self.predict_proba(site, **kwargs)
|
|
195
|
+
return np.where(np.isfinite(p), (p >= THRESHOLD).astype(np.uint8), 255).astype(np.uint8)
|
|
196
|
+
|
|
197
|
+
# ------------------------------------------------------------------------------------------------ evaluation
|
|
198
|
+
def _eval_inputs(self, site, split, predict_kwargs):
|
|
199
|
+
own = self._own(site)
|
|
200
|
+
site = self.site_ if own else site
|
|
201
|
+
if site.Y is None:
|
|
202
|
+
raise ValueError("the site has no labels")
|
|
203
|
+
prob = self.predict_proba(None if own else site, **predict_kwargs)
|
|
204
|
+
if not own:
|
|
205
|
+
return site, prob, site.valid
|
|
206
|
+
if split == "heldout":
|
|
207
|
+
return site, prob, self.masks_["val"] | self.masks_["test"]
|
|
208
|
+
return site, prob, self.masks_[split]
|
|
209
|
+
|
|
210
|
+
def evaluate(self, site=None, split="test", n_boot=2000, block_size=None, **predict_kwargs):
|
|
211
|
+
"""Accuracy, Cohen's kappa, class-wise precision, recall and F1, ROC-AUC, PR-AUC and the confusion counts
|
|
212
|
+
(TN, FP, FN, TP), with a 95% block-bootstrap interval for kappa. At the training site: the pixels of `split`
|
|
213
|
+
("train", "val", "test" or "heldout" = val + test); at a new site with labels: every labelled pixel."""
|
|
214
|
+
self._check()
|
|
215
|
+
site, prob, mask = self._eval_inputs(site, split, predict_kwargs)
|
|
216
|
+
bs = block_size or self.split_settings_.get("block_size", 32)
|
|
217
|
+
rr, cc = np.indices(site.shape)
|
|
218
|
+
blocks = (rr // bs) * int(np.ceil(site.shape[1] / bs)) + (cc // bs)
|
|
219
|
+
out = evaluate(site.Y[mask], prob[mask])
|
|
220
|
+
if n_boot:
|
|
221
|
+
lo, hi = block_bootstrap(site.Y[mask], prob[mask], blocks[mask], n_boot, self.seed)["Kappa"]
|
|
222
|
+
out.update(Kappa_lo=lo, Kappa_hi=hi)
|
|
223
|
+
return out
|
|
224
|
+
|
|
225
|
+
def report(self, site=None, splits=("train", "val", "test"), **kwargs):
|
|
226
|
+
"""Table of accuracy, kappa and class-wise precision, recall and F1 (rows = splits, or the new site)."""
|
|
227
|
+
if site is not None and site is not self.site_:
|
|
228
|
+
return pd.DataFrame({site.name: self.evaluate(site, **kwargs)}).T[MAIN_METRICS]
|
|
229
|
+
return pd.DataFrame({s: self.evaluate(split=s, **kwargs) for s in splits}).T[MAIN_METRICS]
|
|
230
|
+
|
|
231
|
+
def confusion_matrix(self, site=None, split="test", **predict_kwargs):
|
|
232
|
+
"""2 x 2 confusion matrix (rows = reference class, columns = predicted class)."""
|
|
233
|
+
e = self.evaluate(site, split, n_boot=0, **predict_kwargs)
|
|
234
|
+
idx = ["Reference 0 (lower HI)", "Reference 1 (higher HI)"]
|
|
235
|
+
return pd.DataFrame([[e["TN"], e["FP"]], [e["FN"], e["TP"]]], index=idx,
|
|
236
|
+
columns=["Predicted 0", "Predicted 1"])
|
|
237
|
+
|
|
238
|
+
def split_summary(self):
|
|
239
|
+
self._check()
|
|
240
|
+
if self.site_ is None:
|
|
241
|
+
raise ValueError("this model was loaded from a file: the split is not stored")
|
|
242
|
+
return split_summary(self.site_.Y, self.masks_)
|
|
243
|
+
|
|
244
|
+
# ------------------------------------------------------------------------------------------------ interpretation
|
|
245
|
+
def band_attention(self, site=None, mask=None, split="test", normalisation="source"):
|
|
246
|
+
"""Mean band-attention weight of every input band over the patches centred on the pixels of `mask`
|
|
247
|
+
(default: the pixels of `split` at the training site, or every valid pixel of a new site), with its feature
|
|
248
|
+
group, sorted from the highest weight."""
|
|
249
|
+
self._check()
|
|
250
|
+
if "band_attention" not in [l.name for l in self.net_.layers]:
|
|
251
|
+
raise ValueError("this model has no band attention")
|
|
252
|
+
if self._own(site):
|
|
253
|
+
site, X = self.site_, self.site_.prepare(self.stats_)
|
|
254
|
+
mask = mask if mask is not None else (self.masks_["val"] | self.masks_["test"] if split == "heldout"
|
|
255
|
+
else self.masks_[split])
|
|
256
|
+
else:
|
|
257
|
+
X = self._prepare(site, normalisation)
|
|
258
|
+
mask = site.valid if mask is None else mask
|
|
259
|
+
mask = np.asarray(mask, dtype=bool) & site.valid
|
|
260
|
+
sub = Model(self.net_.input, self.net_.get_layer("band_attention").output)
|
|
261
|
+
ds = Patches(X[..., self.keep_], self.cfg["patch"]).predict_dataset(mask, self.cfg["predict_batch"])
|
|
262
|
+
w = sub.predict(ds, verbose=0).mean(axis=0)
|
|
263
|
+
names = self.schema_["input_bands"]
|
|
264
|
+
df = pd.DataFrame({"Band": names, "Feature group": group_of(names), "Weight": w.astype(float)})
|
|
265
|
+
return df.sort_values("Weight", ascending=False).reset_index(drop=True)
|
|
266
|
+
|
|
267
|
+
def group_attention(self, **kwargs):
|
|
268
|
+
"""Mean band-attention weight of every feature group."""
|
|
269
|
+
a = self.band_attention(**kwargs)
|
|
270
|
+
return a.groupby("Feature group")["Weight"].agg(["mean", "count"]).sort_values("mean", ascending=False)
|
|
271
|
+
|
|
272
|
+
def layer_table(self):
|
|
273
|
+
"""Every layer of the network: type, output shape, activation and parameters."""
|
|
274
|
+
self._check()
|
|
275
|
+
rows = []
|
|
276
|
+
for l in self.net_.layers:
|
|
277
|
+
c = l.get_config()
|
|
278
|
+
act = c.get("activation")
|
|
279
|
+
rows.append({"Layer": l.name, "Type": type(l).__name__,
|
|
280
|
+
"Output shape": " x ".join(str(int(v)) for v in l.output.shape[1:]),
|
|
281
|
+
"Activation": act if isinstance(act, str) and act != "linear" else "",
|
|
282
|
+
"Parameters": int(sum(np.prod(w.shape) for w in l.trainable_weights)),
|
|
283
|
+
"Non-trainable": int(sum(np.prod(w.shape) for w in l.non_trainable_weights))})
|
|
284
|
+
return pd.DataFrame(rows).set_index("Layer")
|
|
285
|
+
|
|
286
|
+
# ------------------------------------------------------------------------------------------------ output
|
|
287
|
+
def to_geotiffs(self, out_dir, site=None, prefix="HazardFuse", **predict_kwargs):
|
|
288
|
+
"""Write <prefix>_score.tif (calibrated class-1 score) and <prefix>_class.tif (0/1, 255 = no data) on the
|
|
289
|
+
grid of the site. Returns the paths."""
|
|
290
|
+
own = site is None or site is self.site_
|
|
291
|
+
site = self.site_ if own else site
|
|
292
|
+
if site is None:
|
|
293
|
+
raise ValueError("this model was loaded from a file: give the site to map")
|
|
294
|
+
if site.profile is None:
|
|
295
|
+
raise ValueError("the site has no raster profile (build it with from_folder or give profile=...)")
|
|
296
|
+
p = self.predict_proba(None if own else site, **predict_kwargs)
|
|
297
|
+
return [write_geotiff(Path(out_dir) / f"{prefix}_score.tif", p, site.profile, "float32", np.nan),
|
|
298
|
+
write_geotiff(Path(out_dir) / f"{prefix}_class.tif",
|
|
299
|
+
np.where(np.isfinite(p), p >= THRESHOLD, 255), site.profile, "uint8", 255)]
|
|
300
|
+
|
|
301
|
+
# ------------------------------------------------------------------------------------------------ save / load
|
|
302
|
+
def save(self, folder):
|
|
303
|
+
"""Save the fitted model to `folder`: hazardfuse.weights.h5 (Keras weights) and hazardfuse.json (settings,
|
|
304
|
+
band schema, standardisation, calibration, split settings, scores and training history)."""
|
|
305
|
+
self._check()
|
|
306
|
+
folder = Path(folder)
|
|
307
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
308
|
+
self.net_.save_weights(str(folder / WEIGHTS))
|
|
309
|
+
hist = getattr(self, "history_", None)
|
|
310
|
+
meta = {"format": FORMAT, "version": __version__, "seed": self.seed, "cfg": self.cfg,
|
|
311
|
+
"schema": self.schema_, "stats": self.stats_,
|
|
312
|
+
"calibration": {k: (bool(v) if k == "flipped" else v) for k, v in self.calibration_.items()},
|
|
313
|
+
"data": self.data_, "split": dict(self.split_settings_),
|
|
314
|
+
"metrics": getattr(self, "metrics_", {}), "n_params": self.n_params_,
|
|
315
|
+
"history": {} if hist is None or not len(hist) else {c: list(hist[c]) for c in hist.columns}}
|
|
316
|
+
(folder / META).write_text(json.dumps(_jsonable(meta), indent=1))
|
|
317
|
+
return folder
|
|
318
|
+
|
|
319
|
+
@classmethod
|
|
320
|
+
def load(cls, folder, verbose=True):
|
|
321
|
+
"""Load a model saved with :meth:`save` (or exported by section 12 of the paper notebook)."""
|
|
322
|
+
folder = Path(folder)
|
|
323
|
+
d = json.loads((folder / META).read_text())
|
|
324
|
+
if d.get("format") != FORMAT:
|
|
325
|
+
raise ValueError(f"{folder} does not hold a hazardfuse model")
|
|
326
|
+
m = cls(seed=d["seed"], verbose=verbose, **{k: v for k, v in d["cfg"].items() if k in DEFAULT_MODEL})
|
|
327
|
+
m.schema_ = d["schema"]
|
|
328
|
+
m.keep_ = [m.schema_["band_names"].index(b) for b in m.schema_["input_bands"]]
|
|
329
|
+
m.stats_ = {k: np.asarray(v, dtype=np.float64) for k, v in d["stats"].items()}
|
|
330
|
+
m.calibration_ = d["calibration"]
|
|
331
|
+
m.data_ = merged(DEFAULT_DATA, {k: v for k, v in d.get("data", {}).items() if k in DEFAULT_DATA})
|
|
332
|
+
m.split_settings_ = d.get("split", {})
|
|
333
|
+
m.metrics_ = d.get("metrics", {})
|
|
334
|
+
m.history_ = pd.DataFrame(d.get("history", {}))
|
|
335
|
+
tf.keras.backend.clear_session()
|
|
336
|
+
m.net_ = network_from_cfg(m.cfg, len(m.keep_))
|
|
337
|
+
m.net_.load_weights(str(folder / WEIGHTS))
|
|
338
|
+
m.n_params_ = int(m.net_.count_params())
|
|
339
|
+
return m
|
|
340
|
+
|
|
341
|
+
def summary(self):
|
|
342
|
+
"""Settings, size, band schema, calibration and scores (JSON-serialisable dict)."""
|
|
343
|
+
self._check()
|
|
344
|
+
return _jsonable({"version": __version__, "seed": self.seed, "parameters": self.n_params_,
|
|
345
|
+
"input_bands": len(self.schema_["input_bands"]), "calibration": self.calibration_,
|
|
346
|
+
"split": self.split_settings_,
|
|
347
|
+
"metrics": {k: {m: v.get(m) for m in MAIN_METRICS} for k, v in getattr(self, "metrics_", {}).items()},
|
|
348
|
+
"settings": self.cfg})
|
hazardfuse/nn.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""The HazardFuse network (Keras) and the patch pipeline (notebook section 5, `build_hazardfuse` and
|
|
2
|
+
`HazardFuseModel`)."""
|
|
3
|
+
import numpy as np
|
|
4
|
+
import tensorflow as tf
|
|
5
|
+
from tensorflow.keras import Model, layers
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def build_hazardfuse(input_shape, dropout=0.30, band_attention=True, center_branch=True, spatial_branch=True,
|
|
9
|
+
fusion_gate=True, name="HazardFuse"):
|
|
10
|
+
"""HazardFuse: center-pixel band-attention branch, patch spatial-embedding branch and gated fusion.
|
|
11
|
+
|
|
12
|
+
input_shape: (patch, patch, bands). The switches remove one component each (ablation). Output: probability that
|
|
13
|
+
the center pixel belongs to class 1 (higher HI). With 63 input bands and the default settings the network has
|
|
14
|
+
97,121 parameters (96,929 trainable)."""
|
|
15
|
+
if not (center_branch or spatial_branch):
|
|
16
|
+
raise ValueError("at least one branch is needed")
|
|
17
|
+
h, w, bands = input_shape
|
|
18
|
+
inp = layers.Input(input_shape, name="patch")
|
|
19
|
+
branches = []
|
|
20
|
+
if center_branch: # center-pixel band-attention branch
|
|
21
|
+
center = layers.Reshape((bands,), name="center_pixel")(
|
|
22
|
+
layers.Cropping2D(((h // 2, h // 2), (w // 2, w // 2)), name="center_crop")(inp))
|
|
23
|
+
if band_attention:
|
|
24
|
+
a = layers.Dense(max(16, bands // 2), activation="relu", name="band_attention_hidden")(center)
|
|
25
|
+
a = layers.Dense(bands, activation="sigmoid", name="band_attention")(a)
|
|
26
|
+
px = layers.Concatenate(name="raw_and_attended")([center, layers.Multiply(name="attended_bands")([center, a])])
|
|
27
|
+
else:
|
|
28
|
+
px = center
|
|
29
|
+
px = layers.Dense(96, activation="relu", name="center_embedding")(px)
|
|
30
|
+
branches.append(layers.Dropout(dropout, name="center_dropout")(px))
|
|
31
|
+
if spatial_branch: # patch spatial-embedding branch
|
|
32
|
+
s = inp
|
|
33
|
+
for k, f in enumerate((32, 64), start=1):
|
|
34
|
+
s = layers.Conv2D(f, 3, padding="same", use_bias=False, name=f"spatial_conv{k}")(s)
|
|
35
|
+
s = layers.Activation("relu", name=f"spatial_relu{k}")(layers.BatchNormalization(name=f"spatial_bn{k}")(s))
|
|
36
|
+
s = layers.MaxPooling2D(name="spatial_pool")(s)
|
|
37
|
+
s = layers.SeparableConv2D(96, 3, padding="same", activation="relu", name="spatial_sepconv")(s)
|
|
38
|
+
s = layers.GlobalAveragePooling2D(name="spatial_embedding")(s)
|
|
39
|
+
branches.append(layers.Dropout(dropout, name="spatial_dropout")(s))
|
|
40
|
+
fused = layers.Concatenate(name="fusion")(branches) if len(branches) == 2 else branches[0]
|
|
41
|
+
joint = layers.Dense(96, activation="relu", name="joint_embedding")(fused)
|
|
42
|
+
if fusion_gate and len(branches) == 2:
|
|
43
|
+
joint = layers.Multiply(name="gated_fusion")([joint, layers.Dense(96, activation="sigmoid", name="fusion_gate")(fused)])
|
|
44
|
+
joint = layers.Dropout(dropout, name="joint_dropout")(joint)
|
|
45
|
+
out = layers.Dense(1, activation="sigmoid", dtype="float32", name="p_higher_hi")(joint)
|
|
46
|
+
return Model(inp, out, name=name)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def network_from_cfg(cfg, n_bands):
|
|
50
|
+
p = cfg["patch"]
|
|
51
|
+
return build_hazardfuse((p, p, n_bands), cfg["dropout"], cfg["band_attention"], cfg["center_branch"],
|
|
52
|
+
cfg["spatial_branch"], cfg["fusion_gate"])
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Patches:
|
|
56
|
+
"""Reflect-padded standardised stack of one site; patches are cut on the fly around (row, col) pixels."""
|
|
57
|
+
|
|
58
|
+
def __init__(self, X, patch):
|
|
59
|
+
self.p, self.nb = int(patch), int(X.shape[-1])
|
|
60
|
+
pad = self.p // 2
|
|
61
|
+
self.xpad = tf.constant(np.pad(X.astype(np.float32), ((pad, pad), (pad, pad), (0, 0)), mode="reflect"))
|
|
62
|
+
|
|
63
|
+
def fetch(self, r, c):
|
|
64
|
+
return tf.slice(self.xpad, [r, c, 0], [self.p, self.p, self.nb])
|
|
65
|
+
|
|
66
|
+
def predict_dataset(self, mask, batch):
|
|
67
|
+
r, c = np.nonzero(mask)
|
|
68
|
+
return (tf.data.Dataset.from_tensor_slices((r.astype(np.int32), c.astype(np.int32)))
|
|
69
|
+
.map(self.fetch, num_parallel_calls=tf.data.AUTOTUNE).batch(batch).prefetch(tf.data.AUTOTUNE))
|
|
70
|
+
|
|
71
|
+
def train_dataset(self, mask, Y, weights, batch, training, seed):
|
|
72
|
+
"""Labelled patches of `mask` with class weights (w_neg, w_pos); training: shuffled, random quarter turn and
|
|
73
|
+
flips."""
|
|
74
|
+
r, c = np.nonzero(mask)
|
|
75
|
+
lab = Y[r, c].astype(np.float32)
|
|
76
|
+
wt = np.where(lab == 1, weights[1], weights[0]).astype(np.float32)
|
|
77
|
+
|
|
78
|
+
def aug(x):
|
|
79
|
+
x = tf.image.rot90(x, k=tf.random.uniform([], 0, 4, dtype=tf.int32))
|
|
80
|
+
return tf.image.random_flip_up_down(tf.image.random_flip_left_right(x))
|
|
81
|
+
|
|
82
|
+
ds = tf.data.Dataset.from_tensor_slices((r.astype(np.int32), c.astype(np.int32), lab, wt))
|
|
83
|
+
if training:
|
|
84
|
+
ds = ds.shuffle(len(lab), seed=seed, reshuffle_each_iteration=True)
|
|
85
|
+
ds = ds.map(lambda r_, c_, y_, w_: ((aug(self.fetch(r_, c_)) if training else self.fetch(r_, c_)), y_, w_),
|
|
86
|
+
num_parallel_calls=tf.data.AUTOTUNE)
|
|
87
|
+
return ds.batch(batch).prefetch(tf.data.AUTOTUNE)
|
hazardfuse/site.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""A site: static feature stack, optional 0/1 labels and optional continuous hazard index (HI), on one grid.
|
|
2
|
+
|
|
3
|
+
A site is built in one of two modes:
|
|
4
|
+
|
|
5
|
+
* **training site** (no `reference`): the bands are cleaned as in the paper notebook (section 2): `drop_bands` removed,
|
|
6
|
+
near-constant bands removed, circular bands (aspect) replaced by sine and cosine.
|
|
7
|
+
* **new site** (`reference` = the band schema of a fitted model, ``model.schema``): the bands are aligned by name to the
|
|
8
|
+
bands the model was trained on; absent bands are NaN and become the standardised mean (0).
|
|
9
|
+
|
|
10
|
+
:meth:`Site.prepare` standardises the stack with the statistics of a mask of this site, or with statistics given by a
|
|
11
|
+
fitted model (notebook section 4)."""
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
import warnings
|
|
14
|
+
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from .config import DEFAULT_DATA, merged
|
|
18
|
+
from .io import align_bands, clean_bands, find_tif, read_raster
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _stats(a):
|
|
22
|
+
"""Band mean and SD over the first axis (NaN ignored); non-finite means -> 0, SD <= 1e-12 -> 1."""
|
|
23
|
+
with warnings.catch_warnings():
|
|
24
|
+
warnings.simplefilter("ignore", category=RuntimeWarning)
|
|
25
|
+
m, s = np.nanmean(a, axis=0), np.nanstd(a, axis=0)
|
|
26
|
+
return np.where(np.isfinite(m), m, 0.0), np.where(np.isfinite(s) & (s > 1e-12), s, 1.0)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Site:
|
|
30
|
+
"""Inputs of one site. Build it with :meth:`from_folder` (GeoTIFFs) or :meth:`from_arrays`.
|
|
31
|
+
|
|
32
|
+
Attributes: name, profile (rasterio profile or None), X_raw (H, W, B) cleaned or aligned bands, band_names,
|
|
33
|
+
valid (H, W) bool, Y (H, W) uint8 labels or None, hi (H, W) HI scaled to 0-1 on the valid pixels or None,
|
|
34
|
+
data (band-cleaning settings), log (what the cleaning or the alignment did)."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, name, profile, X_raw, band_names, valid, Y=None, hi=None, data=None, log=None):
|
|
37
|
+
self.name, self.profile = name, profile
|
|
38
|
+
self.X_raw, self.band_names = X_raw, list(band_names)
|
|
39
|
+
self.valid, self.Y, self.hi = valid, Y, hi
|
|
40
|
+
self.data = data or merged(DEFAULT_DATA)
|
|
41
|
+
self.log = log or {}
|
|
42
|
+
|
|
43
|
+
# ------------------------------------------------------------------------------------------------ constructors
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_arrays(cls, static, band_names, labels=None, hi=None, profile=None, name="site", reference=None, **data):
|
|
46
|
+
"""Site from arrays.
|
|
47
|
+
|
|
48
|
+
static: (H, W, B) array; band_names: B names. labels: (H, W) 0/1 raster (any other value = no label) or None.
|
|
49
|
+
hi: continuous hazard-index raster or None. profile: rasterio profile (needed to write GeoTIFFs).
|
|
50
|
+
reference: band schema of a fitted model (``model.schema``) for a new site.
|
|
51
|
+
data: overrides of :data:`hazardfuse.config.DEFAULT_DATA`."""
|
|
52
|
+
cfg = merged(DEFAULT_DATA, data)
|
|
53
|
+
X_raw = np.asarray(static, dtype=np.float32)
|
|
54
|
+
band_names = list(band_names)
|
|
55
|
+
if X_raw.ndim != 3 or X_raw.shape[-1] != len(band_names):
|
|
56
|
+
raise ValueError(f"static must be (H, W, {len(band_names)}), got {X_raw.shape}")
|
|
57
|
+
H, W = X_raw.shape[:2]
|
|
58
|
+
valid = np.isfinite(X_raw).any(axis=-1)
|
|
59
|
+
Y = None
|
|
60
|
+
if labels is not None:
|
|
61
|
+
Y_raw = np.asarray(labels)
|
|
62
|
+
if Y_raw.shape != (H, W):
|
|
63
|
+
raise ValueError("feature and label grids differ")
|
|
64
|
+
valid &= np.isin(Y_raw, [0, 1])
|
|
65
|
+
Y = np.where(valid, Y_raw, 0).astype(np.uint8)
|
|
66
|
+
if reference is None:
|
|
67
|
+
log = {"feature_cleaning": cfg["feature_cleaning"]}
|
|
68
|
+
if cfg["feature_cleaning"]:
|
|
69
|
+
(X_raw,), band_names, log["static"] = clean_bands([X_raw], band_names, valid, cfg["drop_bands"],
|
|
70
|
+
cfg["circular_bands"], cfg["near_constant_share"])
|
|
71
|
+
else:
|
|
72
|
+
X_raw, missing = align_bands(X_raw, band_names, reference["band_names"])
|
|
73
|
+
band_names = list(reference["band_names"])
|
|
74
|
+
needed = set(reference.get("input_bands", band_names))
|
|
75
|
+
if missing:
|
|
76
|
+
warnings.warn(f"{name}: bands absent at this site (set to the standardised mean): {missing}")
|
|
77
|
+
log = {"aligned_to": "model schema", "missing": missing,
|
|
78
|
+
"missing_model_inputs": [b for b in missing if b in needed]}
|
|
79
|
+
hi_n = None
|
|
80
|
+
if hi is not None:
|
|
81
|
+
hi = np.asarray(hi, dtype=np.float32)
|
|
82
|
+
if hi.shape != (H, W):
|
|
83
|
+
raise ValueError("feature and HI grids differ")
|
|
84
|
+
lo, up = np.nanmin(hi[valid]), np.nanmax(hi[valid])
|
|
85
|
+
hi_n = np.nan_to_num((hi - lo) / max(up - lo, 1e-12), nan=0.0).astype(np.float32)
|
|
86
|
+
return cls(name, profile, X_raw, band_names, valid, Y, hi_n, cfg, log)
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def from_folder(cls, folder, features, labels=None, hi=None, name=None, reference=None, **data):
|
|
90
|
+
"""Site from GeoTIFFs in `folder` (file stems without extension; missing optional files are skipped).
|
|
91
|
+
|
|
92
|
+
features: static stack whose band descriptions are the band names. labels: 0/1 label raster. hi: continuous
|
|
93
|
+
HI raster. reference: ``model.schema`` of a fitted model, for a new site."""
|
|
94
|
+
folder = Path(folder)
|
|
95
|
+
Xs, profile, names = read_raster(find_tif(folder, features))
|
|
96
|
+
X_raw = np.transpose(Xs, (1, 2, 0))
|
|
97
|
+
if not all(names):
|
|
98
|
+
raise ValueError(f"{features}: the GeoTIFF has no band descriptions; bands are matched by name")
|
|
99
|
+
H, W = X_raw.shape[:2]
|
|
100
|
+
|
|
101
|
+
def optional(stem):
|
|
102
|
+
if not stem:
|
|
103
|
+
return None
|
|
104
|
+
try:
|
|
105
|
+
a = read_raster(find_tif(folder, stem))[0][0]
|
|
106
|
+
except FileNotFoundError:
|
|
107
|
+
return None
|
|
108
|
+
if a.shape != (H, W):
|
|
109
|
+
raise ValueError(f"{stem}: grid {a.shape} differs from the static stack {(H, W)}")
|
|
110
|
+
return a
|
|
111
|
+
|
|
112
|
+
return cls.from_arrays(X_raw, names, optional(labels), optional(hi), profile, name or features, reference,
|
|
113
|
+
**data)
|
|
114
|
+
|
|
115
|
+
# ------------------------------------------------------------------------------------------------ preparation
|
|
116
|
+
@property
|
|
117
|
+
def shape(self):
|
|
118
|
+
return self.valid.shape
|
|
119
|
+
|
|
120
|
+
def compute_stats(self, mask=None):
|
|
121
|
+
"""Band mean and SD over the pixels of `mask` (default: every valid pixel)."""
|
|
122
|
+
m = self.valid if mask is None else (np.asarray(mask, dtype=bool) & self.valid)
|
|
123
|
+
bm, bs = _stats(self.X_raw[m])
|
|
124
|
+
return {"band_mean": bm, "band_std": bs}
|
|
125
|
+
|
|
126
|
+
def prepare(self, stats=None, mask=None):
|
|
127
|
+
"""Standardised (H, W, B) float32 stack, 0 outside the valid pixels and for missing values. stats: from
|
|
128
|
+
:meth:`compute_stats` (e.g. those stored in a fitted model); default: computed from `mask` of this site."""
|
|
129
|
+
st = self.compute_stats(mask) if stats is None else stats
|
|
130
|
+
mean, std = (np.asarray(st[k], dtype=np.float64) for k in ("band_mean", "band_std"))
|
|
131
|
+
X = np.nan_to_num((self.X_raw - mean) / std, nan=0.0, posinf=0.0, neginf=0.0).astype(np.float32)
|
|
132
|
+
X[~self.valid] = 0.0
|
|
133
|
+
return X
|
|
134
|
+
|
|
135
|
+
def schema(self):
|
|
136
|
+
"""Band schema that new sites are aligned to."""
|
|
137
|
+
return {"band_names": list(self.band_names)}
|
|
138
|
+
|
|
139
|
+
def __repr__(self):
|
|
140
|
+
H, W = self.shape
|
|
141
|
+
extra = ""
|
|
142
|
+
if self.Y is not None:
|
|
143
|
+
extra = f", class-1 fraction {self.Y[self.valid].mean():.3f}"
|
|
144
|
+
return (f"Site({self.name!r}: {H} x {W}, {int(self.valid.sum()):,} valid pixels, {len(self.band_names)} bands, "
|
|
145
|
+
f"labels: {self.Y is not None}{extra}, HI: {self.hi is not None})")
|
hazardfuse/split.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Spatial block split with a buffer (notebook section 3).
|
|
2
|
+
|
|
3
|
+
The grid is cut into square blocks. Whole blocks are assigned to training, validation and test so that the shares of
|
|
4
|
+
valid pixels and the class-1 fraction of each part are close to their targets (best of `n_trials` random orders).
|
|
5
|
+
Training pixels closer than `buffer_px` to a validation or test block, and validation pixels closer than `buffer_px` to
|
|
6
|
+
a test block, are moved to the buffer and used for nothing."""
|
|
7
|
+
import numpy as np
|
|
8
|
+
from scipy.ndimage import distance_transform_edt
|
|
9
|
+
|
|
10
|
+
from .config import DEFAULT_SPLIT
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def block_split(Y, valid, block_size=None, frac=None, buffer_px=None, n_trials=None, seed=None):
|
|
14
|
+
"""Masks of the split. Returns a dict with boolean (H, W) masks "train", "val", "test", "buffer", the block id of
|
|
15
|
+
every pixel ("block_id") and the block assignment ("block_split": -1 empty, 0 training, 1 validation, 2 test)."""
|
|
16
|
+
p = DEFAULT_SPLIT
|
|
17
|
+
block_size = p["block_size"] if block_size is None else block_size
|
|
18
|
+
frac = p["frac"] if frac is None else frac
|
|
19
|
+
buffer_px = p["buffer_px"] if buffer_px is None else buffer_px
|
|
20
|
+
n_trials = p["n_trials"] if n_trials is None else n_trials
|
|
21
|
+
seed = p["seed"] if seed is None else seed
|
|
22
|
+
|
|
23
|
+
Y, valid = np.asarray(Y), np.asarray(valid, dtype=bool)
|
|
24
|
+
rows, cols = valid.shape
|
|
25
|
+
n_block_rows, n_block_cols = int(np.ceil(rows / block_size)), int(np.ceil(cols / block_size))
|
|
26
|
+
rr, cc = np.indices((rows, cols))
|
|
27
|
+
block_id = (rr // block_size) * n_block_cols + (cc // block_size)
|
|
28
|
+
n_blocks = n_block_rows * n_block_cols
|
|
29
|
+
blk_n = np.bincount(block_id[valid], minlength=n_blocks).astype(float)
|
|
30
|
+
blk_pos = np.bincount(block_id[valid], weights=Y[valid], minlength=n_blocks)
|
|
31
|
+
candidates = np.flatnonzero(blk_n > 0)
|
|
32
|
+
n_valid, p_all = valid.sum(), Y[valid].mean()
|
|
33
|
+
f_train, f_val, f_test = frac
|
|
34
|
+
|
|
35
|
+
def propose(rng):
|
|
36
|
+
order = rng.permutation(candidates)
|
|
37
|
+
share = blk_n[order] / n_valid
|
|
38
|
+
mid = np.cumsum(share) - share / 2
|
|
39
|
+
assign = np.full(n_blocks, -1, dtype=int)
|
|
40
|
+
assign[order] = np.where(mid < f_test, 2, np.where(mid < f_test + f_val, 1, 0))
|
|
41
|
+
return assign
|
|
42
|
+
|
|
43
|
+
def score(assign):
|
|
44
|
+
s = 0.0
|
|
45
|
+
for code, target in ((2, f_test), (1, f_val), (0, f_train)):
|
|
46
|
+
sel = assign == code
|
|
47
|
+
n, pos = blk_n[sel].sum(), blk_pos[sel].sum()
|
|
48
|
+
if n == 0 or pos == 0 or pos == n:
|
|
49
|
+
return np.inf
|
|
50
|
+
s += abs(n / n_valid - target) + abs(pos / n - p_all)
|
|
51
|
+
return s
|
|
52
|
+
|
|
53
|
+
rng = np.random.default_rng(seed)
|
|
54
|
+
best, best_score = None, np.inf
|
|
55
|
+
for _ in range(n_trials):
|
|
56
|
+
cand = propose(rng)
|
|
57
|
+
s = score(cand)
|
|
58
|
+
if s < best_score:
|
|
59
|
+
best, best_score = cand, s
|
|
60
|
+
if best is None:
|
|
61
|
+
raise ValueError("no split with both classes in every part was found; use smaller blocks or more trials")
|
|
62
|
+
split = best[block_id]
|
|
63
|
+
dist_to_eval = distance_transform_edt(~np.isin(split, [1, 2]))
|
|
64
|
+
dist_to_test = distance_transform_edt(split != 2)
|
|
65
|
+
train = valid & (split == 0) & (dist_to_eval > buffer_px)
|
|
66
|
+
val = valid & (split == 1) & (dist_to_test > buffer_px)
|
|
67
|
+
test = valid & (split == 2)
|
|
68
|
+
return {"train": train, "val": val, "test": test, "buffer": valid & ~(train | val | test),
|
|
69
|
+
"block_id": block_id, "block_split": split,
|
|
70
|
+
"settings": dict(block_size=block_size, frac=tuple(frac), buffer_px=buffer_px, n_trials=n_trials, seed=seed)}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def split_summary(Y, masks):
|
|
74
|
+
"""Pixels, share of the valid pixels and class-1 fraction of every part."""
|
|
75
|
+
import pandas as pd
|
|
76
|
+
n_valid = sum(int(masks[k].sum()) for k in ("train", "buffer", "val", "test"))
|
|
77
|
+
return pd.DataFrame({name: {"Pixels": int(masks[k].sum()), "Share (%)": 100 * masks[k].sum() / max(n_valid, 1),
|
|
78
|
+
"Class-1 fraction": float(np.asarray(Y)[masks[k]].mean()) if masks[k].any() else np.nan}
|
|
79
|
+
for name, k in (("Train", "train"), ("Buffer", "buffer"), ("Validation", "val"),
|
|
80
|
+
("Test", "test"))}).T
|
hazardfuse/synthetic.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""Small synthetic site (a hazard plume down-gradient of a source) for examples and tests."""
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
STATIC = ["B4", "B8", "NDVI", "CIRE", "CSTV_NDVI_Diff", "NDVI_Rate", "DEM", "Slope_deg", "Aspect_deg", "TWI", "pH",
|
|
5
|
+
"Temperature", "Humidity", "DW_Trees", "DW_LandCover", "QA60", "Constant"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def make_site_arrays(H=48, W=64, seed=0):
|
|
9
|
+
"""Arrays for :meth:`hazardfuse.Site.from_arrays`: static (H, W, 17), band_names, labels (0/1, NaN in the two
|
|
10
|
+
top rows) and hi. The plume lowers NDVI and raises B4 east of a source near (12, 14)."""
|
|
11
|
+
rng = np.random.default_rng(seed)
|
|
12
|
+
rr, cc = np.indices((H, W))
|
|
13
|
+
n = lambda s: rng.normal(0, s, (H, W))
|
|
14
|
+
dem = 300.0 - 0.8 * cc - 0.3 * rr + n(0.5)
|
|
15
|
+
plume = np.exp(-((rr - 14) ** 2) / 120.0 - np.clip(cc - 14, 0, None) / 25.0) * (cc >= 10)
|
|
16
|
+
hi = plume + 0.05 * rng.normal(size=(H, W))
|
|
17
|
+
labels = (hi > np.quantile(hi, 0.6)).astype(np.float32)
|
|
18
|
+
labels[:2, :] = np.nan # unlabelled rows
|
|
19
|
+
static = np.stack([
|
|
20
|
+
0.1 + 0.05 * plume + n(.01), 0.3 - 0.1 * plume + n(.01), 0.6 - 0.3 * plume + n(.02), 2.0 - plume + n(.05),
|
|
21
|
+
-0.2 * plume + n(.02), -0.05 * plume + n(.01), dem, rng.uniform(0, 5, (H, W)), rng.uniform(0, 360, (H, W)),
|
|
22
|
+
8 + n(1), 6 + n(.3), 20 + n(.2), 70 + n(1), rng.uniform(0, 1, (H, W)),
|
|
23
|
+
rng.integers(0, 9, (H, W)).astype(float), rng.integers(0, 2, (H, W)).astype(float), np.ones((H, W))], -1)
|
|
24
|
+
return dict(static=static.astype(np.float32), band_names=list(STATIC), labels=labels, hi=hi.astype(np.float32))
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hazardfuse
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Hazard-index-guided band attention and spatial embedding fusion for mapping leached-metal-associated hazard from satellite and geospatial data
|
|
5
|
+
Author-email: Salman Karim <salmankarim@vt.edu>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/salmansust/hazardfuse
|
|
8
|
+
Project-URL: Source, https://github.com/salmansust/hazardfuse
|
|
9
|
+
Project-URL: Issues, https://github.com/salmansust/hazardfuse/issues
|
|
10
|
+
Keywords: band attention,deep learning,remote sensing,Sentinel-2,groundwater,hazard mapping,coal combustion residuals,leached metals,GeoAI
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Topic :: Scientific/Engineering :: GIS
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: numpy>=1.23
|
|
26
|
+
Requires-Dist: pandas>=1.5
|
|
27
|
+
Requires-Dist: scipy>=1.9
|
|
28
|
+
Requires-Dist: scikit-learn>=1.2
|
|
29
|
+
Requires-Dist: tensorflow>=2.12
|
|
30
|
+
Requires-Dist: rasterio>=1.3
|
|
31
|
+
Requires-Dist: pyyaml>=6.0
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Requires-Dist: pytest>=7; extra == "dev"
|
|
34
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
35
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
36
|
+
Dynamic: license-file
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
hazardfuse/__init__.py,sha256=pj7Ojx1lOuT1OynJnUHQ9N3BrIkvDinc67tdn_fBXbM,1866
|
|
2
|
+
hazardfuse/__main__.py,sha256=bYt9eEaoRQWdejEHFD8REx9jxVEdZptECFsV7F49Ink,30
|
|
3
|
+
hazardfuse/calibration.py,sha256=TbZJGcJBBTHYQpIJ2OI24InmLZ1TUmSM1iDZQuUuLGU,3028
|
|
4
|
+
hazardfuse/cli.py,sha256=-9ATogsAfmY35U9XkkmnFJ5TnBbtuZ6izXx7f6D-V90,5176
|
|
5
|
+
hazardfuse/config.py,sha256=aExD2MMnO6xs7yy4XDEkuSWLMIIz0l2MpITc57CIS-E,2590
|
|
6
|
+
hazardfuse/groups.py,sha256=iOP6aovU95zujXQOWoQJjyMFSD9A4JqF-G4nNsispjA,1245
|
|
7
|
+
hazardfuse/io.py,sha256=G-NHNUNg1mhFJ95XE4TTgQCjXuFC8MGNpvJ43XuShEs,3705
|
|
8
|
+
hazardfuse/metrics.py,sha256=hqUhfEikB6gIninBWbSmW6DU7Xte-SPVJe2UHO8AGPM,3874
|
|
9
|
+
hazardfuse/model.py,sha256=rsKj2x1XyCWONiswrhv8Sj_R3IpAZGDcvDO3hXJoxn8,19486
|
|
10
|
+
hazardfuse/nn.py,sha256=xTZuCrZKU-6QmU53F6Y88jSwoW-g1tyW7fwOX9c2BOI,4920
|
|
11
|
+
hazardfuse/site.py,sha256=tC4RLMSv6w1WGjALfgAX-ZasiTXDqIDP4VgiSRFHPZU,7511
|
|
12
|
+
hazardfuse/split.py,sha256=vfcbx5r4h3v7ZP6aYOF1bP88agh5GJuaV79Ner--2es,4077
|
|
13
|
+
hazardfuse/synthetic.py,sha256=dG05OE8jxxVEVRlk2pUWCXhNPSRGhp9nDFNzeI2Ro9U,1587
|
|
14
|
+
hazardfuse-0.1.0.dist-info/licenses/LICENSE,sha256=WizOE4CLAzYra5NdteS2LnOOGkZf4xCJpgC9vOKyc7U,1069
|
|
15
|
+
hazardfuse-0.1.0.dist-info/METADATA,sha256=R_ZsYEHSzg3ljkrNKqR3PdMLtdJWr_IkHVBiSSQwjYE,1616
|
|
16
|
+
hazardfuse-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
17
|
+
hazardfuse-0.1.0.dist-info/entry_points.txt,sha256=RQTWffpCl1OIhcsI_fWy5rrT89LNJv04zkU7U_f9zo4,51
|
|
18
|
+
hazardfuse-0.1.0.dist-info/top_level.txt,sha256=QMhYjzp6RFUh96ujiIeYar-GQGQCh0clfeCv98c5sxI,11
|
|
19
|
+
hazardfuse-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Salman Karim
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hazardfuse
|