limen-ml 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.
- limen_ml/__init__.py +22 -0
- limen_ml/drift.py +211 -0
- limen_ml/folds.py +60 -0
- limen_ml/matrix.py +156 -0
- limen_ml/metrics.py +89 -0
- limen_ml/py.typed +0 -0
- limen_ml/rainfall_cnn.py +200 -0
- limen_ml/train.py +297 -0
- limen_ml-0.1.0.dist-info/METADATA +100 -0
- limen_ml-0.1.0.dist-info/RECORD +12 -0
- limen_ml-0.1.0.dist-info/WHEEL +4 -0
- limen_ml-0.1.0.dist-info/licenses/LICENSE +202 -0
limen_ml/__init__.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""The machine learning of Limen: train, calibrate, monitor and serve hazard models.
|
|
2
|
+
|
|
3
|
+
- :mod:`limen_ml.matrix`: training samples into an ordered matrix;
|
|
4
|
+
- :mod:`limen_ml.folds`: spatial blocks for cross-validation;
|
|
5
|
+
- :mod:`limen_ml.train`: tuning, cross-validation, comparison of algorithms,
|
|
6
|
+
calibration and the final fit (the ``train`` extra);
|
|
7
|
+
- :mod:`limen_ml.metrics`: AUC-PR, operating points, conformal bands;
|
|
8
|
+
- :mod:`limen_ml.drift`: drift of features and predictions, and when to retrain;
|
|
9
|
+
- :mod:`limen_ml.rainfall_cnn`: a small network over a week of rain (the ``dl``
|
|
10
|
+
and ``serve`` extras).
|
|
11
|
+
|
|
12
|
+
No database, no tracking server, no feature schema: the application brings
|
|
13
|
+
its samples and its schema, and logs what it wants. A model never decides an
|
|
14
|
+
alert: the official warning is the criticality bulletin of the Civil
|
|
15
|
+
Protection Department.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from importlib.metadata import version
|
|
19
|
+
|
|
20
|
+
__version__ = version("limen-ml")
|
|
21
|
+
|
|
22
|
+
__all__ = ["__version__"]
|
limen_ml/drift.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
"""Has the world moved away from the data the model learnt from?
|
|
2
|
+
|
|
3
|
+
Three signals, each on plain sequences of numbers:
|
|
4
|
+
|
|
5
|
+
- :func:`population_stability_index`: the drift of one feature between the
|
|
6
|
+
training distribution and a recent one, in deciles of the reference;
|
|
7
|
+
- :func:`ks_distance`: the two-sample Kolmogorov-Smirnov statistic;
|
|
8
|
+
- :func:`prediction_drift`: the change of the mean predicted probability.
|
|
9
|
+
|
|
10
|
+
:func:`make_report` checks them against thresholds, :func:`worst` picks the
|
|
11
|
+
feature that drifts most, and :class:`RetrainingTrigger` says whether to train
|
|
12
|
+
again: on drift, or when enough new events have arrived. It never promotes a
|
|
13
|
+
model.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
from collections.abc import Mapping, Sequence
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True, slots=True)
|
|
24
|
+
class DriftReport:
|
|
25
|
+
"""The three drift values and whether each crosses its threshold."""
|
|
26
|
+
|
|
27
|
+
psi: float
|
|
28
|
+
ks: float
|
|
29
|
+
pred_drift: float
|
|
30
|
+
psi_alert: bool
|
|
31
|
+
ks_alert: bool
|
|
32
|
+
pred_alert: bool
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def any_alert(self) -> bool:
|
|
36
|
+
return self.psi_alert or self.ks_alert or self.pred_alert
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _safe_log(x: float) -> float:
|
|
40
|
+
return math.log(max(x, 1e-9))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def population_stability_index(
|
|
44
|
+
reference: Sequence[float],
|
|
45
|
+
candidate: Sequence[float],
|
|
46
|
+
*,
|
|
47
|
+
n_buckets: int = 10,
|
|
48
|
+
) -> float:
|
|
49
|
+
"""PSI between two univariate distributions.
|
|
50
|
+
|
|
51
|
+
Buckets are quantile-based on the reference. Empty buckets get a
|
|
52
|
+
small floor to keep the log finite.
|
|
53
|
+
"""
|
|
54
|
+
if not reference or not candidate:
|
|
55
|
+
return 0.0
|
|
56
|
+
|
|
57
|
+
sorted_ref = sorted(reference)
|
|
58
|
+
bucket_edges = [
|
|
59
|
+
sorted_ref[min(int(i / n_buckets * (len(sorted_ref) - 1)), len(sorted_ref) - 1)]
|
|
60
|
+
for i in range(n_buckets + 1)
|
|
61
|
+
]
|
|
62
|
+
# Force the last edge to be the max to capture the tail.
|
|
63
|
+
bucket_edges[-1] = sorted_ref[-1]
|
|
64
|
+
|
|
65
|
+
def _hist(values: Sequence[float]) -> list[float]:
|
|
66
|
+
counts = [0] * n_buckets
|
|
67
|
+
for v in values:
|
|
68
|
+
for i in range(n_buckets):
|
|
69
|
+
lo, hi = bucket_edges[i], bucket_edges[i + 1]
|
|
70
|
+
if (v >= lo and v < hi) or (i == n_buckets - 1 and v == hi):
|
|
71
|
+
counts[i] += 1
|
|
72
|
+
break
|
|
73
|
+
total = float(sum(counts)) or 1.0
|
|
74
|
+
return [c / total for c in counts]
|
|
75
|
+
|
|
76
|
+
ref_hist = _hist(reference)
|
|
77
|
+
cand_hist = _hist(candidate)
|
|
78
|
+
psi = 0.0
|
|
79
|
+
for r, c in zip(ref_hist, cand_hist, strict=True):
|
|
80
|
+
r_safe = max(r, 1e-6)
|
|
81
|
+
c_safe = max(c, 1e-6)
|
|
82
|
+
psi += (c_safe - r_safe) * (_safe_log(c_safe) - _safe_log(r_safe))
|
|
83
|
+
# Defensive: PSI is sometimes negative due to floating-point noise.
|
|
84
|
+
return float(max(psi, 0.0))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def ks_distance(reference: Sequence[float], candidate: Sequence[float]) -> float:
|
|
88
|
+
"""Two-sample Kolmogorov-Smirnov statistic ∈ [0, 1].
|
|
89
|
+
|
|
90
|
+
Computes ``max_x |F_a(x) - F_b(x)|`` on the empirical CDFs. Ties
|
|
91
|
+
between the two samples advance both pointers — important so the
|
|
92
|
+
statistic is exactly zero on identical inputs.
|
|
93
|
+
"""
|
|
94
|
+
if not reference or not candidate:
|
|
95
|
+
return 0.0
|
|
96
|
+
a = sorted(reference)
|
|
97
|
+
b = sorted(candidate)
|
|
98
|
+
n_a = float(len(a))
|
|
99
|
+
n_b = float(len(b))
|
|
100
|
+
i = j = 0
|
|
101
|
+
ks = 0.0
|
|
102
|
+
while i < len(a) and j < len(b):
|
|
103
|
+
if a[i] < b[j]:
|
|
104
|
+
i += 1
|
|
105
|
+
elif a[i] > b[j]:
|
|
106
|
+
j += 1
|
|
107
|
+
else:
|
|
108
|
+
# Equal values — advance both so identical samples → KS = 0.
|
|
109
|
+
i += 1
|
|
110
|
+
j += 1
|
|
111
|
+
diff = abs(i / n_a - j / n_b)
|
|
112
|
+
if diff > ks:
|
|
113
|
+
ks = diff
|
|
114
|
+
# Finish remaining tail.
|
|
115
|
+
while i < len(a):
|
|
116
|
+
i += 1
|
|
117
|
+
diff = abs(i / n_a - j / n_b)
|
|
118
|
+
if diff > ks:
|
|
119
|
+
ks = diff
|
|
120
|
+
while j < len(b):
|
|
121
|
+
j += 1
|
|
122
|
+
diff = abs(i / n_a - j / n_b)
|
|
123
|
+
if diff > ks:
|
|
124
|
+
ks = diff
|
|
125
|
+
return float(ks)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def prediction_drift(reference_probs: Sequence[float], candidate_probs: Sequence[float]) -> float:
|
|
129
|
+
"""Absolute change in mean predicted probability."""
|
|
130
|
+
if not reference_probs or not candidate_probs:
|
|
131
|
+
return 0.0
|
|
132
|
+
return float(
|
|
133
|
+
abs(
|
|
134
|
+
sum(candidate_probs) / len(candidate_probs)
|
|
135
|
+
- sum(reference_probs) / len(reference_probs)
|
|
136
|
+
)
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def make_report(
|
|
141
|
+
*,
|
|
142
|
+
reference: Sequence[float],
|
|
143
|
+
candidate: Sequence[float],
|
|
144
|
+
reference_probs: Sequence[float],
|
|
145
|
+
candidate_probs: Sequence[float],
|
|
146
|
+
psi_alert: float,
|
|
147
|
+
ks_alert: float,
|
|
148
|
+
pred_alert: float,
|
|
149
|
+
) -> DriftReport:
|
|
150
|
+
psi = population_stability_index(reference, candidate)
|
|
151
|
+
ks = ks_distance(reference, candidate)
|
|
152
|
+
pd = prediction_drift(reference_probs, candidate_probs)
|
|
153
|
+
return DriftReport(
|
|
154
|
+
psi=psi,
|
|
155
|
+
ks=ks,
|
|
156
|
+
pred_drift=pd,
|
|
157
|
+
psi_alert=psi >= psi_alert,
|
|
158
|
+
ks_alert=ks >= ks_alert,
|
|
159
|
+
pred_alert=pd >= pred_alert,
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def worst(reports: Mapping[str, DriftReport]) -> tuple[str, DriftReport]:
|
|
164
|
+
"""The feature that drifts most: first one over a threshold, then the highest PSI.
|
|
165
|
+
|
|
166
|
+
A retraining trigger looks at one feature, the worst: summing the alerts of
|
|
167
|
+
seventeen columns would retrain on noise.
|
|
168
|
+
"""
|
|
169
|
+
if not reports:
|
|
170
|
+
raise ValueError("no feature to compare")
|
|
171
|
+
return max(reports.items(), key=lambda kv: (kv[1].any_alert, kv[1].psi, kv[0]))
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
@dataclass(frozen=True, slots=True)
|
|
175
|
+
class RetrainingTrigger:
|
|
176
|
+
"""Decision result for one monitoring tick."""
|
|
177
|
+
|
|
178
|
+
should_retrain: bool
|
|
179
|
+
reason: str
|
|
180
|
+
|
|
181
|
+
@classmethod
|
|
182
|
+
def from_inputs(
|
|
183
|
+
cls,
|
|
184
|
+
*,
|
|
185
|
+
drift: DriftReport,
|
|
186
|
+
new_events_since_last_train: int,
|
|
187
|
+
new_events_threshold: int = 50,
|
|
188
|
+
) -> RetrainingTrigger:
|
|
189
|
+
if drift.psi_alert:
|
|
190
|
+
return cls(True, f"PSI={drift.psi:.3f} ≥ threshold")
|
|
191
|
+
if drift.ks_alert:
|
|
192
|
+
return cls(True, f"KS={drift.ks:.3f} ≥ threshold")
|
|
193
|
+
if drift.pred_alert:
|
|
194
|
+
return cls(True, f"prediction_drift={drift.pred_drift:.3f} ≥ threshold")
|
|
195
|
+
if new_events_since_last_train >= new_events_threshold:
|
|
196
|
+
return cls(
|
|
197
|
+
True,
|
|
198
|
+
f"{new_events_since_last_train} new events ≥ {new_events_threshold}",
|
|
199
|
+
)
|
|
200
|
+
return cls(False, "no signals")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
__all__ = [
|
|
204
|
+
"DriftReport",
|
|
205
|
+
"RetrainingTrigger",
|
|
206
|
+
"ks_distance",
|
|
207
|
+
"make_report",
|
|
208
|
+
"population_stability_index",
|
|
209
|
+
"prediction_drift",
|
|
210
|
+
"worst",
|
|
211
|
+
]
|
limen_ml/folds.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
"""Spatial blocks for cross-validation: no fold learns from its neighbours.
|
|
2
|
+
|
|
3
|
+
Two cells a kilometre apart share their rain, their rock and often their
|
|
4
|
+
landslides. A random split would put one in training and the other in
|
|
5
|
+
validation and measure memory, not skill. Cells are grouped into coarse
|
|
6
|
+
blocks (:class:`SpatialBlockGrid`) and whole blocks go to one fold.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import random
|
|
12
|
+
from collections.abc import Sequence
|
|
13
|
+
from dataclasses import dataclass
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass(frozen=True, slots=True)
|
|
20
|
+
class SpatialBlockGrid:
|
|
21
|
+
"""A coarse grid of square blocks of ``edge_deg`` degrees."""
|
|
22
|
+
|
|
23
|
+
edge_deg: float
|
|
24
|
+
|
|
25
|
+
def block_for(self, lon: float, lat: float) -> str:
|
|
26
|
+
"""The block id ``"{lon_index}|{lat_index}"`` of a point."""
|
|
27
|
+
return f"{int(lon // self.edge_deg)}|{int(lat // self.edge_deg)}"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def spatial_block_folds(blocks: Sequence[str], k: int, *, rng_seed: int = 42) -> list[list[str]]:
|
|
31
|
+
"""``blocks`` into ``k`` disjoint folds, round-robin after a seeded shuffle."""
|
|
32
|
+
if k < 2:
|
|
33
|
+
raise ValueError("k must be >= 2")
|
|
34
|
+
if not blocks:
|
|
35
|
+
return [[] for _ in range(k)]
|
|
36
|
+
ordered = sorted(set(blocks))
|
|
37
|
+
random.Random(rng_seed).shuffle(ordered)
|
|
38
|
+
folds: list[list[str]] = [[] for _ in range(k)]
|
|
39
|
+
for i, block in enumerate(ordered):
|
|
40
|
+
folds[i % k].append(block)
|
|
41
|
+
return folds
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def fold_index(groups: Sequence[str], folds: Sequence[Sequence[str]]) -> Any:
|
|
45
|
+
"""The fold of each row, from its block; a block in no fold goes to fold 0."""
|
|
46
|
+
block_to_fold = {b: i for i, fold in enumerate(folds) for b in fold}
|
|
47
|
+
return np.array([block_to_fold.get(g, 0) for g in groups])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def class_weight(y: Any) -> dict[int, float]:
|
|
51
|
+
"""Inverse-frequency weights of the two classes, for the heavy 0/1 imbalance."""
|
|
52
|
+
counts = np.bincount(np.asarray(y, dtype=int), minlength=2)
|
|
53
|
+
total = counts.sum()
|
|
54
|
+
return {
|
|
55
|
+
0: float(total / (2.0 * max(counts[0], 1))),
|
|
56
|
+
1: float(total / (2.0 * max(counts[1], 1))),
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
__all__ = ["SpatialBlockGrid", "class_weight", "fold_index", "spatial_block_folds"]
|
limen_ml/matrix.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""Training samples into the matrix a model learns from.
|
|
2
|
+
|
|
3
|
+
A sample is a ``features`` dictionary of blocks (``{"static": {"slope_deg":
|
|
4
|
+
31.0}, "rain": {...}}``), a 0/1 ``label`` and the ``split_block`` it belongs
|
|
5
|
+
to for spatial cross-validation. :func:`to_matrix` flattens the blocks into
|
|
6
|
+
``"block.name"`` columns, in the order of the schema given: the order is what
|
|
7
|
+
a registered model reads back, so it never changes silently.
|
|
8
|
+
|
|
9
|
+
A feature a sample does not carry takes ``missing(name)``: NaN where "not
|
|
10
|
+
measured" must stay unknown (a cell with no satellite pixel is not a still
|
|
11
|
+
slope), 0 where absence is a true zero. The schema and that rule belong to the
|
|
12
|
+
application.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import hashlib
|
|
18
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Any, Protocol
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class Sample(Protocol):
|
|
26
|
+
"""What a training sample carries."""
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def features(self) -> Mapping[str, Any]: ...
|
|
30
|
+
|
|
31
|
+
@property
|
|
32
|
+
def label(self) -> int | bool: ...
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def split_block(self) -> str: ...
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True, slots=True)
|
|
39
|
+
class TrainingMatrix:
|
|
40
|
+
"""X, y, the spatial block of each row, and the ordered feature schema."""
|
|
41
|
+
|
|
42
|
+
feature_names: tuple[str, ...]
|
|
43
|
+
X: Any # np.ndarray, rows by features
|
|
44
|
+
y: Any # np.ndarray of 0/1
|
|
45
|
+
groups: tuple[str, ...]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def flatten(features: Mapping[str, Any]) -> dict[str, float]:
|
|
49
|
+
"""``{"block.name": value}`` for the numbers of each block; everything else left out.
|
|
50
|
+
|
|
51
|
+
A sample may also carry raw inputs that are provenance, not columns (a land
|
|
52
|
+
cover code as text, a flag): a string or a bool never becomes a number here.
|
|
53
|
+
"""
|
|
54
|
+
flat: dict[str, float] = {}
|
|
55
|
+
for top, child in features.items():
|
|
56
|
+
if not isinstance(child, Mapping):
|
|
57
|
+
continue
|
|
58
|
+
for k, v in child.items():
|
|
59
|
+
if isinstance(v, bool) or not isinstance(v, (int, float)):
|
|
60
|
+
continue
|
|
61
|
+
flat[f"{top}.{k}"] = float(v)
|
|
62
|
+
return flat
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def zero(_name: str) -> float:
|
|
66
|
+
"""The default for a feature a sample does not carry."""
|
|
67
|
+
return 0.0
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def to_matrix(
|
|
71
|
+
samples: Iterable[Sample],
|
|
72
|
+
features: Sequence[str],
|
|
73
|
+
*,
|
|
74
|
+
missing: Callable[[str], float] = zero,
|
|
75
|
+
) -> TrainingMatrix:
|
|
76
|
+
"""Stack ``samples`` into the matrix of the ordered schema ``features``."""
|
|
77
|
+
names = tuple(features)
|
|
78
|
+
rows: list[list[float]] = []
|
|
79
|
+
labels: list[int] = []
|
|
80
|
+
groups: list[str] = []
|
|
81
|
+
for s in samples:
|
|
82
|
+
flat = flatten(s.features)
|
|
83
|
+
rows.append([flat.get(name, missing(name)) for name in names])
|
|
84
|
+
labels.append(int(s.label))
|
|
85
|
+
groups.append(s.split_block)
|
|
86
|
+
return TrainingMatrix(
|
|
87
|
+
feature_names=names,
|
|
88
|
+
X=np.array(rows, dtype=float).reshape(len(rows), len(names)),
|
|
89
|
+
y=np.array(labels, dtype=int),
|
|
90
|
+
groups=tuple(groups),
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def matrix_sha(matrix: TrainingMatrix) -> str:
|
|
95
|
+
"""The SHA-256 of a matrix: same data, same hash, on any machine.
|
|
96
|
+
|
|
97
|
+
On the values **rounded to nine decimals**, not the raw bytes: BLAS sums in
|
|
98
|
+
an order that depends on the number of threads, and a last-bit difference
|
|
99
|
+
would change the hash without the data having changed. Names, labels and
|
|
100
|
+
blocks are in it: the same numbers under other columns or another split are
|
|
101
|
+
another dataset.
|
|
102
|
+
"""
|
|
103
|
+
digest = hashlib.sha256()
|
|
104
|
+
digest.update("|".join(matrix.feature_names).encode("utf-8"))
|
|
105
|
+
digest.update(b"\x00")
|
|
106
|
+
rounded = np.round(np.asarray(matrix.X, dtype=float), 9)
|
|
107
|
+
digest.update(np.ascontiguousarray(rounded).tobytes())
|
|
108
|
+
digest.update(np.ascontiguousarray(np.asarray(matrix.y, dtype=np.int64)).tobytes())
|
|
109
|
+
digest.update("|".join(matrix.groups).encode("utf-8"))
|
|
110
|
+
return digest.hexdigest()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def prune_collinear(
|
|
114
|
+
matrix: TrainingMatrix, *, threshold: float
|
|
115
|
+
) -> tuple[TrainingMatrix, list[tuple[str, str, float]]]:
|
|
116
|
+
"""Drop each feature whose |Pearson r| with an earlier one exceeds ``threshold``.
|
|
117
|
+
|
|
118
|
+
The schema order is the priority: the first of a collinear pair stays.
|
|
119
|
+
Boosted trees tolerate collinearity, but it splits the SHAP credit between
|
|
120
|
+
twins. The correlation of two columns is computed on the rows where both
|
|
121
|
+
are measured; a constant column correlates 0. Returns the matrix and the
|
|
122
|
+
dropped pairs ``(kept, dropped, r)``.
|
|
123
|
+
"""
|
|
124
|
+
x = np.asarray(matrix.X, dtype=float)
|
|
125
|
+
names = list(matrix.feature_names)
|
|
126
|
+
with np.errstate(invalid="ignore", divide="ignore"):
|
|
127
|
+
corr = np.ma.corrcoef(np.ma.masked_invalid(x), rowvar=False).filled(np.nan)
|
|
128
|
+
corr = np.nan_to_num(corr, nan=0.0)
|
|
129
|
+
dropped: list[tuple[str, str, float]] = []
|
|
130
|
+
keep: list[int] = []
|
|
131
|
+
for j in range(len(names)):
|
|
132
|
+
twin = next((i for i in keep if abs(corr[i, j]) > threshold), None)
|
|
133
|
+
if twin is None:
|
|
134
|
+
keep.append(j)
|
|
135
|
+
else:
|
|
136
|
+
dropped.append((names[twin], names[j], float(corr[twin, j])))
|
|
137
|
+
if not dropped:
|
|
138
|
+
return matrix, []
|
|
139
|
+
pruned = TrainingMatrix(
|
|
140
|
+
feature_names=tuple(names[j] for j in keep),
|
|
141
|
+
X=x[:, keep],
|
|
142
|
+
y=matrix.y,
|
|
143
|
+
groups=matrix.groups,
|
|
144
|
+
)
|
|
145
|
+
return pruned, dropped
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
__all__ = [
|
|
149
|
+
"Sample",
|
|
150
|
+
"TrainingMatrix",
|
|
151
|
+
"flatten",
|
|
152
|
+
"matrix_sha",
|
|
153
|
+
"prune_collinear",
|
|
154
|
+
"to_matrix",
|
|
155
|
+
"zero",
|
|
156
|
+
]
|
limen_ml/metrics.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""The metrics of a probabilistic model that need scikit-learn, and its error bands.
|
|
2
|
+
|
|
3
|
+
The plain ones (AUC, contingency, Brier, reliability) are in
|
|
4
|
+
``limen_core.verification``; these are the model's own:
|
|
5
|
+
|
|
6
|
+
- :func:`auc_pr`: the area under the precision-recall curve, the measure that
|
|
7
|
+
stays honest when landslides are one row in a thousand;
|
|
8
|
+
- :func:`threshold_sweep`: what catching 50, 70 or 90 % of the events costs in
|
|
9
|
+
false alarms;
|
|
10
|
+
- :func:`conformal_quantiles`: split-conformal error bands on calibrated
|
|
11
|
+
probabilities.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from collections.abc import Sequence
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
from limen_core import verification
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def auc_pr(y_true: Any, y_prob: Any) -> float:
|
|
24
|
+
"""Area under the precision-recall curve (average precision)."""
|
|
25
|
+
from sklearn.metrics import average_precision_score
|
|
26
|
+
|
|
27
|
+
return float(average_precision_score(y_true, y_prob))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _contingency(y_true: Any, y_prob: Any, threshold: float) -> verification.Contingency:
|
|
31
|
+
return verification.Contingency.at(
|
|
32
|
+
np.asarray(y_true, dtype=int).astype(bool).tolist(),
|
|
33
|
+
np.asarray(y_prob, dtype=float).tolist(),
|
|
34
|
+
threshold=threshold,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def threshold_sweep(
|
|
39
|
+
y_true: Any, y_prob: Any, *, recall_targets: Sequence[float] = (0.5, 0.7, 0.9)
|
|
40
|
+
) -> list[dict[str, float]]:
|
|
41
|
+
"""The operating point at each recall target: threshold, hit rate, FAR, TSS.
|
|
42
|
+
|
|
43
|
+
For each target, the highest threshold whose recall meets it. With no
|
|
44
|
+
event the threshold is 1.0 and nothing else is said. An empty denominator
|
|
45
|
+
reads 0.0.
|
|
46
|
+
"""
|
|
47
|
+
yt = np.asarray(y_true, dtype=int)
|
|
48
|
+
yp = np.asarray(y_prob, dtype=float)
|
|
49
|
+
out: list[dict[str, float]] = []
|
|
50
|
+
for target in recall_targets:
|
|
51
|
+
threshold = verification.threshold_for_recall(yt.astype(bool).tolist(), yp.tolist(), target)
|
|
52
|
+
if threshold is None:
|
|
53
|
+
out.append({"recall_target": float(target), "threshold": 1.0})
|
|
54
|
+
continue
|
|
55
|
+
c = _contingency(yt, yp, threshold)
|
|
56
|
+
sens = float(c.hit_rate or 0.0)
|
|
57
|
+
spec = float(c.specificity or 0.0)
|
|
58
|
+
out.append(
|
|
59
|
+
{
|
|
60
|
+
"recall_target": float(target),
|
|
61
|
+
"threshold": float(threshold),
|
|
62
|
+
"hit_rate": sens,
|
|
63
|
+
"far": float(c.false_alarm_ratio or 0.0),
|
|
64
|
+
"tss": sens + spec - 1.0,
|
|
65
|
+
"sensitivity": sens,
|
|
66
|
+
"specificity": spec,
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
return out
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def conformal_quantiles(
|
|
73
|
+
y_true: Any, y_prob: Any, *, alphas: Sequence[float] = (0.2, 0.1, 0.05)
|
|
74
|
+
) -> dict[str, float]:
|
|
75
|
+
"""Split-conformal error quantiles: ``[p - q, p + q]`` covers the outcome 1 - alpha.
|
|
76
|
+
|
|
77
|
+
Nonconformity is ``|y - p|`` on calibrated out-of-fold predictions, with the
|
|
78
|
+
finite-sample corrected rank. Keys are ``q80``, ``q90``, ``q95``.
|
|
79
|
+
"""
|
|
80
|
+
scores = np.abs(np.asarray(y_true, dtype=float) - np.asarray(y_prob, dtype=float))
|
|
81
|
+
n = scores.size
|
|
82
|
+
out: dict[str, float] = {}
|
|
83
|
+
for alpha in alphas:
|
|
84
|
+
rank = min(1.0, np.ceil((n + 1) * (1 - alpha)) / n)
|
|
85
|
+
out[f"q{int((1 - alpha) * 100)}"] = float(np.quantile(scores, rank))
|
|
86
|
+
return out
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
__all__ = ["auc_pr", "conformal_quantiles", "threshold_sweep"]
|
limen_ml/py.typed
ADDED
|
File without changes
|
limen_ml/rainfall_cnn.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""A small 1D-CNN over a week of hourly rain: the probability of a landslide.
|
|
2
|
+
|
|
3
|
+
The network is deliberately small (three convolutions and a sigmoid head) so
|
|
4
|
+
that once exported to ONNX it weighs tens of kilobytes and scores a cell in
|
|
5
|
+
milliseconds on a CPU.
|
|
6
|
+
|
|
7
|
+
- :func:`build_rainfall_cnn`: an untrained network (needs the ``dl`` extra,
|
|
8
|
+
PyTorch);
|
|
9
|
+
- :func:`train_rainfall_cnn`: train it on windows of :data:`SEQUENCE_LENGTH_HOURS`
|
|
10
|
+
and export it to ONNX;
|
|
11
|
+
- :class:`RainfallProbability`: score a window with the ONNX model (needs the
|
|
12
|
+
``serve`` extra, onnxruntime). Without a usable model it answers 0.5, "no
|
|
13
|
+
signal", so the caller never crashes on it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import logging
|
|
19
|
+
from collections.abc import Sequence
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any
|
|
23
|
+
|
|
24
|
+
log = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
#: One week of hourly rain: the antecedent that triggers most Italian flow slides.
|
|
27
|
+
SEQUENCE_LENGTH_HOURS = 168
|
|
28
|
+
#: What :class:`RainfallProbability` answers when it cannot score.
|
|
29
|
+
NEUTRAL = 0.5
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def build_rainfall_cnn() -> Any:
|
|
33
|
+
"""A fresh, untrained 1D-CNN. The caller sets up the optimiser."""
|
|
34
|
+
import torch
|
|
35
|
+
from torch import nn
|
|
36
|
+
|
|
37
|
+
class RainfallCNN(nn.Module): # type: ignore[misc, unused-ignore]
|
|
38
|
+
def __init__(self) -> None:
|
|
39
|
+
super().__init__()
|
|
40
|
+
self.net = nn.Sequential(
|
|
41
|
+
nn.Conv1d(in_channels=1, out_channels=16, kernel_size=5, padding=2),
|
|
42
|
+
nn.ReLU(),
|
|
43
|
+
nn.MaxPool1d(2),
|
|
44
|
+
nn.Conv1d(16, 32, kernel_size=5, padding=2),
|
|
45
|
+
nn.ReLU(),
|
|
46
|
+
nn.MaxPool1d(2),
|
|
47
|
+
nn.Conv1d(32, 64, kernel_size=5, padding=2),
|
|
48
|
+
nn.ReLU(),
|
|
49
|
+
nn.AdaptiveAvgPool1d(1),
|
|
50
|
+
nn.Flatten(),
|
|
51
|
+
nn.Linear(64, 32),
|
|
52
|
+
nn.ReLU(),
|
|
53
|
+
nn.Linear(32, 1),
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
def forward(self, x: Any) -> Any:
|
|
57
|
+
return torch.sigmoid(self.net(x)).squeeze(-1)
|
|
58
|
+
|
|
59
|
+
return RainfallCNN()
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass(frozen=True, slots=True)
|
|
63
|
+
class TrainedCNN:
|
|
64
|
+
onnx_path: Path | None
|
|
65
|
+
epochs: int
|
|
66
|
+
final_loss: float
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def train_rainfall_cnn(
|
|
70
|
+
sequences: Any,
|
|
71
|
+
labels: Any,
|
|
72
|
+
*,
|
|
73
|
+
epochs: int = 12,
|
|
74
|
+
batch_size: int = 64,
|
|
75
|
+
learning_rate: float = 1e-3,
|
|
76
|
+
onnx_path: Path | None = None,
|
|
77
|
+
) -> TrainedCNN:
|
|
78
|
+
"""Train the network on ``sequences`` (``[N, 168]``) and ``labels`` (``[N]``).
|
|
79
|
+
|
|
80
|
+
With ``onnx_path`` the trained network is exported there. Raises
|
|
81
|
+
``ValueError`` on an empty input or windows of the wrong length.
|
|
82
|
+
"""
|
|
83
|
+
import numpy as np
|
|
84
|
+
import torch
|
|
85
|
+
from torch.utils.data import DataLoader, TensorDataset
|
|
86
|
+
|
|
87
|
+
seq = np.asarray(sequences, dtype=float)
|
|
88
|
+
if len(seq) == 0 or seq.ndim != 2 or seq.shape[1] != SEQUENCE_LENGTH_HOURS:
|
|
89
|
+
raise ValueError(f"expected [N, {SEQUENCE_LENGTH_HOURS}] windows, got {seq.shape}")
|
|
90
|
+
x = torch.tensor(seq, dtype=torch.float32).unsqueeze(1)
|
|
91
|
+
y = torch.tensor(np.asarray(labels, dtype=float), dtype=torch.float32)
|
|
92
|
+
loader = DataLoader(TensorDataset(x, y), batch_size=batch_size, shuffle=True)
|
|
93
|
+
model = build_rainfall_cnn()
|
|
94
|
+
optimiser = torch.optim.Adam(model.parameters(), lr=learning_rate)
|
|
95
|
+
loss_fn = torch.nn.BCELoss()
|
|
96
|
+
final_loss = 0.0
|
|
97
|
+
for epoch in range(epochs):
|
|
98
|
+
running = 0.0
|
|
99
|
+
for batch_x, batch_y in loader:
|
|
100
|
+
optimiser.zero_grad()
|
|
101
|
+
loss = loss_fn(model(batch_x), batch_y)
|
|
102
|
+
loss.backward()
|
|
103
|
+
optimiser.step()
|
|
104
|
+
running += float(loss.item())
|
|
105
|
+
final_loss = running / max(len(loader), 1)
|
|
106
|
+
log.info("epoch %d, loss %.4f", epoch, final_loss)
|
|
107
|
+
saved = export_onnx(model, onnx_path) if onnx_path is not None else None
|
|
108
|
+
return TrainedCNN(onnx_path=saved, epochs=epochs, final_loss=final_loss)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def export_onnx(model: Any, dest: Path) -> Path:
|
|
112
|
+
"""Export the network to ONNX at ``dest``, with a dynamic batch."""
|
|
113
|
+
import torch
|
|
114
|
+
|
|
115
|
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
116
|
+
dummy = torch.zeros((1, 1, SEQUENCE_LENGTH_HOURS), dtype=torch.float32)
|
|
117
|
+
torch.onnx.export(
|
|
118
|
+
model,
|
|
119
|
+
(dummy,),
|
|
120
|
+
str(dest),
|
|
121
|
+
input_names=["rainfall_window"],
|
|
122
|
+
output_names=["probability"],
|
|
123
|
+
dynamic_axes={"rainfall_window": {0: "batch"}, "probability": {0: "batch"}},
|
|
124
|
+
opset_version=17,
|
|
125
|
+
)
|
|
126
|
+
return dest
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def pad_or_trim(values: Sequence[float], *, length: int = SEQUENCE_LENGTH_HOURS) -> list[float]:
|
|
130
|
+
"""The last ``length`` values, padded with zeros in front when fewer."""
|
|
131
|
+
if len(values) >= length:
|
|
132
|
+
return [float(v) for v in values[-length:]]
|
|
133
|
+
return [0.0] * (length - len(values)) + [float(v) for v in values]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class RainfallProbability:
|
|
137
|
+
"""An ONNX rainfall model: ``predict(window)`` is P(landslide | window).
|
|
138
|
+
|
|
139
|
+
Answers :data:`NEUTRAL` when onnxruntime is missing, the model file is
|
|
140
|
+
missing or unreadable, or a prediction fails.
|
|
141
|
+
"""
|
|
142
|
+
|
|
143
|
+
def __init__(self, model_path: Path) -> None:
|
|
144
|
+
self._model_path = Path(model_path)
|
|
145
|
+
self._session: Any = None
|
|
146
|
+
self._input_name = "rainfall_window"
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def sequence_length(self) -> int:
|
|
150
|
+
return SEQUENCE_LENGTH_HOURS
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def model_path(self) -> Path:
|
|
154
|
+
return self._model_path
|
|
155
|
+
|
|
156
|
+
def _ensure_session(self) -> None:
|
|
157
|
+
if self._session is not None:
|
|
158
|
+
return
|
|
159
|
+
try:
|
|
160
|
+
import onnxruntime as ort
|
|
161
|
+
except ImportError:
|
|
162
|
+
log.warning("onnxruntime is not installed: install the serve extra")
|
|
163
|
+
return
|
|
164
|
+
if not self._model_path.exists():
|
|
165
|
+
log.warning("rainfall model not found: %s", self._model_path)
|
|
166
|
+
return
|
|
167
|
+
try:
|
|
168
|
+
self._session = ort.InferenceSession(
|
|
169
|
+
str(self._model_path), providers=["CPUExecutionProvider"]
|
|
170
|
+
)
|
|
171
|
+
self._input_name = self._session.get_inputs()[0].name
|
|
172
|
+
except Exception as exc:
|
|
173
|
+
log.warning("rainfall model not loaded: %s", exc)
|
|
174
|
+
|
|
175
|
+
def predict(self, window: Sequence[float]) -> float:
|
|
176
|
+
"""P(landslide | window); :data:`NEUTRAL` on any failure."""
|
|
177
|
+
self._ensure_session()
|
|
178
|
+
if self._session is None:
|
|
179
|
+
return NEUTRAL
|
|
180
|
+
import numpy as np
|
|
181
|
+
|
|
182
|
+
arr = np.asarray(pad_or_trim(window), dtype=np.float32).reshape(1, 1, SEQUENCE_LENGTH_HOURS)
|
|
183
|
+
try:
|
|
184
|
+
outputs = self._session.run(None, {self._input_name: arr})
|
|
185
|
+
except Exception as exc:
|
|
186
|
+
log.warning("rainfall prediction failed: %s", exc)
|
|
187
|
+
return NEUTRAL
|
|
188
|
+
return float(np.asarray(outputs[0]).flatten()[0])
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
__all__ = [
|
|
192
|
+
"NEUTRAL",
|
|
193
|
+
"SEQUENCE_LENGTH_HOURS",
|
|
194
|
+
"RainfallProbability",
|
|
195
|
+
"TrainedCNN",
|
|
196
|
+
"build_rainfall_cnn",
|
|
197
|
+
"export_onnx",
|
|
198
|
+
"pad_or_trim",
|
|
199
|
+
"train_rainfall_cnn",
|
|
200
|
+
]
|
limen_ml/train.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""Train a hazard model on a matrix: tune, cross-validate, compare, calibrate, fit.
|
|
2
|
+
|
|
3
|
+
Every step works on spatial folds (:mod:`limen_ml.folds`), the same folds for
|
|
4
|
+
all, because comparing two models on two partitions measures the luck of the
|
|
5
|
+
partition. The pieces, in the order a training run uses them:
|
|
6
|
+
|
|
7
|
+
1. :func:`tune`: Optuna (TPE, seeded) over LightGBM, maximising the AUC-PR
|
|
8
|
+
averaged across folds;
|
|
9
|
+
2. :func:`cross_validate`: the tuned model on each fold, its AUC-PR, Brier and
|
|
10
|
+
the out-of-fold probabilities;
|
|
11
|
+
3. :func:`compare_algorithms`: a random forest, a standardised logistic
|
|
12
|
+
regression (the linear reference: if boosting does not beat it, the
|
|
13
|
+
non-linear structure buys nothing) and LightGBM, on the same folds;
|
|
14
|
+
4. :func:`fit_isotonic` on the out-of-fold probabilities, and :func:`fit_final`
|
|
15
|
+
on all the data;
|
|
16
|
+
5. :func:`shap_explainer` for the breakdown of a score.
|
|
17
|
+
|
|
18
|
+
No tracking, no registry, no database: the application logs what it wants
|
|
19
|
+
where it wants. Needs the ``train`` extra (LightGBM, scikit-learn, Optuna,
|
|
20
|
+
SHAP).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import logging
|
|
26
|
+
from collections.abc import Sequence
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from typing import Any
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
from limen_ml.folds import class_weight, fold_index
|
|
33
|
+
from limen_ml.matrix import TrainingMatrix
|
|
34
|
+
from limen_ml.metrics import auc_pr
|
|
35
|
+
|
|
36
|
+
log = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
#: The seed of the cross-validated models, as Limen has always used it.
|
|
39
|
+
CV_SEED = 42
|
|
40
|
+
#: The fewest rows a training run accepts.
|
|
41
|
+
MIN_SAMPLES = 20
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def too_few(labels: Sequence[int | bool]) -> bool:
|
|
45
|
+
"""Whether a training set is too small or has a single class."""
|
|
46
|
+
return len(labels) < MIN_SAMPLES or {int(v) for v in labels} != {0, 1}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def lightgbm_params(params: dict[str, Any], y: Any, *, seed: int) -> dict[str, Any]:
|
|
50
|
+
"""``params`` with the fixed settings: binary, balanced, deterministic, seeded."""
|
|
51
|
+
w = class_weight(y)
|
|
52
|
+
return {
|
|
53
|
+
**params,
|
|
54
|
+
"objective": "binary",
|
|
55
|
+
"verbosity": -1,
|
|
56
|
+
"scale_pos_weight": w[1] / w[0],
|
|
57
|
+
"deterministic": True,
|
|
58
|
+
"force_row_wise": True,
|
|
59
|
+
"seed": seed,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def objective(matrix: TrainingMatrix, folds: Sequence[Sequence[str]]) -> Any:
|
|
64
|
+
"""The Optuna objective: AUC-PR of LightGBM averaged across the spatial folds.
|
|
65
|
+
|
|
66
|
+
A fold whose validation part is empty or has no event is skipped; with none
|
|
67
|
+
left the trial scores 0.
|
|
68
|
+
"""
|
|
69
|
+
import lightgbm as lgb
|
|
70
|
+
import optuna
|
|
71
|
+
from sklearn.metrics import average_precision_score
|
|
72
|
+
|
|
73
|
+
idx = fold_index(matrix.groups, folds)
|
|
74
|
+
weights = class_weight(matrix.y)
|
|
75
|
+
|
|
76
|
+
def run(trial: optuna.Trial) -> float:
|
|
77
|
+
params: dict[str, Any] = {
|
|
78
|
+
"objective": "binary",
|
|
79
|
+
"metric": "average_precision",
|
|
80
|
+
"verbosity": -1,
|
|
81
|
+
"learning_rate": trial.suggest_float("learning_rate", 0.01, 0.2, log=True),
|
|
82
|
+
"num_leaves": trial.suggest_int("num_leaves", 15, 127),
|
|
83
|
+
"min_data_in_leaf": trial.suggest_int("min_data_in_leaf", 5, 50),
|
|
84
|
+
"feature_fraction": trial.suggest_float("feature_fraction", 0.6, 1.0),
|
|
85
|
+
"bagging_fraction": trial.suggest_float("bagging_fraction", 0.6, 1.0),
|
|
86
|
+
"bagging_freq": trial.suggest_int("bagging_freq", 0, 5),
|
|
87
|
+
"lambda_l1": trial.suggest_float("lambda_l1", 0.0, 1.0),
|
|
88
|
+
"lambda_l2": trial.suggest_float("lambda_l2", 0.0, 1.0),
|
|
89
|
+
"n_estimators": trial.suggest_int("n_estimators", 100, 600),
|
|
90
|
+
"scale_pos_weight": weights[1] / weights[0],
|
|
91
|
+
"deterministic": True,
|
|
92
|
+
"force_row_wise": True,
|
|
93
|
+
"seed": CV_SEED,
|
|
94
|
+
}
|
|
95
|
+
scores: list[float] = []
|
|
96
|
+
for k in range(len(folds)):
|
|
97
|
+
train, val = idx != k, idx == k
|
|
98
|
+
if val.sum() == 0 or matrix.y[val].sum() == 0:
|
|
99
|
+
continue
|
|
100
|
+
model = lgb.LGBMClassifier(**params)
|
|
101
|
+
model.fit(matrix.X[train], matrix.y[train])
|
|
102
|
+
proba = np.asarray(model.predict_proba(matrix.X[val]))[:, 1]
|
|
103
|
+
scores.append(float(average_precision_score(matrix.y[val], proba)))
|
|
104
|
+
return float(np.mean(scores)) if scores else 0.0
|
|
105
|
+
|
|
106
|
+
return run
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def tune(
|
|
110
|
+
matrix: TrainingMatrix,
|
|
111
|
+
folds: Sequence[Sequence[str]],
|
|
112
|
+
*,
|
|
113
|
+
trials: int,
|
|
114
|
+
timeout_s: float | None = None,
|
|
115
|
+
seed: int = CV_SEED,
|
|
116
|
+
study_name: str | None = None,
|
|
117
|
+
) -> dict[str, Any]:
|
|
118
|
+
"""The best LightGBM parameters found by a seeded TPE search."""
|
|
119
|
+
import optuna
|
|
120
|
+
|
|
121
|
+
optuna.logging.set_verbosity(optuna.logging.WARNING)
|
|
122
|
+
study = optuna.create_study(
|
|
123
|
+
direction="maximize",
|
|
124
|
+
sampler=optuna.samplers.TPESampler(seed=seed),
|
|
125
|
+
study_name=study_name,
|
|
126
|
+
)
|
|
127
|
+
study.optimize(objective(matrix, folds), n_trials=trials, timeout=timeout_s)
|
|
128
|
+
return dict(study.best_params)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass(frozen=True, slots=True)
|
|
132
|
+
class CrossValidation:
|
|
133
|
+
"""The tuned model across the spatial folds."""
|
|
134
|
+
|
|
135
|
+
auc_pr_mean: float
|
|
136
|
+
auc_pr_std: float
|
|
137
|
+
brier_mean: float
|
|
138
|
+
#: The probability of each row from the model that did not see its fold.
|
|
139
|
+
oof_prob: Any
|
|
140
|
+
y: Any
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def cross_validate(
|
|
144
|
+
matrix: TrainingMatrix,
|
|
145
|
+
folds: Sequence[Sequence[str]],
|
|
146
|
+
params: dict[str, Any],
|
|
147
|
+
*,
|
|
148
|
+
seed: int = CV_SEED,
|
|
149
|
+
) -> CrossValidation:
|
|
150
|
+
"""Fit on all folds but one, predict that one, for each fold.
|
|
151
|
+
|
|
152
|
+
A fold with no event gives probabilities but no AUC-PR or Brier.
|
|
153
|
+
"""
|
|
154
|
+
import lightgbm as lgb
|
|
155
|
+
from sklearn.metrics import brier_score_loss
|
|
156
|
+
|
|
157
|
+
idx = fold_index(matrix.groups, folds)
|
|
158
|
+
oof = np.zeros(len(matrix.y), dtype=float)
|
|
159
|
+
aucs: list[float] = []
|
|
160
|
+
briers: list[float] = []
|
|
161
|
+
full = {**lightgbm_params(params, matrix.y, seed=seed), "metric": "average_precision"}
|
|
162
|
+
for k in range(len(folds)):
|
|
163
|
+
train, val = idx != k, idx == k
|
|
164
|
+
if val.sum() == 0:
|
|
165
|
+
continue
|
|
166
|
+
model = lgb.LGBMClassifier(**full)
|
|
167
|
+
model.fit(matrix.X[train], matrix.y[train])
|
|
168
|
+
proba = np.asarray(model.predict_proba(matrix.X[val]))[:, 1]
|
|
169
|
+
oof[val] = proba
|
|
170
|
+
if matrix.y[val].sum() > 0:
|
|
171
|
+
aucs.append(auc_pr(matrix.y[val], proba))
|
|
172
|
+
briers.append(float(brier_score_loss(matrix.y[val], proba)))
|
|
173
|
+
return CrossValidation(
|
|
174
|
+
auc_pr_mean=float(np.mean(aucs)) if aucs else 0.0,
|
|
175
|
+
auc_pr_std=float(np.std(aucs)) if aucs else 0.0,
|
|
176
|
+
brier_mean=float(np.mean(briers)) if briers else 0.0,
|
|
177
|
+
oof_prob=oof,
|
|
178
|
+
y=matrix.y,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def algorithm_candidates(y: Any, *, seed: int) -> dict[str, Any]:
|
|
183
|
+
"""The algorithms compared on the same folds: forest, logistic, LightGBM.
|
|
184
|
+
|
|
185
|
+
The logistic regression is standardised (indices in [0, 1] and millimetres
|
|
186
|
+
of rain live together) and imputes a missing value with the median plus a
|
|
187
|
+
"was missing" column, so that not measured is not read as zero. The forest
|
|
188
|
+
and LightGBM handle missing values themselves.
|
|
189
|
+
"""
|
|
190
|
+
import lightgbm as lgb
|
|
191
|
+
from sklearn.ensemble import RandomForestClassifier
|
|
192
|
+
from sklearn.impute import SimpleImputer
|
|
193
|
+
from sklearn.linear_model import LogisticRegression
|
|
194
|
+
from sklearn.pipeline import make_pipeline
|
|
195
|
+
from sklearn.preprocessing import StandardScaler
|
|
196
|
+
|
|
197
|
+
w = class_weight(y)
|
|
198
|
+
return {
|
|
199
|
+
"random_forest": RandomForestClassifier(
|
|
200
|
+
n_estimators=300,
|
|
201
|
+
min_samples_leaf=5,
|
|
202
|
+
class_weight="balanced",
|
|
203
|
+
random_state=seed,
|
|
204
|
+
n_jobs=-1,
|
|
205
|
+
),
|
|
206
|
+
"logistic": make_pipeline(
|
|
207
|
+
SimpleImputer(strategy="median", add_indicator=True),
|
|
208
|
+
StandardScaler(),
|
|
209
|
+
LogisticRegression(max_iter=2000, class_weight="balanced", random_state=seed),
|
|
210
|
+
),
|
|
211
|
+
"gradient_boosting": lgb.LGBMClassifier(
|
|
212
|
+
objective="binary",
|
|
213
|
+
verbosity=-1,
|
|
214
|
+
scale_pos_weight=w[1] / w[0],
|
|
215
|
+
deterministic=True,
|
|
216
|
+
force_row_wise=True,
|
|
217
|
+
seed=seed,
|
|
218
|
+
n_estimators=300,
|
|
219
|
+
),
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def compare_algorithms(
|
|
224
|
+
matrix: TrainingMatrix, folds: Sequence[Sequence[str]], *, seed: int
|
|
225
|
+
) -> dict[str, dict[str, float]]:
|
|
226
|
+
"""AUC-PR and Brier of each candidate on the out-of-fold rows it could predict."""
|
|
227
|
+
from sklearn.base import clone
|
|
228
|
+
from sklearn.metrics import brier_score_loss
|
|
229
|
+
|
|
230
|
+
idx = fold_index(matrix.groups, folds)
|
|
231
|
+
out: dict[str, dict[str, float]] = {}
|
|
232
|
+
for name, estimator in algorithm_candidates(matrix.y, seed=seed).items():
|
|
233
|
+
oof = np.zeros(len(matrix.y), dtype=float)
|
|
234
|
+
covered = np.zeros(len(matrix.y), dtype=bool)
|
|
235
|
+
for k in range(len(folds)):
|
|
236
|
+
train, val = idx != k, idx == k
|
|
237
|
+
if val.sum() == 0 or matrix.y[train].sum() == 0:
|
|
238
|
+
continue
|
|
239
|
+
model = clone(estimator)
|
|
240
|
+
model.fit(matrix.X[train], matrix.y[train])
|
|
241
|
+
oof[val] = model.predict_proba(matrix.X[val])[:, 1]
|
|
242
|
+
covered[val] = True
|
|
243
|
+
if not covered.any():
|
|
244
|
+
continue
|
|
245
|
+
out[name] = {
|
|
246
|
+
"auc_pr": auc_pr(matrix.y[covered], oof[covered]),
|
|
247
|
+
"brier": float(brier_score_loss(matrix.y[covered], oof[covered])),
|
|
248
|
+
}
|
|
249
|
+
return out
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def fit_final(matrix: TrainingMatrix, params: dict[str, Any], *, seed: int) -> Any:
|
|
253
|
+
"""LightGBM with the tuned parameters, fitted on every row."""
|
|
254
|
+
import lightgbm as lgb
|
|
255
|
+
|
|
256
|
+
model = lgb.LGBMClassifier(**lightgbm_params(params, matrix.y, seed=seed))
|
|
257
|
+
model.fit(matrix.X, matrix.y)
|
|
258
|
+
return model
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def fit_isotonic(y_prob: Any, y_true: Any) -> Any:
|
|
262
|
+
"""An isotonic calibrator of probabilities, clipped outside the range it saw."""
|
|
263
|
+
from sklearn.isotonic import IsotonicRegression
|
|
264
|
+
|
|
265
|
+
iso = IsotonicRegression(out_of_bounds="clip")
|
|
266
|
+
iso.fit(y_prob, y_true)
|
|
267
|
+
return iso
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def shap_explainer(model: Any) -> Any | None:
|
|
271
|
+
"""A SHAP tree explainer of the model; ``None`` without SHAP or if it cannot build one."""
|
|
272
|
+
try:
|
|
273
|
+
import shap
|
|
274
|
+
except ImportError:
|
|
275
|
+
return None
|
|
276
|
+
try:
|
|
277
|
+
return shap.TreeExplainer(model)
|
|
278
|
+
except Exception as exc: # pragma: no cover - depends on the model
|
|
279
|
+
log.debug("no SHAP explainer: %s", exc)
|
|
280
|
+
return None
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
__all__ = [
|
|
284
|
+
"CV_SEED",
|
|
285
|
+
"MIN_SAMPLES",
|
|
286
|
+
"CrossValidation",
|
|
287
|
+
"algorithm_candidates",
|
|
288
|
+
"compare_algorithms",
|
|
289
|
+
"cross_validate",
|
|
290
|
+
"fit_final",
|
|
291
|
+
"fit_isotonic",
|
|
292
|
+
"lightgbm_params",
|
|
293
|
+
"objective",
|
|
294
|
+
"shap_explainer",
|
|
295
|
+
"too_few",
|
|
296
|
+
"tune",
|
|
297
|
+
]
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: limen-ml
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: The machine learning of Limen: train, calibrate, monitor and serve hazard models on spatial folds
|
|
5
|
+
Keywords: machine learning,landslide,wildfire,flood,spatial cross-validation,lightgbm
|
|
6
|
+
Author: Giuseppe Zileni
|
|
7
|
+
Author-email: Giuseppe Zileni <giuseppe.zileni@gmail.com>
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: Operating System :: OS Independent
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Typing :: Typed
|
|
18
|
+
Requires-Dist: numpy>=2.1
|
|
19
|
+
Requires-Dist: limen-core~=0.6.0
|
|
20
|
+
Requires-Dist: torch>=2.4 ; extra == 'dl'
|
|
21
|
+
Requires-Dist: onnx>=1.17 ; extra == 'dl'
|
|
22
|
+
Requires-Dist: onnxruntime>=1.20 ; extra == 'serve'
|
|
23
|
+
Requires-Dist: lightgbm>=4.5 ; extra == 'train'
|
|
24
|
+
Requires-Dist: scikit-learn>=1.5 ; extra == 'train'
|
|
25
|
+
Requires-Dist: optuna>=4.0 ; extra == 'train'
|
|
26
|
+
Requires-Dist: shap>=0.46 ; extra == 'train'
|
|
27
|
+
Requires-Python: >=3.12
|
|
28
|
+
Project-URL: Homepage, https://github.com/agent-engineering-studio/limen-ml
|
|
29
|
+
Project-URL: Issues, https://github.com/agent-engineering-studio/limen-ml/issues
|
|
30
|
+
Project-URL: Documentation, https://agentengineering.it/limen-ml/
|
|
31
|
+
Project-URL: Changelog, https://github.com/agent-engineering-studio/limen-ml/blob/main/CHANGELOG.md
|
|
32
|
+
Provides-Extra: dl
|
|
33
|
+
Provides-Extra: serve
|
|
34
|
+
Provides-Extra: train
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
# limen-ml
|
|
38
|
+
|
|
39
|
+
[Documentation](https://agentengineering.it/limen-ml/) · [Changelog](CHANGELOG.md)
|
|
40
|
+
|
|
41
|
+
**limen-ml** is the machine learning of [Limen](https://github.com/agent-engineering-studio/limen),
|
|
42
|
+
an open early-warning system for landslides, floods and wildfires in Italy: it
|
|
43
|
+
trains a hazard model on spatial folds, calibrates it, tells when the world has
|
|
44
|
+
drifted from its data, and serves a small network over a week of rain.
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install "limen-ml[train]" # LightGBM, scikit-learn, Optuna, SHAP
|
|
48
|
+
pip install "limen-ml[serve]" # onnxruntime, to score with the rainfall network
|
|
49
|
+
pip install "limen-ml[dl]" # PyTorch, to train it
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from limen_ml import folds, matrix, metrics, train
|
|
54
|
+
|
|
55
|
+
m = matrix.to_matrix(samples, ("static.slope_deg", "rain.rain_72h_mm", "insar.velocity_mmy"))
|
|
56
|
+
k = folds.spatial_block_folds(list(m.groups), 5, rng_seed=42)
|
|
57
|
+
|
|
58
|
+
best = train.tune(m, k, trials=50, seed=42)
|
|
59
|
+
cv = train.cross_validate(m, k, best) # AUC-PR, Brier, out-of-fold probabilities
|
|
60
|
+
calibrator = train.fit_isotonic(cv.oof_prob, cv.y)
|
|
61
|
+
model = train.fit_final(m, best, seed=42)
|
|
62
|
+
print(cv.auc_pr_mean, metrics.conformal_quantiles(cv.y, calibrator.transform(cv.oof_prob)))
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
A sample is anything with `features` (blocks of numbers), `label` (0/1) and
|
|
66
|
+
`split_block` (its spatial block).
|
|
67
|
+
|
|
68
|
+
## The rules
|
|
69
|
+
|
|
70
|
+
- **Spatial folds, the same for every model.** Two cells a kilometre apart share
|
|
71
|
+
their rain and their rock: a random split measures memory. Whole blocks go to
|
|
72
|
+
one fold, and every algorithm is compared on the same folds.
|
|
73
|
+
- **AUC-PR, not accuracy.** Landslides are one row in many; the area under the
|
|
74
|
+
precision-recall curve stays honest where accuracy does not.
|
|
75
|
+
- **Not measured stays not measured.** The application says which absent
|
|
76
|
+
feature is NaN (a cell the satellite does not see is not a still slope) and
|
|
77
|
+
which is a true zero; the logistic reference imputes with a "was missing"
|
|
78
|
+
column.
|
|
79
|
+
- **A linear reference.** A standardised logistic regression runs next to the
|
|
80
|
+
boosted trees: if they do not beat it, the non-linear structure buys nothing.
|
|
81
|
+
- **Reproducible.** Seeded search and folds, deterministic LightGBM, and a
|
|
82
|
+
matrix hash on values rounded to nine decimals, so threads do not change it.
|
|
83
|
+
- **No database, no tracking, no schema.** The application brings its samples,
|
|
84
|
+
its feature schema and its baselines, and logs where it wants.
|
|
85
|
+
- **Checked against the code it replaces.** Every function that comes from Limen
|
|
86
|
+
is compared with Limen's own, frozen in `tests/limen_reference.py`.
|
|
87
|
+
- **A model never decides an alert.** It is a challenger, promoted only by a
|
|
88
|
+
person after a backtest. The official warning is the criticality bulletin of
|
|
89
|
+
the Civil Protection Department.
|
|
90
|
+
|
|
91
|
+
## Develop
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
make help # the targets
|
|
95
|
+
make check # ruff, mypy --strict, pytest: the gate CI runs
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
## Licence
|
|
99
|
+
|
|
100
|
+
Code: Apache-2.0.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
limen_ml/__init__.py,sha256=Gu9Los_NE2zuHovzmp-JUmUnNAWzETurR-_nLipyNjE,954
|
|
2
|
+
limen_ml/drift.py,sha256=5gtYYdE0ONgvvvbqy_cxJDgXQv6PHlFjDSKouZbkJTY,6350
|
|
3
|
+
limen_ml/folds.py,sha256=C5IhQeSIfvFLNXsVNmfnT7hKBex_Lwo9jqUSLGjhwDo,2131
|
|
4
|
+
limen_ml/matrix.py,sha256=MrZCJdD9okIHF-MTF4WA-f1GiRJt8jNl4jIKNXPmzYI,5308
|
|
5
|
+
limen_ml/metrics.py,sha256=a2AFo2tZjqT5ohf97NQlfENhDfusnjvk9CWozQYic1w,3221
|
|
6
|
+
limen_ml/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
7
|
+
limen_ml/rainfall_cnn.py,sha256=UChaMR7ZrPi76ownWaqpQjk01YYlMUlhpI0kQw_hQ44,6831
|
|
8
|
+
limen_ml/train.py,sha256=mFCyD07SmUUOpfRSPQM7Gs7id0ldJfC2uHgVboPd2uw,10376
|
|
9
|
+
limen_ml-0.1.0.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
|
|
10
|
+
limen_ml-0.1.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
|
|
11
|
+
limen_ml-0.1.0.dist-info/METADATA,sha256=iJHjvyI2JcmVPIsluw63Mc8GIAa9TJ273R4r_wcucdU,4480
|
|
12
|
+
limen_ml-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
202
|
+
|