deup 0.1.1__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.
- deup/__init__.py +19 -0
- deup/core/__init__.py +32 -0
- deup/core/grouping.py +104 -0
- deup/core/losses.py +213 -0
- deup/core/oof.py +183 -0
- deup/core/protocols.py +41 -0
- deup/core/types.py +124 -0
- deup/estimators.py +140 -0
- deup/py.typed +0 -0
- deup/splitters.py +117 -0
- deup-0.1.1.dist-info/METADATA +112 -0
- deup-0.1.1.dist-info/RECORD +14 -0
- deup-0.1.1.dist-info/WHEEL +4 -0
- deup-0.1.1.dist-info/licenses/LICENSE +201 -0
deup/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""deup: Direct Epistemic Uncertainty Prediction for any scikit-learn-style model.
|
|
2
|
+
|
|
3
|
+
DEUP (Lahlou et al., 2023, TMLR) estimates *epistemic* uncertainty by training a
|
|
4
|
+
secondary "error predictor" on a base model's out-of-sample errors, then (optionally)
|
|
5
|
+
subtracting an estimate of aleatoric noise. This package provides a maintained,
|
|
6
|
+
scikit-learn-compatible implementation with first-class support for time-series and
|
|
7
|
+
cross-sectional workflows, where correct out-of-fold error construction (no leakage)
|
|
8
|
+
is the difference between a valid and an invalid uncertainty estimate.
|
|
9
|
+
|
|
10
|
+
This is the library implementation; the DEUP *method* is due to
|
|
11
|
+
Lahlou, Jain, Nekoei, Butoi, Bertin, Rector-Brooks, Korablyov, and Bengio (2023).
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from deup.estimators import DEUPRegressor
|
|
17
|
+
|
|
18
|
+
__all__ = ["DEUPRegressor", "__version__"]
|
|
19
|
+
__version__ = "0.1.1"
|
deup/core/__init__.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Core protocols, typed result containers, and the grouped/panel data model.
|
|
2
|
+
|
|
3
|
+
These are the framework-agnostic foundations every estimator in ``deup`` is built
|
|
4
|
+
on. Nothing here imports a heavy backend (no torch, lightgbm, or pandas); the only
|
|
5
|
+
runtime dependency is numpy.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from deup.core.grouping import Grouping
|
|
11
|
+
from deup.core.losses import (
|
|
12
|
+
TargetTransform,
|
|
13
|
+
apply_error_transform,
|
|
14
|
+
get_loss,
|
|
15
|
+
inverse_error_transform,
|
|
16
|
+
)
|
|
17
|
+
from deup.core.oof import OOFErrorCollector
|
|
18
|
+
from deup.core.protocols import Predictor, ProbabilisticPredictor
|
|
19
|
+
from deup.core.types import OOFResult, UncertaintyResult
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"Grouping",
|
|
23
|
+
"OOFErrorCollector",
|
|
24
|
+
"OOFResult",
|
|
25
|
+
"Predictor",
|
|
26
|
+
"ProbabilisticPredictor",
|
|
27
|
+
"TargetTransform",
|
|
28
|
+
"UncertaintyResult",
|
|
29
|
+
"apply_error_transform",
|
|
30
|
+
"get_loss",
|
|
31
|
+
"inverse_error_transform",
|
|
32
|
+
]
|
deup/core/grouping.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""The grouped / panel data model.
|
|
2
|
+
|
|
3
|
+
Many DEUP use cases are not i.i.d. row collections: a cross-sectional ranker scores
|
|
4
|
+
many assets *per date*, where the loss (rank loss) and any rank-geometry
|
|
5
|
+
residualization are defined *within* each date's cross-section. :class:`Grouping`
|
|
6
|
+
makes that ``group_by`` concept first-class, while still handling the i.i.d. case
|
|
7
|
+
(``group_by=None``) as a single trivial group.
|
|
8
|
+
|
|
9
|
+
Pure numpy — no pandas dependency in the core.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
import numpy.typing as npt
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _average_rank(values: npt.NDArray[Any]) -> npt.NDArray[Any]:
|
|
22
|
+
"""Return 1-based ranks with ties resolved by averaging (scipy 'average').
|
|
23
|
+
|
|
24
|
+
Implemented from unique values + counts, so it is independent of input order
|
|
25
|
+
and matches ``pandas.Series.rank(method="average")``.
|
|
26
|
+
"""
|
|
27
|
+
_, inverse, counts = np.unique(values, return_inverse=True, return_counts=True)
|
|
28
|
+
inverse = np.ravel(inverse)
|
|
29
|
+
end = np.cumsum(counts).astype(float)
|
|
30
|
+
start = end - counts + 1.0
|
|
31
|
+
average = (start + end) / 2.0
|
|
32
|
+
result: npt.NDArray[Any] = average[inverse]
|
|
33
|
+
return result
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass(frozen=True)
|
|
37
|
+
class Grouping:
|
|
38
|
+
"""Maps each row to a group and supports within-group operations.
|
|
39
|
+
|
|
40
|
+
Attributes
|
|
41
|
+
----------
|
|
42
|
+
codes:
|
|
43
|
+
Integer group code per row, in ``[0, n_groups)``.
|
|
44
|
+
labels:
|
|
45
|
+
The unique group labels, indexed by code.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
codes: npt.NDArray[Any]
|
|
49
|
+
labels: npt.NDArray[Any]
|
|
50
|
+
|
|
51
|
+
@classmethod
|
|
52
|
+
def from_labels(cls, group_labels: npt.ArrayLike | None, n: int) -> Grouping:
|
|
53
|
+
"""Build a grouping from per-row labels.
|
|
54
|
+
|
|
55
|
+
Parameters
|
|
56
|
+
----------
|
|
57
|
+
group_labels:
|
|
58
|
+
Per-row group labels (e.g. dates). If ``None``, all ``n`` rows form a
|
|
59
|
+
single trivial group (the i.i.d. case).
|
|
60
|
+
n:
|
|
61
|
+
Number of rows (used to size the trivial group and validate lengths).
|
|
62
|
+
"""
|
|
63
|
+
if group_labels is None:
|
|
64
|
+
return cls(
|
|
65
|
+
codes=np.zeros(n, dtype=np.intp),
|
|
66
|
+
labels=np.zeros(1, dtype=np.intp),
|
|
67
|
+
)
|
|
68
|
+
arr = np.asarray(group_labels)
|
|
69
|
+
if arr.shape[0] != n:
|
|
70
|
+
raise ValueError(f"group_labels length {arr.shape[0]} != n {n}")
|
|
71
|
+
labels, codes = np.unique(arr, return_inverse=True)
|
|
72
|
+
return cls(codes=np.ravel(codes).astype(np.intp), labels=labels)
|
|
73
|
+
|
|
74
|
+
@property
|
|
75
|
+
def n_groups(self) -> int:
|
|
76
|
+
"""Number of distinct groups."""
|
|
77
|
+
return int(self.labels.shape[0])
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def is_trivial(self) -> bool:
|
|
81
|
+
"""True when there is a single group (the i.i.d. case)."""
|
|
82
|
+
return self.n_groups == 1
|
|
83
|
+
|
|
84
|
+
def indices(self) -> list[npt.NDArray[Any]]:
|
|
85
|
+
"""Row indices for each group, ordered by group code."""
|
|
86
|
+
return [np.flatnonzero(self.codes == code) for code in range(self.n_groups)]
|
|
87
|
+
|
|
88
|
+
def rank_within(self, values: npt.ArrayLike, pct: bool = True) -> npt.NDArray[Any]:
|
|
89
|
+
"""Rank ``values`` within each group.
|
|
90
|
+
|
|
91
|
+
Ties are averaged. With ``pct=True`` (default) ranks are divided by the
|
|
92
|
+
group size, matching ``pandas.Series.groupby(...).rank(pct=True)`` — the
|
|
93
|
+
convention used for cross-sectional rank features and rank losses.
|
|
94
|
+
"""
|
|
95
|
+
vals = np.asarray(values, dtype=float)
|
|
96
|
+
if vals.shape[0] != self.codes.shape[0]:
|
|
97
|
+
raise ValueError(f"values length {vals.shape[0]} != n_rows {self.codes.shape[0]}")
|
|
98
|
+
out = np.empty(vals.shape[0], dtype=float)
|
|
99
|
+
for idx in self.indices():
|
|
100
|
+
ranks = _average_rank(vals[idx])
|
|
101
|
+
if pct:
|
|
102
|
+
ranks = ranks / ranks.shape[0]
|
|
103
|
+
out[idx] = ranks
|
|
104
|
+
return out
|
deup/core/losses.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""Error-target losses for DEUP.
|
|
2
|
+
|
|
3
|
+
In DEUP the *error target* for a row is the base model's pointwise loss
|
|
4
|
+
``l(y, f(x))`` (Lahlou et al., 2023, Eq. 9 / Alg. 1). The secondary predictor ``g``
|
|
5
|
+
then regresses these targets. This module provides the common choices behind a
|
|
6
|
+
single ``get_loss`` factory, plus a ``callable`` escape hatch for custom losses.
|
|
7
|
+
|
|
8
|
+
Each loss has the signature ``loss(y_true, y_pred, groups=None) -> ndarray`` and
|
|
9
|
+
returns one non-negative error per row. ``groups`` is only used by group-aware losses
|
|
10
|
+
such as :func:`rank_loss`.
|
|
11
|
+
|
|
12
|
+
**Task pairing**
|
|
13
|
+
|
|
14
|
+
- regression: ``squared``, ``absolute``, ``pinball``
|
|
15
|
+
- classification: ``logloss``, ``brier``
|
|
16
|
+
- ranking: ``rank`` (requires ``groups``)
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
from collections.abc import Callable
|
|
22
|
+
from typing import Any, Literal
|
|
23
|
+
|
|
24
|
+
import numpy as np
|
|
25
|
+
import numpy.typing as npt
|
|
26
|
+
|
|
27
|
+
from deup.core.grouping import Grouping
|
|
28
|
+
|
|
29
|
+
LossFn = Callable[..., npt.NDArray[Any]]
|
|
30
|
+
TargetTransform = Literal["none", "log", "asinh"]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def squared_error(
|
|
34
|
+
y_true: npt.ArrayLike, y_pred: npt.ArrayLike, groups: npt.ArrayLike | None = None
|
|
35
|
+
) -> npt.NDArray[Any]:
|
|
36
|
+
"""Squared residual ``(y - f(x))**2`` (regression)."""
|
|
37
|
+
yt = np.asarray(y_true, dtype=float)
|
|
38
|
+
yp = np.asarray(y_pred, dtype=float)
|
|
39
|
+
out: npt.NDArray[Any] = (yt - yp) ** 2
|
|
40
|
+
return out
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def absolute_error(
|
|
44
|
+
y_true: npt.ArrayLike, y_pred: npt.ArrayLike, groups: npt.ArrayLike | None = None
|
|
45
|
+
) -> npt.NDArray[Any]:
|
|
46
|
+
"""Absolute residual ``|y - f(x)|`` (regression)."""
|
|
47
|
+
yt = np.asarray(y_true, dtype=float)
|
|
48
|
+
yp = np.asarray(y_pred, dtype=float)
|
|
49
|
+
out: npt.NDArray[Any] = np.abs(yt - yp)
|
|
50
|
+
return out
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def log_loss(
|
|
54
|
+
y_true: npt.ArrayLike, y_pred: npt.ArrayLike, groups: npt.ArrayLike | None = None
|
|
55
|
+
) -> npt.NDArray[Any]:
|
|
56
|
+
"""Pointwise cross-entropy (classification).
|
|
57
|
+
|
|
58
|
+
``y_pred`` may be a 1-D vector of positive-class probabilities (binary) or a 2-D
|
|
59
|
+
array of class probabilities (multiclass); ``y_true`` holds class indices
|
|
60
|
+
(or 0/1 for binary).
|
|
61
|
+
"""
|
|
62
|
+
yt = np.asarray(y_true)
|
|
63
|
+
yp = np.asarray(y_pred, dtype=float)
|
|
64
|
+
eps = 1e-12
|
|
65
|
+
if yp.ndim == 2:
|
|
66
|
+
probs = np.clip(yp, eps, 1.0)
|
|
67
|
+
true_idx = yt.astype(int)
|
|
68
|
+
chosen = probs[np.arange(probs.shape[0]), true_idx]
|
|
69
|
+
multiclass: npt.NDArray[Any] = -np.log(chosen)
|
|
70
|
+
return multiclass
|
|
71
|
+
p = np.clip(yp, eps, 1.0 - eps)
|
|
72
|
+
yt_f = yt.astype(float)
|
|
73
|
+
binary: npt.NDArray[Any] = -(yt_f * np.log(p) + (1.0 - yt_f) * np.log(1.0 - p))
|
|
74
|
+
return binary
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def brier_loss(
|
|
78
|
+
y_true: npt.ArrayLike, y_pred: npt.ArrayLike, groups: npt.ArrayLike | None = None
|
|
79
|
+
) -> npt.NDArray[Any]:
|
|
80
|
+
"""Brier score (classification calibration loss).
|
|
81
|
+
|
|
82
|
+
Binary: ``(y - p)²`` with ``y ∈ {0,1}``. Multiclass: ``Σ_k (𝟙[y=k] - p_k)²``.
|
|
83
|
+
"""
|
|
84
|
+
yt = np.asarray(y_true)
|
|
85
|
+
yp = np.asarray(y_pred, dtype=float)
|
|
86
|
+
if yp.ndim == 2:
|
|
87
|
+
n, k = yp.shape
|
|
88
|
+
one_hot = np.zeros((n, k), dtype=float)
|
|
89
|
+
one_hot[np.arange(n), yt.astype(int)] = 1.0
|
|
90
|
+
out: npt.NDArray[Any] = np.sum((one_hot - yp) ** 2, axis=1)
|
|
91
|
+
return out
|
|
92
|
+
yt_f = yt.astype(float)
|
|
93
|
+
out = (yt_f - yp) ** 2
|
|
94
|
+
return out
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def pinball_loss(
|
|
98
|
+
y_true: npt.ArrayLike,
|
|
99
|
+
y_pred: npt.ArrayLike,
|
|
100
|
+
groups: npt.ArrayLike | None = None,
|
|
101
|
+
*,
|
|
102
|
+
q: float = 0.5,
|
|
103
|
+
) -> npt.NDArray[Any]:
|
|
104
|
+
"""Pinball / quantile loss for quantile regression (``q ∈ (0, 1)``).
|
|
105
|
+
|
|
106
|
+
``y_pred`` must be the predicted ``q``-quantile of ``y``.
|
|
107
|
+
"""
|
|
108
|
+
if not 0.0 < q < 1.0:
|
|
109
|
+
raise ValueError(f"pinball quantile q must be in (0, 1), got {q}")
|
|
110
|
+
yt = np.asarray(y_true, dtype=float)
|
|
111
|
+
yp = np.asarray(y_pred, dtype=float)
|
|
112
|
+
diff = yt - yp
|
|
113
|
+
out: npt.NDArray[Any] = np.maximum(q * diff, (q - 1.0) * diff)
|
|
114
|
+
return out
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def rank_loss(
|
|
118
|
+
y_true: npt.ArrayLike, y_pred: npt.ArrayLike, groups: npt.ArrayLike | None = None
|
|
119
|
+
) -> npt.NDArray[Any]:
|
|
120
|
+
"""Per-group absolute rank displacement (cross-sectional ranking).
|
|
121
|
+
|
|
122
|
+
For each group (e.g. a date), ranks ``y_true`` and ``y_pred`` to percentiles and
|
|
123
|
+
returns ``|rank_pct(y_true) - rank_pct(y_pred)|``. Requires a group-coherent
|
|
124
|
+
splitter so that each group's full cross-section is scored together.
|
|
125
|
+
"""
|
|
126
|
+
yt = np.asarray(y_true, dtype=float)
|
|
127
|
+
grouping = Grouping.from_labels(groups, n=yt.shape[0])
|
|
128
|
+
rank_true = grouping.rank_within(yt, pct=True)
|
|
129
|
+
rank_pred = grouping.rank_within(y_pred, pct=True)
|
|
130
|
+
out: npt.NDArray[Any] = np.abs(rank_true - rank_pred)
|
|
131
|
+
return out
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def apply_error_transform(
|
|
135
|
+
errors: npt.ArrayLike,
|
|
136
|
+
method: TargetTransform = "log",
|
|
137
|
+
*,
|
|
138
|
+
eps: float = 1e-6,
|
|
139
|
+
) -> npt.NDArray[Any]:
|
|
140
|
+
"""Stabilize heavy-tailed error targets before training ``g``.
|
|
141
|
+
|
|
142
|
+
- ``log``: ``log(error + eps)`` (default; used by :class:`~deup.estimators.DEUPRegressor`)
|
|
143
|
+
- ``asinh``: ``asinh(error / eps)`` — robust alternative for very heavy tails
|
|
144
|
+
- ``none``: identity
|
|
145
|
+
"""
|
|
146
|
+
err = np.asarray(errors, dtype=float)
|
|
147
|
+
if method == "none":
|
|
148
|
+
return err
|
|
149
|
+
if method == "log":
|
|
150
|
+
out: npt.NDArray[Any] = np.log(err + eps)
|
|
151
|
+
return out
|
|
152
|
+
if method == "asinh":
|
|
153
|
+
out = np.arcsinh(err / eps)
|
|
154
|
+
return out
|
|
155
|
+
raise ValueError(f"Unknown target transform {method!r}. Choose from log, asinh, none.")
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def inverse_error_transform(
|
|
159
|
+
values: npt.ArrayLike,
|
|
160
|
+
method: TargetTransform = "log",
|
|
161
|
+
*,
|
|
162
|
+
eps: float = 1e-6,
|
|
163
|
+
) -> npt.NDArray[Any]:
|
|
164
|
+
"""Map ``g``'s prediction back to the error scale."""
|
|
165
|
+
vals = np.asarray(values, dtype=float)
|
|
166
|
+
if method == "none":
|
|
167
|
+
return vals
|
|
168
|
+
if method == "log":
|
|
169
|
+
out: npt.NDArray[Any] = np.exp(vals) - eps
|
|
170
|
+
return out
|
|
171
|
+
if method == "asinh":
|
|
172
|
+
out = np.sinh(vals) * eps
|
|
173
|
+
return out
|
|
174
|
+
raise ValueError(f"Unknown target transform {method!r}. Choose from log, asinh, none.")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
_REGISTRY: dict[str, LossFn] = {
|
|
178
|
+
"squared": squared_error,
|
|
179
|
+
"absolute": absolute_error,
|
|
180
|
+
"logloss": log_loss,
|
|
181
|
+
"brier": brier_loss,
|
|
182
|
+
"rank": rank_loss,
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def get_loss(loss: str | LossFn, **kwargs: Any) -> LossFn:
|
|
187
|
+
"""Resolve ``loss`` (a registry name or a callable) to a loss function.
|
|
188
|
+
|
|
189
|
+
For ``pinball``, pass ``q`` (default 0.5) or use the string ``"pinball:0.9"``.
|
|
190
|
+
"""
|
|
191
|
+
if callable(loss):
|
|
192
|
+
return loss
|
|
193
|
+
if loss.startswith("pinball"):
|
|
194
|
+
q = float(kwargs.get("q", 0.5))
|
|
195
|
+
if ":" in loss:
|
|
196
|
+
q = float(loss.split(":", 1)[1])
|
|
197
|
+
q_val = q
|
|
198
|
+
|
|
199
|
+
def _pinball(
|
|
200
|
+
y_true: npt.ArrayLike,
|
|
201
|
+
y_pred: npt.ArrayLike,
|
|
202
|
+
groups: npt.ArrayLike | None = None,
|
|
203
|
+
) -> npt.NDArray[Any]:
|
|
204
|
+
return pinball_loss(y_true, y_pred, groups, q=q_val)
|
|
205
|
+
|
|
206
|
+
return _pinball
|
|
207
|
+
try:
|
|
208
|
+
return _REGISTRY[loss]
|
|
209
|
+
except KeyError:
|
|
210
|
+
raise ValueError(
|
|
211
|
+
f"Unknown loss {loss!r}. Choose from {sorted(_REGISTRY)} "
|
|
212
|
+
f"(or pinball[:q]) or pass a callable."
|
|
213
|
+
) from None
|
deup/core/oof.py
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""Out-of-fold error collection -- the correctness heart of DEUP.
|
|
2
|
+
|
|
3
|
+
This implements the paper's Algorithm 2 (K-fold pre-fill of the error dataset): for
|
|
4
|
+
each fold, fit a *fresh* clone of the base model on the training rows and predict the
|
|
5
|
+
held-out rows, so every row receives an **out-of-sample** prediction. The pointwise
|
|
6
|
+
loss of those predictions is the training target for the secondary error predictor.
|
|
7
|
+
|
|
8
|
+
Training the error predictor on in-sample errors instead (e.g. by predicting rows the
|
|
9
|
+
base model was trained on) is the canonical DEUP failure mode -- it underestimates
|
|
10
|
+
epistemic uncertainty (Lahlou et al., 2023, Sec. 3.2). The leakage test in the test
|
|
11
|
+
suite is designed to fail if this collector ever regresses to in-sample behavior.
|
|
12
|
+
|
|
13
|
+
Refit assumption
|
|
14
|
+
----------------
|
|
15
|
+
By default the collector also refits the base model ``f`` on *all* training data and
|
|
16
|
+
exposes it as ``OOFResult.estimator`` for deployment. The error predictor ``g`` is
|
|
17
|
+
therefore trained on the out-of-sample errors of fold models ``f_{-k}`` (each fit on
|
|
18
|
+
a strict subset of the data), but deployed alongside the full-data ``f``. This is the
|
|
19
|
+
standard DEUP / stacking assumption: ``g`` learns the error of a *slightly smaller*
|
|
20
|
+
model than the one it is paired with at inference. In practice fold and full models
|
|
21
|
+
are close for reasonable fold counts; for time-series the fold models are genuinely
|
|
22
|
+
smaller (expanding window), which is the realistic operating regime and is handled
|
|
23
|
+
explicitly by walk-forward splitters. Set ``refit_on_all=False`` to disable.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from __future__ import annotations
|
|
27
|
+
|
|
28
|
+
import warnings
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
import numpy as np
|
|
32
|
+
import numpy.typing as npt
|
|
33
|
+
from sklearn.base import clone
|
|
34
|
+
|
|
35
|
+
from deup.core.losses import LossFn, get_loss
|
|
36
|
+
from deup.core.types import OOFResult
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _safe_index(X: Any, idx: npt.NDArray[Any]) -> Any:
|
|
40
|
+
"""Row-index ``X`` whether it is a numpy array or a pandas object."""
|
|
41
|
+
if hasattr(X, "iloc"):
|
|
42
|
+
return X.iloc[idx]
|
|
43
|
+
return np.asarray(X)[idx]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class OOFErrorCollector:
|
|
47
|
+
"""Collect a base model's out-of-fold predictions and pointwise errors.
|
|
48
|
+
|
|
49
|
+
Parameters
|
|
50
|
+
----------
|
|
51
|
+
estimator:
|
|
52
|
+
The base model ``f`` (any scikit-learn-style ``fit``/``predict`` object).
|
|
53
|
+
It is cloned per fold; the passed instance is never fitted in place.
|
|
54
|
+
cv:
|
|
55
|
+
A splitter exposing ``split(X, y, groups)`` (e.g. ``KFold``,
|
|
56
|
+
``TimeSeriesSplit``, or :class:`deup.splitters.PurgedWalkForward`). For
|
|
57
|
+
time-ordered data use a non-shuffling splitter; the collector itself never
|
|
58
|
+
shuffles.
|
|
59
|
+
loss:
|
|
60
|
+
Error-target loss: a registry name (``"squared"``, ``"absolute"``,
|
|
61
|
+
``"logloss"``, ``"brier"``, ``"pinball"``, ``"rank"``) or a callable
|
|
62
|
+
``loss(y_true, y_pred, groups)``.
|
|
63
|
+
proba:
|
|
64
|
+
If ``True``, use ``predict_proba`` instead of ``predict`` -- required for
|
|
65
|
+
classification log-loss / Brier targets. Binary probabilities are stored as
|
|
66
|
+
the positive-class column; multiclass probabilities are stored as a 2-D
|
|
67
|
+
array and passed through to the loss.
|
|
68
|
+
refit_on_all:
|
|
69
|
+
If ``True`` (default), also refit a clone of the base model on all data and
|
|
70
|
+
expose it as ``OOFResult.estimator``. See the module docstring for the
|
|
71
|
+
"g trained on errors of a slightly smaller f" assumption this entails.
|
|
72
|
+
|
|
73
|
+
Notes
|
|
74
|
+
-----
|
|
75
|
+
Rows never assigned to a test fold (e.g. the earliest rows under walk-forward)
|
|
76
|
+
are excluded from the returned :class:`~deup.core.types.OOFResult`. If a row is
|
|
77
|
+
assigned to more than one test fold (e.g. repeated CV), a warning is raised and
|
|
78
|
+
the last fold's prediction is kept, since averaging would break the
|
|
79
|
+
one-error-per-row contract that ``g`` is trained on.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
estimator: Any,
|
|
85
|
+
cv: Any,
|
|
86
|
+
loss: str | LossFn = "squared",
|
|
87
|
+
*,
|
|
88
|
+
proba: bool = False,
|
|
89
|
+
refit_on_all: bool = True,
|
|
90
|
+
) -> None:
|
|
91
|
+
self.estimator = estimator
|
|
92
|
+
self.cv = cv
|
|
93
|
+
self.loss = loss
|
|
94
|
+
self.proba = proba
|
|
95
|
+
self.refit_on_all = refit_on_all
|
|
96
|
+
|
|
97
|
+
def _predict_fold(self, model: Any, X_test: Any) -> npt.NDArray[Any]:
|
|
98
|
+
"""Return fold predictions: 1-D point preds, pos-class probs, or 2-D probs."""
|
|
99
|
+
if not self.proba:
|
|
100
|
+
return np.asarray(model.predict(X_test), dtype=float)
|
|
101
|
+
proba = np.asarray(model.predict_proba(X_test), dtype=float)
|
|
102
|
+
if proba.ndim == 2 and proba.shape[1] == 2:
|
|
103
|
+
return proba[:, 1]
|
|
104
|
+
return proba
|
|
105
|
+
|
|
106
|
+
def fit_collect(
|
|
107
|
+
self, X: Any, y: npt.ArrayLike, groups: npt.ArrayLike | None = None
|
|
108
|
+
) -> OOFResult:
|
|
109
|
+
"""Run the out-of-fold loop and return the collected errors.
|
|
110
|
+
|
|
111
|
+
Parameters
|
|
112
|
+
----------
|
|
113
|
+
X, y:
|
|
114
|
+
Training features and targets.
|
|
115
|
+
groups:
|
|
116
|
+
Optional per-row group labels (e.g. dates). Passed to the splitter and to
|
|
117
|
+
group-aware losses such as ``"rank"``.
|
|
118
|
+
"""
|
|
119
|
+
y_arr = np.asarray(y)
|
|
120
|
+
n = y_arr.shape[0]
|
|
121
|
+
groups_arr = None if groups is None else np.asarray(groups)
|
|
122
|
+
if groups_arr is not None and groups_arr.shape[0] != n:
|
|
123
|
+
raise ValueError(f"groups length {groups_arr.shape[0]} != n_rows {n}")
|
|
124
|
+
|
|
125
|
+
# Accumulate per-fold predictions so we can size the output array correctly
|
|
126
|
+
# for either point predictions (1-D) or multiclass probabilities (2-D).
|
|
127
|
+
fold_results: list[tuple[npt.NDArray[Any], npt.NDArray[Any]]] = []
|
|
128
|
+
pred_width: int | None = None # None => 1-D output; int => 2-D output
|
|
129
|
+
for fold, (train_idx, test_idx) in enumerate(self.cv.split(X, y_arr, groups_arr)):
|
|
130
|
+
if len(test_idx) == 0:
|
|
131
|
+
continue # degenerate fold: nothing held out
|
|
132
|
+
model = clone(self.estimator)
|
|
133
|
+
model.fit(_safe_index(X, train_idx), y_arr[train_idx])
|
|
134
|
+
pred = self._predict_fold(model, _safe_index(X, test_idx))
|
|
135
|
+
if pred.ndim == 2:
|
|
136
|
+
pred_width = pred.shape[1]
|
|
137
|
+
fold_results.append((np.asarray(test_idx), pred))
|
|
138
|
+
del fold # fold index not needed beyond enumerate
|
|
139
|
+
|
|
140
|
+
if not fold_results:
|
|
141
|
+
raise ValueError("No out-of-fold predictions were produced by the splitter.")
|
|
142
|
+
|
|
143
|
+
if pred_width is None:
|
|
144
|
+
oof_pred: npt.NDArray[Any] = np.full(n, np.nan, dtype=float)
|
|
145
|
+
else:
|
|
146
|
+
oof_pred = np.full((n, pred_width), np.nan, dtype=float)
|
|
147
|
+
fold_ids = np.full(n, -1, dtype=np.intp)
|
|
148
|
+
hit_count = np.zeros(n, dtype=np.intp)
|
|
149
|
+
|
|
150
|
+
for fold, (test_idx, pred) in enumerate(fold_results):
|
|
151
|
+
oof_pred[test_idx] = pred
|
|
152
|
+
fold_ids[test_idx] = fold
|
|
153
|
+
hit_count[test_idx] += 1
|
|
154
|
+
|
|
155
|
+
if (hit_count > 1).any():
|
|
156
|
+
n_overlap = int((hit_count > 1).sum())
|
|
157
|
+
warnings.warn(
|
|
158
|
+
f"{n_overlap} row(s) were assigned to multiple test folds; "
|
|
159
|
+
"keeping the last prediction. Use a partitioning splitter for "
|
|
160
|
+
"honest one-error-per-row out-of-fold targets.",
|
|
161
|
+
stacklevel=2,
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
mask = fold_ids >= 0
|
|
165
|
+
loss_fn = get_loss(self.loss)
|
|
166
|
+
g_groups = None if groups_arr is None else groups_arr[mask]
|
|
167
|
+
errors = np.asarray(loss_fn(y_arr[mask], oof_pred[mask], g_groups), dtype=float)
|
|
168
|
+
if errors.shape[0] != int(mask.sum()):
|
|
169
|
+
raise ValueError(f"loss returned {errors.shape[0]} values for {int(mask.sum())} rows")
|
|
170
|
+
|
|
171
|
+
estimator_ = None
|
|
172
|
+
if self.refit_on_all:
|
|
173
|
+
estimator_ = clone(self.estimator)
|
|
174
|
+
estimator_.fit(X, y_arr)
|
|
175
|
+
|
|
176
|
+
return OOFResult(
|
|
177
|
+
predictions=oof_pred[mask],
|
|
178
|
+
errors=errors,
|
|
179
|
+
fold_ids=fold_ids[mask],
|
|
180
|
+
group_ids=g_groups,
|
|
181
|
+
indices=np.flatnonzero(mask),
|
|
182
|
+
estimator=estimator_,
|
|
183
|
+
)
|
deup/core/protocols.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Structural typing for the models ``deup`` wraps.
|
|
2
|
+
|
|
3
|
+
DEUP is model-agnostic: it orchestrates a *base* predictor and a *secondary* error
|
|
4
|
+
predictor that both follow the scikit-learn ``fit`` / ``predict`` convention. We
|
|
5
|
+
express that requirement structurally (via :class:`typing.Protocol`) rather than by
|
|
6
|
+
inheritance, so any duck-typed estimator — scikit-learn, LightGBM, XGBoost, a thin
|
|
7
|
+
wrapper around a neural net — qualifies without importing scikit-learn here.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from typing import Any, Protocol, runtime_checkable
|
|
13
|
+
|
|
14
|
+
import numpy.typing as npt
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@runtime_checkable
|
|
18
|
+
class Predictor(Protocol):
|
|
19
|
+
"""A minimal scikit-learn-style point predictor.
|
|
20
|
+
|
|
21
|
+
Any object exposing ``fit(X, y)`` and ``predict(X)`` satisfies this protocol.
|
|
22
|
+
The return type of ``fit`` is intentionally ``Any`` (scikit-learn returns
|
|
23
|
+
``self``); only the *presence* of the methods is required.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def fit(self, X: npt.ArrayLike, y: npt.ArrayLike) -> Any:
|
|
27
|
+
"""Fit the predictor on features ``X`` and targets ``y``."""
|
|
28
|
+
...
|
|
29
|
+
|
|
30
|
+
def predict(self, X: npt.ArrayLike) -> npt.NDArray[Any]:
|
|
31
|
+
"""Return point predictions for ``X``."""
|
|
32
|
+
...
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@runtime_checkable
|
|
36
|
+
class ProbabilisticPredictor(Predictor, Protocol):
|
|
37
|
+
"""A classifier that additionally exposes ``predict_proba``."""
|
|
38
|
+
|
|
39
|
+
def predict_proba(self, X: npt.ArrayLike) -> npt.NDArray[Any]:
|
|
40
|
+
"""Return class-probability estimates for ``X``."""
|
|
41
|
+
...
|
deup/core/types.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""Typed, immutable result containers passed between DEUP's layers.
|
|
2
|
+
|
|
3
|
+
These dataclasses are the contract between the out-of-fold collector, the error
|
|
4
|
+
estimator, and the calibration layer. They are frozen (their fields cannot be
|
|
5
|
+
reassigned) and validate array-length consistency on construction, so a malformed
|
|
6
|
+
result fails loudly at the boundary rather than silently downstream.
|
|
7
|
+
|
|
8
|
+
``eq=False`` is deliberate: the fields are numpy arrays, whose element-wise ``==``
|
|
9
|
+
does not yield a single boolean, so an auto-generated ``__eq__`` would be a footgun.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any
|
|
16
|
+
|
|
17
|
+
import numpy as np
|
|
18
|
+
import numpy.typing as npt
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclass(frozen=True, eq=False)
|
|
22
|
+
class OOFResult:
|
|
23
|
+
"""Out-of-fold artifacts produced when collecting a base model's errors.
|
|
24
|
+
|
|
25
|
+
Attributes
|
|
26
|
+
----------
|
|
27
|
+
predictions:
|
|
28
|
+
Out-of-fold predictions of the base model ``f``, one per row.
|
|
29
|
+
errors:
|
|
30
|
+
Per-row error targets that the secondary predictor ``g`` will learn from
|
|
31
|
+
(e.g. squared residuals or per-group rank losses).
|
|
32
|
+
fold_ids:
|
|
33
|
+
The fold in which each row was held out. Useful for diagnostics and for
|
|
34
|
+
walk-forward reporting.
|
|
35
|
+
group_ids:
|
|
36
|
+
Optional per-row group label (e.g. a date for cross-sectional ranking).
|
|
37
|
+
``None`` for i.i.d. data.
|
|
38
|
+
indices:
|
|
39
|
+
Optional positions of these rows in the original input ``X`` (the rows that
|
|
40
|
+
received an out-of-fold prediction). ``None`` if not tracked.
|
|
41
|
+
estimator:
|
|
42
|
+
Optionally, the base model refit on all data for deployment. ``None`` if
|
|
43
|
+
the caller chose not to refit.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
predictions: npt.NDArray[Any]
|
|
47
|
+
errors: npt.NDArray[Any]
|
|
48
|
+
fold_ids: npt.NDArray[Any]
|
|
49
|
+
group_ids: npt.NDArray[Any] | None = None
|
|
50
|
+
indices: npt.NDArray[Any] | None = None
|
|
51
|
+
estimator: Any = field(default=None)
|
|
52
|
+
|
|
53
|
+
def __post_init__(self) -> None:
|
|
54
|
+
preds = np.asarray(self.predictions)
|
|
55
|
+
errs = np.asarray(self.errors)
|
|
56
|
+
folds = np.asarray(self.fold_ids)
|
|
57
|
+
object.__setattr__(self, "predictions", preds)
|
|
58
|
+
object.__setattr__(self, "errors", errs)
|
|
59
|
+
object.__setattr__(self, "fold_ids", folds)
|
|
60
|
+
|
|
61
|
+
n = preds.shape[0]
|
|
62
|
+
if errs.shape[0] != n or folds.shape[0] != n:
|
|
63
|
+
raise ValueError(
|
|
64
|
+
"OOFResult arrays must share length: "
|
|
65
|
+
f"predictions={preds.shape[0]}, errors={errs.shape[0]}, "
|
|
66
|
+
f"fold_ids={folds.shape[0]}"
|
|
67
|
+
)
|
|
68
|
+
for name in ("group_ids", "indices"):
|
|
69
|
+
value = getattr(self, name)
|
|
70
|
+
if value is not None:
|
|
71
|
+
arr = np.asarray(value)
|
|
72
|
+
object.__setattr__(self, name, arr)
|
|
73
|
+
if arr.shape[0] != n:
|
|
74
|
+
raise ValueError(f"{name} length {arr.shape[0]} != n_rows {n}")
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def n(self) -> int:
|
|
78
|
+
"""Number of rows."""
|
|
79
|
+
return int(self.predictions.shape[0])
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True, eq=False)
|
|
83
|
+
class UncertaintyResult:
|
|
84
|
+
"""A prediction together with its uncertainty decomposition.
|
|
85
|
+
|
|
86
|
+
Attributes
|
|
87
|
+
----------
|
|
88
|
+
prediction:
|
|
89
|
+
Point prediction of the base model.
|
|
90
|
+
epistemic:
|
|
91
|
+
Estimated epistemic uncertainty ``g(x)`` (optionally net of aleatoric).
|
|
92
|
+
aleatoric:
|
|
93
|
+
Optional estimated aleatoric (irreducible) uncertainty ``a(x)``.
|
|
94
|
+
lower, upper:
|
|
95
|
+
Optional calibrated prediction-interval bounds.
|
|
96
|
+
"""
|
|
97
|
+
|
|
98
|
+
prediction: npt.NDArray[Any]
|
|
99
|
+
epistemic: npt.NDArray[Any]
|
|
100
|
+
aleatoric: npt.NDArray[Any] | None = None
|
|
101
|
+
lower: npt.NDArray[Any] | None = None
|
|
102
|
+
upper: npt.NDArray[Any] | None = None
|
|
103
|
+
|
|
104
|
+
def __post_init__(self) -> None:
|
|
105
|
+
pred = np.asarray(self.prediction)
|
|
106
|
+
epi = np.asarray(self.epistemic)
|
|
107
|
+
object.__setattr__(self, "prediction", pred)
|
|
108
|
+
object.__setattr__(self, "epistemic", epi)
|
|
109
|
+
|
|
110
|
+
n = pred.shape[0]
|
|
111
|
+
if epi.shape[0] != n:
|
|
112
|
+
raise ValueError(f"epistemic length {epi.shape[0]} != prediction length {n}")
|
|
113
|
+
for name in ("aleatoric", "lower", "upper"):
|
|
114
|
+
value = getattr(self, name)
|
|
115
|
+
if value is not None:
|
|
116
|
+
arr = np.asarray(value)
|
|
117
|
+
object.__setattr__(self, name, arr)
|
|
118
|
+
if arr.shape[0] != n:
|
|
119
|
+
raise ValueError(f"{name} length {arr.shape[0]} != prediction length {n}")
|
|
120
|
+
|
|
121
|
+
@property
|
|
122
|
+
def n(self) -> int:
|
|
123
|
+
"""Number of rows."""
|
|
124
|
+
return int(self.prediction.shape[0])
|
deup/estimators.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""User-facing DEUP estimators.
|
|
2
|
+
|
|
3
|
+
``DEUPRegressor`` is the ergonomic, scikit-learn-compatible entry point: wrap any
|
|
4
|
+
regressor, fit, and get a point prediction plus an epistemic-uncertainty estimate.
|
|
5
|
+
|
|
6
|
+
from sklearn.ensemble import RandomForestRegressor
|
|
7
|
+
from deup import DEUPRegressor
|
|
8
|
+
|
|
9
|
+
model = DEUPRegressor(base_model=RandomForestRegressor())
|
|
10
|
+
model.fit(X_train, y_train)
|
|
11
|
+
pred, unc = model.predict(X_test, return_uncertainty=True)
|
|
12
|
+
|
|
13
|
+
Under the hood it composes the leakage-correct :class:`~deup.core.oof.OOFErrorCollector`
|
|
14
|
+
(out-of-sample errors of the base model) with a secondary "error predictor" ``g`` that
|
|
15
|
+
regresses those errors -- this is DEUP (Lahlou et al., 2023). In this minimal v0.1
|
|
16
|
+
the aleatoric term is taken as zero, so the reported epistemic uncertainty is the
|
|
17
|
+
predicted out-of-sample error ``g(x)`` (the paper's conservative proxy); the
|
|
18
|
+
aleatoric decomposition and density/variance features are added in later versions.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
import numpy.typing as npt
|
|
27
|
+
from sklearn.base import BaseEstimator, MetaEstimatorMixin, RegressorMixin, clone
|
|
28
|
+
from sklearn.ensemble import HistGradientBoostingRegressor
|
|
29
|
+
from sklearn.model_selection import KFold
|
|
30
|
+
from sklearn.utils.validation import check_is_fitted
|
|
31
|
+
|
|
32
|
+
from deup.core.losses import TargetTransform, apply_error_transform, inverse_error_transform
|
|
33
|
+
from deup.core.oof import OOFErrorCollector, _safe_index
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class DEUPRegressor(RegressorMixin, MetaEstimatorMixin, BaseEstimator):
|
|
37
|
+
"""Direct Epistemic Uncertainty Prediction for regression.
|
|
38
|
+
|
|
39
|
+
Parameters
|
|
40
|
+
----------
|
|
41
|
+
base_model:
|
|
42
|
+
The regressor whose uncertainty we estimate. Defaults to
|
|
43
|
+
:class:`~sklearn.ensemble.HistGradientBoostingRegressor`.
|
|
44
|
+
error_model:
|
|
45
|
+
The secondary error predictor ``g``. Defaults to
|
|
46
|
+
:class:`~sklearn.ensemble.HistGradientBoostingRegressor` (no extra deps).
|
|
47
|
+
cv:
|
|
48
|
+
An int (number of ``KFold`` folds) or any splitter exposing ``split``
|
|
49
|
+
(e.g. :class:`deup.splitters.PurgedWalkForward` for time series).
|
|
50
|
+
loss:
|
|
51
|
+
Error-target loss passed to the collector (``"squared"`` by default).
|
|
52
|
+
target_transform:
|
|
53
|
+
Stabilization for ``g``'s regression target: ``"log"`` (default),
|
|
54
|
+
``"asinh"``, or ``"none"``.
|
|
55
|
+
log_target:
|
|
56
|
+
Deprecated alias for ``target_transform="log"``. If ``False``, sets
|
|
57
|
+
``target_transform="none"`` unless ``target_transform`` is explicitly given.
|
|
58
|
+
error_eps:
|
|
59
|
+
Stabilizer for ``log`` / ``asinh`` transforms.
|
|
60
|
+
random_state:
|
|
61
|
+
Seed used when ``cv`` is an int (a shuffled ``KFold``).
|
|
62
|
+
|
|
63
|
+
Attributes
|
|
64
|
+
----------
|
|
65
|
+
base_model_ :
|
|
66
|
+
The base model refit on all training data (used for ``predict``).
|
|
67
|
+
error_model_ :
|
|
68
|
+
The fitted error predictor ``g``.
|
|
69
|
+
oof_ :
|
|
70
|
+
The :class:`~deup.core.types.OOFResult` used to train ``g``.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(
|
|
74
|
+
self,
|
|
75
|
+
base_model: Any = None,
|
|
76
|
+
error_model: Any = None,
|
|
77
|
+
cv: Any = 5,
|
|
78
|
+
loss: Any = "squared",
|
|
79
|
+
*,
|
|
80
|
+
target_transform: TargetTransform | None = None,
|
|
81
|
+
log_target: bool = True,
|
|
82
|
+
error_eps: float = 1e-6,
|
|
83
|
+
random_state: int | None = None,
|
|
84
|
+
) -> None:
|
|
85
|
+
self.base_model = base_model
|
|
86
|
+
self.error_model = error_model
|
|
87
|
+
self.cv = cv
|
|
88
|
+
self.loss = loss
|
|
89
|
+
if target_transform is not None:
|
|
90
|
+
self.target_transform: TargetTransform = target_transform
|
|
91
|
+
else:
|
|
92
|
+
self.target_transform = "log" if log_target else "none"
|
|
93
|
+
self.log_target = log_target
|
|
94
|
+
self.error_eps = error_eps
|
|
95
|
+
self.random_state = random_state
|
|
96
|
+
|
|
97
|
+
def _resolve_cv(self) -> Any:
|
|
98
|
+
if isinstance(self.cv, int):
|
|
99
|
+
return KFold(n_splits=self.cv, shuffle=True, random_state=self.random_state)
|
|
100
|
+
return self.cv
|
|
101
|
+
|
|
102
|
+
def fit(self, X: Any, y: npt.ArrayLike, groups: npt.ArrayLike | None = None) -> DEUPRegressor:
|
|
103
|
+
"""Fit the base model (out-of-fold) and the error predictor ``g``."""
|
|
104
|
+
base = self.base_model if self.base_model is not None else HistGradientBoostingRegressor()
|
|
105
|
+
err = self.error_model if self.error_model is not None else HistGradientBoostingRegressor()
|
|
106
|
+
|
|
107
|
+
collector = OOFErrorCollector(
|
|
108
|
+
base, cv=self._resolve_cv(), loss=self.loss, refit_on_all=True
|
|
109
|
+
)
|
|
110
|
+
oof = collector.fit_collect(X, y, groups=groups)
|
|
111
|
+
|
|
112
|
+
assert oof.indices is not None # collector always records indices
|
|
113
|
+
g_X = _safe_index(X, oof.indices)
|
|
114
|
+
target = apply_error_transform(oof.errors, method=self.target_transform, eps=self.error_eps)
|
|
115
|
+
|
|
116
|
+
self.error_model_ = clone(err)
|
|
117
|
+
self.error_model_.fit(g_X, target)
|
|
118
|
+
self.base_model_ = oof.estimator
|
|
119
|
+
self.oof_ = oof
|
|
120
|
+
if hasattr(X, "shape"):
|
|
121
|
+
self.n_features_in_ = int(X.shape[1])
|
|
122
|
+
return self
|
|
123
|
+
|
|
124
|
+
def predict(
|
|
125
|
+
self, X: Any, return_uncertainty: bool = False
|
|
126
|
+
) -> npt.NDArray[Any] | tuple[npt.NDArray[Any], npt.NDArray[Any]]:
|
|
127
|
+
"""Predict, optionally returning ``(prediction, epistemic_uncertainty)``."""
|
|
128
|
+
check_is_fitted(self, "base_model_")
|
|
129
|
+
pred = np.asarray(self.base_model_.predict(X), dtype=float)
|
|
130
|
+
if not return_uncertainty:
|
|
131
|
+
return pred
|
|
132
|
+
return pred, self.predict_epistemic(X)
|
|
133
|
+
|
|
134
|
+
def predict_epistemic(self, X: Any) -> npt.NDArray[Any]:
|
|
135
|
+
"""Return the estimated epistemic uncertainty ``g(x)`` (>= 0)."""
|
|
136
|
+
check_is_fitted(self, "error_model_")
|
|
137
|
+
raw = np.asarray(self.error_model_.predict(X), dtype=float)
|
|
138
|
+
unc = inverse_error_transform(raw, method=self.target_transform, eps=self.error_eps)
|
|
139
|
+
clipped: npt.NDArray[Any] = np.clip(unc, 0.0, None)
|
|
140
|
+
return clipped
|
deup/py.typed
ADDED
|
File without changes
|
deup/splitters.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Cross-validation splitters for collecting out-of-sample errors.
|
|
2
|
+
|
|
3
|
+
DEUP's error predictor must be trained on *out-of-sample* errors of the base model
|
|
4
|
+
(Lahlou et al., 2023, Algorithms 1-2). The splitter is therefore the leakage-control
|
|
5
|
+
knob: choose ``KFold`` for i.i.d. data, ``TimeSeriesSplit`` for ordered data, and
|
|
6
|
+
:class:`PurgedWalkForward` for time-series / cross-sectional data where an embargo is
|
|
7
|
+
needed to prevent look-ahead between train and test.
|
|
8
|
+
|
|
9
|
+
``KFold`` and ``TimeSeriesSplit`` are re-exported from scikit-learn so users have a
|
|
10
|
+
single import surface.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Iterator
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
import numpy.typing as npt
|
|
20
|
+
from sklearn.model_selection import KFold, TimeSeriesSplit
|
|
21
|
+
|
|
22
|
+
__all__ = ["KFold", "PurgedWalkForward", "TimeSeriesSplit"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _n_rows(X: Any) -> int:
|
|
26
|
+
if hasattr(X, "shape"):
|
|
27
|
+
return int(X.shape[0])
|
|
28
|
+
return len(X)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PurgedWalkForward:
|
|
32
|
+
"""Expanding-window walk-forward splitter with an embargo (purge).
|
|
33
|
+
|
|
34
|
+
Time is measured in *units*. If ``groups`` is passed to :meth:`split`, each
|
|
35
|
+
unique group value (e.g. a date) is one time unit and the whole cross-section
|
|
36
|
+
of a unit always stays together in the same fold — which is required for
|
|
37
|
+
cross-sectional rank losses. If ``groups`` is ``None``, each row is its own unit.
|
|
38
|
+
|
|
39
|
+
For each of ``n_splits`` folds, the test block is a contiguous range of the most
|
|
40
|
+
recent units; the training set is all units strictly before it, minus an
|
|
41
|
+
``embargo`` of units immediately preceding the test block (the purge). This
|
|
42
|
+
prevents the base model from being trained on data adjacent to (and potentially
|
|
43
|
+
leaking into) the evaluation block.
|
|
44
|
+
|
|
45
|
+
Parameters
|
|
46
|
+
----------
|
|
47
|
+
n_splits:
|
|
48
|
+
Number of walk-forward test folds.
|
|
49
|
+
embargo:
|
|
50
|
+
Number of time units to drop between the train set and each test block.
|
|
51
|
+
min_train_size:
|
|
52
|
+
Minimum number of training units required to emit a fold; smaller folds are
|
|
53
|
+
skipped.
|
|
54
|
+
max_train_size:
|
|
55
|
+
If set, training uses at most this many of the most recent units (rolling
|
|
56
|
+
window). Otherwise the window expands from the start.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(
|
|
60
|
+
self,
|
|
61
|
+
n_splits: int = 5,
|
|
62
|
+
embargo: int = 0,
|
|
63
|
+
min_train_size: int = 1,
|
|
64
|
+
max_train_size: int | None = None,
|
|
65
|
+
) -> None:
|
|
66
|
+
if n_splits < 1:
|
|
67
|
+
raise ValueError("n_splits must be >= 1")
|
|
68
|
+
if embargo < 0:
|
|
69
|
+
raise ValueError("embargo must be >= 0")
|
|
70
|
+
if min_train_size < 1:
|
|
71
|
+
raise ValueError("min_train_size must be >= 1")
|
|
72
|
+
self.n_splits = n_splits
|
|
73
|
+
self.embargo = embargo
|
|
74
|
+
self.min_train_size = min_train_size
|
|
75
|
+
self.max_train_size = max_train_size
|
|
76
|
+
|
|
77
|
+
def get_n_splits(self, X: Any = None, y: Any = None, groups: Any = None) -> int:
|
|
78
|
+
return self.n_splits
|
|
79
|
+
|
|
80
|
+
def split(
|
|
81
|
+
self, X: Any, y: Any = None, groups: npt.ArrayLike | None = None
|
|
82
|
+
) -> Iterator[tuple[npt.NDArray[Any], npt.NDArray[Any]]]:
|
|
83
|
+
"""Yield ``(train_idx, test_idx)`` row-index arrays for each fold."""
|
|
84
|
+
n = _n_rows(X)
|
|
85
|
+
if groups is None:
|
|
86
|
+
row_units = np.arange(n)
|
|
87
|
+
n_units = n
|
|
88
|
+
else:
|
|
89
|
+
groups_arr = np.asarray(groups)
|
|
90
|
+
if groups_arr.shape[0] != n:
|
|
91
|
+
raise ValueError(f"groups length {groups_arr.shape[0]} != n_rows {n}")
|
|
92
|
+
_, row_units = np.unique(groups_arr, return_inverse=True)
|
|
93
|
+
row_units = np.ravel(row_units)
|
|
94
|
+
n_units = int(row_units.max()) + 1 if n > 0 else 0
|
|
95
|
+
|
|
96
|
+
test_size = n_units // (self.n_splits + 1)
|
|
97
|
+
if test_size < 1:
|
|
98
|
+
raise ValueError(f"Not enough time units ({n_units}) for n_splits={self.n_splits}")
|
|
99
|
+
|
|
100
|
+
indices = np.arange(n)
|
|
101
|
+
for i in range(self.n_splits):
|
|
102
|
+
test_start = n_units - (self.n_splits - i) * test_size
|
|
103
|
+
test_end = test_start + test_size
|
|
104
|
+
train_end = test_start - self.embargo
|
|
105
|
+
if train_end < self.min_train_size:
|
|
106
|
+
continue
|
|
107
|
+
train_start = 0
|
|
108
|
+
if self.max_train_size is not None:
|
|
109
|
+
train_start = max(0, train_end - self.max_train_size)
|
|
110
|
+
|
|
111
|
+
train_mask = (row_units >= train_start) & (row_units < train_end)
|
|
112
|
+
test_mask = (row_units >= test_start) & (row_units < test_end)
|
|
113
|
+
train_idx = indices[train_mask]
|
|
114
|
+
test_idx = indices[test_mask]
|
|
115
|
+
if train_idx.shape[0] == 0 or test_idx.shape[0] == 0:
|
|
116
|
+
continue
|
|
117
|
+
yield train_idx, test_idx
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: deup
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Direct Epistemic Uncertainty Prediction (DEUP) for any scikit-learn model, with first-class time-series support.
|
|
5
|
+
Project-URL: Homepage, https://github.com/ursinasanderink/deup
|
|
6
|
+
Project-URL: Repository, https://github.com/ursinasanderink/deup
|
|
7
|
+
Project-URL: Issues, https://github.com/ursinasanderink/deup/issues
|
|
8
|
+
Author: Ursina Sanderink
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: conformal-prediction,deup,epistemic-uncertainty,machine-learning,scikit-learn,time-series,uncertainty
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Requires-Dist: numpy>=1.23
|
|
23
|
+
Requires-Dist: scikit-learn>=1.3
|
|
24
|
+
Provides-Extra: dev
|
|
25
|
+
Requires-Dist: mypy>=1.8; extra == 'dev'
|
|
26
|
+
Requires-Dist: pre-commit>=3.5; extra == 'dev'
|
|
27
|
+
Requires-Dist: pytest-cov>=4.1; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest>=7.4; extra == 'dev'
|
|
29
|
+
Requires-Dist: ruff>=0.5; extra == 'dev'
|
|
30
|
+
Provides-Extra: docs
|
|
31
|
+
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
|
|
32
|
+
Requires-Dist: mkdocstrings[python]>=0.24; extra == 'docs'
|
|
33
|
+
Provides-Extra: finance
|
|
34
|
+
Requires-Dist: pandas>=2.0; extra == 'finance'
|
|
35
|
+
Provides-Extra: gbm
|
|
36
|
+
Requires-Dist: lightgbm>=4.0; extra == 'gbm'
|
|
37
|
+
Provides-Extra: torch
|
|
38
|
+
Requires-Dist: gpytorch>=1.11; extra == 'torch'
|
|
39
|
+
Requires-Dist: torch>=2.0; extra == 'torch'
|
|
40
|
+
Description-Content-Type: text/markdown
|
|
41
|
+
|
|
42
|
+
# deup
|
|
43
|
+
|
|
44
|
+
**Direct Epistemic Uncertainty Prediction (DEUP) for any scikit-learn model — with first-class, leakage-correct time-series support.**
|
|
45
|
+
|
|
46
|
+
[](https://pypi.org/project/deup/)
|
|
47
|
+
[](https://github.com/ursinasanderink/deup/actions/workflows/ci.yml)
|
|
48
|
+
[](https://ursinasanderink.github.io/deup/)
|
|
49
|
+
|
|
50
|
+
DEUP estimates *epistemic* uncertainty by training a secondary **error predictor** on
|
|
51
|
+
your model's **out-of-sample** errors — no ensembles, no Bayesian retraining, works
|
|
52
|
+
with the model you already use. The method is due to
|
|
53
|
+
[Lahlou et al., 2023 (TMLR)](https://openreview.net/forum?id=eGLdVRvvfQ); this package
|
|
54
|
+
is a maintained, installable, scikit-learn-compatible implementation of it.
|
|
55
|
+
|
|
56
|
+
Repository: <https://github.com/ursinasanderink/deup> · Docs: <https://ursinasanderink.github.io/deup/>
|
|
57
|
+
|
|
58
|
+
## Quickstart
|
|
59
|
+
|
|
60
|
+
```python
|
|
61
|
+
from sklearn.ensemble import RandomForestRegressor
|
|
62
|
+
from deup import DEUPRegressor
|
|
63
|
+
|
|
64
|
+
model = DEUPRegressor(base_model=RandomForestRegressor())
|
|
65
|
+
model.fit(X_train, y_train)
|
|
66
|
+
|
|
67
|
+
pred, unc = model.predict(X_test, return_uncertainty=True)
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
For time-series / cross-sectional data, pass a leakage-safe splitter:
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from deup.splitters import PurgedWalkForward
|
|
74
|
+
|
|
75
|
+
model = DEUPRegressor(base_model=my_model, cv=PurgedWalkForward(embargo=5))
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Install
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
pip install deup # core (numpy + scikit-learn)
|
|
82
|
+
pip install "deup[gbm]" # + LightGBM error predictor
|
|
83
|
+
pip install "deup[docs]" # + MkDocs site locally
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Why this exists
|
|
87
|
+
|
|
88
|
+
The only public DEUP code is a 3-year-old research repo of notebooks; no maintained
|
|
89
|
+
`pip`-installable package existed until now. Major UQ libraries
|
|
90
|
+
(`torch-uncertainty`, `uncertainty-toolbox`, `MAPIE`) don't implement DEUP. `deup`
|
|
91
|
+
fills that gap with **correct out-of-fold error construction** for time-series /
|
|
92
|
+
cross-sectional data.
|
|
93
|
+
|
|
94
|
+
On California housing (v0.1 benchmark), DEUP uncertainty ranks test errors better
|
|
95
|
+
than ensemble disagreement or a conformal residual baseline — see [BENCHMARKS.md](BENCHMARKS.md).
|
|
96
|
+
|
|
97
|
+
## Status / roadmap
|
|
98
|
+
|
|
99
|
+
**v0.1 (released):** `DEUPRegressor`, OOF collector, splitters, full loss registry
|
|
100
|
+
(squared / Brier / pinball / rank), target transforms (log / asinh), benchmark, docs.
|
|
101
|
+
|
|
102
|
+
**v0.2:** `DEUPClassifier` / `DEUPRanker`, conformal intervals, aleatoric decomposition,
|
|
103
|
+
density/GP features, aggregation-reliability diagnostics.
|
|
104
|
+
|
|
105
|
+
## Citing
|
|
106
|
+
|
|
107
|
+
If you use `deup`, please cite both this software (see [`CITATION.cff`](CITATION.cff))
|
|
108
|
+
and the original DEUP paper (Lahlou et al., 2023).
|
|
109
|
+
|
|
110
|
+
## License
|
|
111
|
+
|
|
112
|
+
Apache-2.0. See [`LICENSE`](LICENSE).
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
deup/__init__.py,sha256=mJsLpzdlIfMHkyyLb9-IxpxMcy5wbtOJzJJWpTXwDEs,867
|
|
2
|
+
deup/estimators.py,sha256=R-xcC_9a6yXWSjz4UhHvWhO9fiOtbf3jQdSIRDIcQQQ,5753
|
|
3
|
+
deup/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
deup/splitters.py,sha256=szyzCbc0tDd50NwzQRjfiPgvNAWxtxleSoxK59VGgIA,4599
|
|
5
|
+
deup/core/__init__.py,sha256=a-G0rq_pZClZEqfHi4GHgMrEXYpKxQhwbRrvwLS6lbI,889
|
|
6
|
+
deup/core/grouping.py,sha256=eUNvNFzKQsiHS9dqae5Ps8VzmEFV-L2-vmJ4mcsIV3o,3723
|
|
7
|
+
deup/core/losses.py,sha256=iIioMIlCZ1vlRwUVJdbnvbm_kVws_eML5XpJKzJK8r0,6910
|
|
8
|
+
deup/core/oof.py,sha256=m_A1KI0JfLZv4cNFNznX485XX0HqMd00ZB0jiwP0kH8,7835
|
|
9
|
+
deup/core/protocols.py,sha256=S88ZvWh7WTSRZELW0Fs8wi2ajRRPT1j6H1J_NWB9pFo,1467
|
|
10
|
+
deup/core/types.py,sha256=JAlrrQxbLglhgAG_qokLxEcWUcybr4aU2niNEkcWzLo,4476
|
|
11
|
+
deup-0.1.1.dist-info/METADATA,sha256=Wee1uZjBxZuoAnlNKozrWnjb7knQCE5AZw0-HdvGj9s,4463
|
|
12
|
+
deup-0.1.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
|
|
13
|
+
deup-0.1.1.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
|
|
14
|
+
deup-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,201 @@
|
|
|
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.
|