dalheimdall 1.0.707__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.
- dalheimdall/__init__.py +275 -0
- dalheimdall/adaptive/__init__.py +84 -0
- dalheimdall/adaptive/concept.py +316 -0
- dalheimdall/adaptive/policy.py +142 -0
- dalheimdall/adaptive/recurrent.py +610 -0
- dalheimdall/adaptive/retrain.py +335 -0
- dalheimdall/adaptive/selectors.py +796 -0
- dalheimdall/base.py +375 -0
- dalheimdall/benchmark.py +829 -0
- dalheimdall/datasets.py +126 -0
- dalheimdall/detectors/__init__.py +116 -0
- dalheimdall/detectors/ensemble.py +750 -0
- dalheimdall/detectors/error.py +686 -0
- dalheimdall/detectors/multivariate.py +565 -0
- dalheimdall/detectors/neural.py +1594 -0
- dalheimdall/detectors/sketch.py +1133 -0
- dalheimdall/detectors/statistical.py +1612 -0
- dalheimdall/detectors/structural.py +1374 -0
- dalheimdall/detectors/univariate.py +810 -0
- dalheimdall/memory.py +107 -0
- dalheimdall/metrics.py +231 -0
- dalheimdall/norm.py +109 -0
- dalheimdall/transforms.py +72 -0
- dalheimdall/utils.py +565 -0
- dalheimdall-1.0.707.dist-info/METADATA +153 -0
- dalheimdall-1.0.707.dist-info/RECORD +28 -0
- dalheimdall-1.0.707.dist-info/WHEEL +4 -0
- dalheimdall-1.0.707.dist-info/licenses/LICENSE +21 -0
dalheimdall/__init__.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
"""dalheimdall: Drift Adaptable Models (Python port of the R heimdall package)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from . import benchmark, datasets
|
|
5
|
+
from .adaptive import (
|
|
6
|
+
AdpRecurrent,
|
|
7
|
+
AdpRetrain,
|
|
8
|
+
Concept,
|
|
9
|
+
ConceptPool,
|
|
10
|
+
ConceptPoolInactive,
|
|
11
|
+
ConceptRanker,
|
|
12
|
+
Evictor,
|
|
13
|
+
EvtLeastUsed,
|
|
14
|
+
EvtRedundant,
|
|
15
|
+
LearnedLimit,
|
|
16
|
+
ModelTrainer,
|
|
17
|
+
RankPsi,
|
|
18
|
+
RankRatio,
|
|
19
|
+
RareDrop,
|
|
20
|
+
RareKeep,
|
|
21
|
+
RarePolicy,
|
|
22
|
+
RecAlways,
|
|
23
|
+
RecordPolicy,
|
|
24
|
+
RecStable,
|
|
25
|
+
Selector,
|
|
26
|
+
SlctAe,
|
|
27
|
+
SlctErrorMetrics,
|
|
28
|
+
SlctInactive,
|
|
29
|
+
SlctPsi,
|
|
30
|
+
SlctPsiThenBest,
|
|
31
|
+
SlctPsiThenError,
|
|
32
|
+
TrainIncremental,
|
|
33
|
+
TrainRetrain,
|
|
34
|
+
TrainStatic,
|
|
35
|
+
adapt_incremental,
|
|
36
|
+
adapt_reset,
|
|
37
|
+
adapt_retrain,
|
|
38
|
+
adapt_static,
|
|
39
|
+
recurrent_ensemble,
|
|
40
|
+
recurrent_incremental,
|
|
41
|
+
)
|
|
42
|
+
from .base import (
|
|
43
|
+
DfrInactive,
|
|
44
|
+
DfrMultiCriteria,
|
|
45
|
+
DfrPassive,
|
|
46
|
+
DistBased,
|
|
47
|
+
Drifter,
|
|
48
|
+
DriftWorkflow,
|
|
49
|
+
Dummy,
|
|
50
|
+
ErrorBased,
|
|
51
|
+
MvDistBased,
|
|
52
|
+
drift_step,
|
|
53
|
+
)
|
|
54
|
+
from .benchmark import (
|
|
55
|
+
dsg_agrawal,
|
|
56
|
+
dsg_drift,
|
|
57
|
+
dsg_mixed,
|
|
58
|
+
dsg_mmd_test,
|
|
59
|
+
dsg_sea,
|
|
60
|
+
dsg_sine,
|
|
61
|
+
dsg_source,
|
|
62
|
+
dsg_source_data,
|
|
63
|
+
dsg_source_regions,
|
|
64
|
+
dsg_stream,
|
|
65
|
+
dsg_take,
|
|
66
|
+
)
|
|
67
|
+
from .detectors import (
|
|
68
|
+
IKS,
|
|
69
|
+
DfrAdwin,
|
|
70
|
+
DfrAedd,
|
|
71
|
+
DfrCosine,
|
|
72
|
+
DfrCusum,
|
|
73
|
+
DfrDde,
|
|
74
|
+
DfrDdm,
|
|
75
|
+
DfrEcdd,
|
|
76
|
+
DfrEddm,
|
|
77
|
+
DfrEikmeans,
|
|
78
|
+
DfrEnsemble,
|
|
79
|
+
DfrFastlr,
|
|
80
|
+
DfrGreedyks,
|
|
81
|
+
DfrHddm,
|
|
82
|
+
DfrIks,
|
|
83
|
+
DfrIndid,
|
|
84
|
+
DfrKldist,
|
|
85
|
+
DfrKswin,
|
|
86
|
+
DfrLbdd,
|
|
87
|
+
DfrLlr2,
|
|
88
|
+
DfrMcd,
|
|
89
|
+
DfrMcdd,
|
|
90
|
+
DfrMmqt,
|
|
91
|
+
DfrOnlinebcp,
|
|
92
|
+
DfrPadd,
|
|
93
|
+
DfrPageHinkley,
|
|
94
|
+
DfrProton,
|
|
95
|
+
DfrPsi,
|
|
96
|
+
DfrQts,
|
|
97
|
+
DfrStudd,
|
|
98
|
+
DfrWwAggr,
|
|
99
|
+
GreedyKS,
|
|
100
|
+
cosine_score,
|
|
101
|
+
cpd_calibrate,
|
|
102
|
+
cpd_ensemble,
|
|
103
|
+
cpd_ensemble_fit,
|
|
104
|
+
cpd_scores,
|
|
105
|
+
dde_curve,
|
|
106
|
+
dde_feature_drift,
|
|
107
|
+
dde_score,
|
|
108
|
+
eikmeans,
|
|
109
|
+
eikmeans_test,
|
|
110
|
+
ensemble_vote,
|
|
111
|
+
fastlr_split,
|
|
112
|
+
iks_ca,
|
|
113
|
+
indid,
|
|
114
|
+
indid_predict,
|
|
115
|
+
ks_sf,
|
|
116
|
+
mmqt,
|
|
117
|
+
mmqt_test,
|
|
118
|
+
online_bcp,
|
|
119
|
+
psi,
|
|
120
|
+
spbn,
|
|
121
|
+
spbn_loglik,
|
|
122
|
+
ts2vec,
|
|
123
|
+
tscp2,
|
|
124
|
+
wwaggr,
|
|
125
|
+
)
|
|
126
|
+
from .memory import MemoryBasic, MemoryManager, MemoryOversampling, MemoryUndersampling
|
|
127
|
+
from .metrics import (
|
|
128
|
+
Metric,
|
|
129
|
+
MtAccuracy,
|
|
130
|
+
MtFscore,
|
|
131
|
+
MtPrecision,
|
|
132
|
+
MtRecall,
|
|
133
|
+
MtRocauc,
|
|
134
|
+
cm_metrics,
|
|
135
|
+
f1_aggregate,
|
|
136
|
+
)
|
|
137
|
+
from .norm import NrmBase, NrmMemory
|
|
138
|
+
from .transforms import OneHot, TransPipeline
|
|
139
|
+
|
|
140
|
+
__version__ = "1.0.707"
|
|
141
|
+
|
|
142
|
+
__all__ = [
|
|
143
|
+
"IKS",
|
|
144
|
+
"AdpRecurrent",
|
|
145
|
+
"AdpRetrain",
|
|
146
|
+
"Concept",
|
|
147
|
+
"ConceptPool",
|
|
148
|
+
"ConceptPoolInactive",
|
|
149
|
+
"ConceptRanker",
|
|
150
|
+
"DfrAdwin",
|
|
151
|
+
"DfrAedd",
|
|
152
|
+
"DfrCosine",
|
|
153
|
+
"DfrCusum",
|
|
154
|
+
"DfrDde",
|
|
155
|
+
"DfrDdm",
|
|
156
|
+
"DfrEcdd",
|
|
157
|
+
"DfrEddm",
|
|
158
|
+
"DfrEikmeans",
|
|
159
|
+
"DfrEnsemble",
|
|
160
|
+
"DfrFastlr",
|
|
161
|
+
"DfrGreedyks",
|
|
162
|
+
"DfrHddm",
|
|
163
|
+
"DfrIks",
|
|
164
|
+
"DfrInactive",
|
|
165
|
+
"DfrIndid",
|
|
166
|
+
"DfrKldist",
|
|
167
|
+
"DfrKswin",
|
|
168
|
+
"DfrLbdd",
|
|
169
|
+
"DfrLlr2",
|
|
170
|
+
"DfrMcd",
|
|
171
|
+
"DfrMcdd",
|
|
172
|
+
"DfrMmqt",
|
|
173
|
+
"DfrMultiCriteria",
|
|
174
|
+
"DfrOnlinebcp",
|
|
175
|
+
"DfrPadd",
|
|
176
|
+
"DfrPageHinkley",
|
|
177
|
+
"DfrPassive",
|
|
178
|
+
"DfrProton",
|
|
179
|
+
"DfrPsi",
|
|
180
|
+
"DfrQts",
|
|
181
|
+
"DfrStudd",
|
|
182
|
+
"DfrWwAggr",
|
|
183
|
+
"DistBased",
|
|
184
|
+
"DriftWorkflow",
|
|
185
|
+
"Drifter",
|
|
186
|
+
"Dummy",
|
|
187
|
+
"ErrorBased",
|
|
188
|
+
"Evictor",
|
|
189
|
+
"EvtLeastUsed",
|
|
190
|
+
"EvtRedundant",
|
|
191
|
+
"GreedyKS",
|
|
192
|
+
"LearnedLimit",
|
|
193
|
+
"MemoryBasic",
|
|
194
|
+
"MemoryManager",
|
|
195
|
+
"MemoryOversampling",
|
|
196
|
+
"MemoryUndersampling",
|
|
197
|
+
"Metric",
|
|
198
|
+
"ModelTrainer",
|
|
199
|
+
"MtAccuracy",
|
|
200
|
+
"MtFscore",
|
|
201
|
+
"MtPrecision",
|
|
202
|
+
"MtRecall",
|
|
203
|
+
"MtRocauc",
|
|
204
|
+
"MvDistBased",
|
|
205
|
+
"NrmBase",
|
|
206
|
+
"NrmMemory",
|
|
207
|
+
"OneHot",
|
|
208
|
+
"RankPsi",
|
|
209
|
+
"RankRatio",
|
|
210
|
+
"RareDrop",
|
|
211
|
+
"RareKeep",
|
|
212
|
+
"RarePolicy",
|
|
213
|
+
"RecAlways",
|
|
214
|
+
"RecStable",
|
|
215
|
+
"RecordPolicy",
|
|
216
|
+
"Selector",
|
|
217
|
+
"SlctAe",
|
|
218
|
+
"SlctErrorMetrics",
|
|
219
|
+
"SlctInactive",
|
|
220
|
+
"SlctPsi",
|
|
221
|
+
"SlctPsiThenBest",
|
|
222
|
+
"SlctPsiThenError",
|
|
223
|
+
"TrainIncremental",
|
|
224
|
+
"TrainRetrain",
|
|
225
|
+
"TrainStatic",
|
|
226
|
+
"TransPipeline",
|
|
227
|
+
"__version__",
|
|
228
|
+
"adapt_incremental",
|
|
229
|
+
"adapt_reset",
|
|
230
|
+
"adapt_retrain",
|
|
231
|
+
"adapt_static",
|
|
232
|
+
"benchmark",
|
|
233
|
+
"cm_metrics",
|
|
234
|
+
"cosine_score",
|
|
235
|
+
"cpd_calibrate",
|
|
236
|
+
"cpd_ensemble",
|
|
237
|
+
"cpd_ensemble_fit",
|
|
238
|
+
"cpd_scores",
|
|
239
|
+
"datasets",
|
|
240
|
+
"dde_curve",
|
|
241
|
+
"dde_feature_drift",
|
|
242
|
+
"dde_score",
|
|
243
|
+
"drift_step",
|
|
244
|
+
"dsg_agrawal",
|
|
245
|
+
"dsg_drift",
|
|
246
|
+
"dsg_mixed",
|
|
247
|
+
"dsg_mmd_test",
|
|
248
|
+
"dsg_sea",
|
|
249
|
+
"dsg_sine",
|
|
250
|
+
"dsg_source",
|
|
251
|
+
"dsg_source_data",
|
|
252
|
+
"dsg_source_regions",
|
|
253
|
+
"dsg_stream",
|
|
254
|
+
"dsg_take",
|
|
255
|
+
"eikmeans",
|
|
256
|
+
"eikmeans_test",
|
|
257
|
+
"ensemble_vote",
|
|
258
|
+
"f1_aggregate",
|
|
259
|
+
"fastlr_split",
|
|
260
|
+
"iks_ca",
|
|
261
|
+
"indid",
|
|
262
|
+
"indid_predict",
|
|
263
|
+
"ks_sf",
|
|
264
|
+
"mmqt",
|
|
265
|
+
"mmqt_test",
|
|
266
|
+
"online_bcp",
|
|
267
|
+
"psi",
|
|
268
|
+
"recurrent_ensemble",
|
|
269
|
+
"recurrent_incremental",
|
|
270
|
+
"spbn",
|
|
271
|
+
"spbn_loglik",
|
|
272
|
+
"ts2vec",
|
|
273
|
+
"tscp2",
|
|
274
|
+
"wwaggr",
|
|
275
|
+
]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Drift-adaptive model workflows (``AdpRetrain`` and ``AdpRecurrent``)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .concept import (
|
|
5
|
+
Concept,
|
|
6
|
+
ConceptPool,
|
|
7
|
+
ConceptPoolInactive,
|
|
8
|
+
ModelTrainer,
|
|
9
|
+
TrainIncremental,
|
|
10
|
+
TrainRetrain,
|
|
11
|
+
TrainStatic,
|
|
12
|
+
)
|
|
13
|
+
from .policy import (
|
|
14
|
+
LearnedLimit,
|
|
15
|
+
RareDrop,
|
|
16
|
+
RareKeep,
|
|
17
|
+
RarePolicy,
|
|
18
|
+
RecAlways,
|
|
19
|
+
RecordPolicy,
|
|
20
|
+
RecStable,
|
|
21
|
+
)
|
|
22
|
+
from .recurrent import (
|
|
23
|
+
AdpRecurrent,
|
|
24
|
+
adapt_incremental,
|
|
25
|
+
adapt_reset,
|
|
26
|
+
adapt_retrain,
|
|
27
|
+
adapt_static,
|
|
28
|
+
recurrent_ensemble,
|
|
29
|
+
recurrent_incremental,
|
|
30
|
+
)
|
|
31
|
+
from .retrain import AdpRetrain
|
|
32
|
+
from .selectors import (
|
|
33
|
+
ConceptRanker,
|
|
34
|
+
Evictor,
|
|
35
|
+
EvtLeastUsed,
|
|
36
|
+
EvtRedundant,
|
|
37
|
+
RankPsi,
|
|
38
|
+
RankRatio,
|
|
39
|
+
Selector,
|
|
40
|
+
SlctAe,
|
|
41
|
+
SlctErrorMetrics,
|
|
42
|
+
SlctInactive,
|
|
43
|
+
SlctPsi,
|
|
44
|
+
SlctPsiThenBest,
|
|
45
|
+
SlctPsiThenError,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
__all__ = [
|
|
49
|
+
"AdpRecurrent",
|
|
50
|
+
"AdpRetrain",
|
|
51
|
+
"Concept",
|
|
52
|
+
"ConceptPool",
|
|
53
|
+
"ConceptPoolInactive",
|
|
54
|
+
"ConceptRanker",
|
|
55
|
+
"Evictor",
|
|
56
|
+
"EvtLeastUsed",
|
|
57
|
+
"EvtRedundant",
|
|
58
|
+
"LearnedLimit",
|
|
59
|
+
"ModelTrainer",
|
|
60
|
+
"RankPsi",
|
|
61
|
+
"RankRatio",
|
|
62
|
+
"RareDrop",
|
|
63
|
+
"RareKeep",
|
|
64
|
+
"RarePolicy",
|
|
65
|
+
"RecAlways",
|
|
66
|
+
"RecStable",
|
|
67
|
+
"RecordPolicy",
|
|
68
|
+
"Selector",
|
|
69
|
+
"SlctAe",
|
|
70
|
+
"SlctErrorMetrics",
|
|
71
|
+
"SlctInactive",
|
|
72
|
+
"SlctPsi",
|
|
73
|
+
"SlctPsiThenBest",
|
|
74
|
+
"SlctPsiThenError",
|
|
75
|
+
"TrainIncremental",
|
|
76
|
+
"TrainRetrain",
|
|
77
|
+
"TrainStatic",
|
|
78
|
+
"adapt_incremental",
|
|
79
|
+
"adapt_reset",
|
|
80
|
+
"adapt_retrain",
|
|
81
|
+
"adapt_static",
|
|
82
|
+
"recurrent_ensemble",
|
|
83
|
+
"recurrent_incremental",
|
|
84
|
+
]
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Concept representation, trainers, and concept pool for recurrent drift adaptation.
|
|
2
|
+
|
|
3
|
+
Mirrors ``ac_remind.R`` (``new_concept``/``project``), ``ac_trainer.R``, and
|
|
4
|
+
``ac_manager.R`` from the R ``heimdall`` package.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import copy
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pandas as pd
|
|
13
|
+
from pydaltoolbox import DalBase
|
|
14
|
+
|
|
15
|
+
from ..memory import MemoryBasic, MemoryManager
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"Concept",
|
|
19
|
+
"ConceptPool",
|
|
20
|
+
"ConceptPoolInactive",
|
|
21
|
+
"ModelTrainer",
|
|
22
|
+
"TrainIncremental",
|
|
23
|
+
"TrainRetrain",
|
|
24
|
+
"TrainStatic",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Concept:
|
|
29
|
+
"""A concept learned for one regime in ``AdpRecurrent``.
|
|
30
|
+
|
|
31
|
+
Holds the fitted ``model``, preprocessing ``pipeline``, data ``memory``
|
|
32
|
+
window, decision threshold ``th``, learned-limit ``history``, selector
|
|
33
|
+
``cache``, ``uid``, pool ``slot`` (``-1`` = not in pool), and ``version``.
|
|
34
|
+
|
|
35
|
+
Porting:
|
|
36
|
+
Mirrors ``ac_remind.R`` (``new_concept`` / ``project.concept``). Fidelity: exact.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(self, memory: MemoryManager | None = None) -> None:
|
|
40
|
+
self.model: Any = None
|
|
41
|
+
self.uid: int | None = None
|
|
42
|
+
self.memory: MemoryManager = copy.deepcopy(memory) if memory is not None else MemoryBasic()
|
|
43
|
+
self.qty: int = 0
|
|
44
|
+
self.slot: int = -1
|
|
45
|
+
self.pipeline: Any = None
|
|
46
|
+
self.history: dict[str, list[float]] = {}
|
|
47
|
+
self.cache: dict[str, Any] = {}
|
|
48
|
+
self.version: dict[str, int] = {"data": 0, "model": 0}
|
|
49
|
+
self.th: float = 0.5
|
|
50
|
+
self.th_version: dict[str, int] | None = None
|
|
51
|
+
|
|
52
|
+
def project(self, data: pd.DataFrame) -> pd.DataFrame:
|
|
53
|
+
"""Project ``data`` into this concept's model input space."""
|
|
54
|
+
return self.pipeline.transform(data)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def push_window(
|
|
58
|
+
win: dict[str, pd.DataFrame | None],
|
|
59
|
+
x: pd.DataFrame,
|
|
60
|
+
y: pd.DataFrame,
|
|
61
|
+
train_size: int,
|
|
62
|
+
) -> dict[str, pd.DataFrame]:
|
|
63
|
+
"""Append a batch to a sliding window of at most ``train_size`` rows."""
|
|
64
|
+
prev_x = win.get("x")
|
|
65
|
+
prev_y = win.get("y")
|
|
66
|
+
new_x = x.reset_index(drop=True) if (prev_x is None or len(prev_x) == 0) else pd.concat(
|
|
67
|
+
[prev_x, x], ignore_index=True
|
|
68
|
+
)
|
|
69
|
+
new_y = y.reset_index(drop=True) if (prev_y is None or len(prev_y) == 0) else pd.concat(
|
|
70
|
+
[prev_y, y], ignore_index=True
|
|
71
|
+
)
|
|
72
|
+
if len(new_x) > train_size:
|
|
73
|
+
new_x = new_x.iloc[-train_size:].reset_index(drop=True)
|
|
74
|
+
new_y = new_y.iloc[-train_size:].reset_index(drop=True)
|
|
75
|
+
return {"x": new_x, "y": new_y}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def advance_window(
|
|
79
|
+
concept: Concept,
|
|
80
|
+
x: pd.DataFrame,
|
|
81
|
+
y: pd.DataFrame,
|
|
82
|
+
rsrc: dict[str, Any],
|
|
83
|
+
) -> Concept:
|
|
84
|
+
"""Slide a concept's data window and refit its memory."""
|
|
85
|
+
win = push_window({"x": concept.memory.X, "y": concept.memory.y}, x, y, rsrc["train_size"])
|
|
86
|
+
mem = copy.deepcopy(rsrc["memory"])
|
|
87
|
+
mem.fit(win["x"], win["y"])
|
|
88
|
+
concept.memory = mem
|
|
89
|
+
concept.version["data"] += 1
|
|
90
|
+
return concept
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _prepare_target_for_model(y_df: pd.DataFrame, model: Any) -> pd.DataFrame:
|
|
94
|
+
out = y_df.copy().reset_index(drop=True)
|
|
95
|
+
col = out.columns[0]
|
|
96
|
+
if pd.api.types.is_bool_dtype(out[col]):
|
|
97
|
+
slevels = getattr(model, "slevels", None)
|
|
98
|
+
if slevels is not None and len(slevels) == 2 and all(isinstance(s, str) for s in slevels):
|
|
99
|
+
out[col] = np.where(out[col].to_numpy(dtype=bool), slevels[1], slevels[0])
|
|
100
|
+
else:
|
|
101
|
+
out[col] = out[col].astype(str)
|
|
102
|
+
if slevels is not None and any(isinstance(s, bool) for s in slevels):
|
|
103
|
+
model.slevels = [str(s) for s in slevels]
|
|
104
|
+
return out
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def full_train(
|
|
108
|
+
concept: Concept,
|
|
109
|
+
mem: MemoryManager,
|
|
110
|
+
rsrc: dict[str, Any],
|
|
111
|
+
) -> dict[str, Any]:
|
|
112
|
+
"""Fit preprocessing, balance projected features, and fit the concept's model."""
|
|
113
|
+
pipeline = copy.deepcopy(rsrc["preprocess"]).fit(mem.X)
|
|
114
|
+
concept.pipeline = pipeline
|
|
115
|
+
xp = pipeline.transform(mem.X)
|
|
116
|
+
balanced = rsrc["memory"].memory_balance(xp, mem.y)
|
|
117
|
+
if len(balanced["X"]) < rsrc["warmup_size"]:
|
|
118
|
+
return {"concept": concept, "trained": False}
|
|
119
|
+
model_copy = copy.deepcopy(rsrc["method"])
|
|
120
|
+
y_fit = _prepare_target_for_model(balanced["y"], model_copy)
|
|
121
|
+
train_df = pd.concat(
|
|
122
|
+
[balanced["X"].reset_index(drop=True), y_fit],
|
|
123
|
+
axis=1,
|
|
124
|
+
)
|
|
125
|
+
concept.model = model_copy.fit(train_df)
|
|
126
|
+
return {"concept": concept, "trained": True}
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
class ModelTrainer(DalBase):
|
|
130
|
+
"""Base class for model-training activities on an existing concept.
|
|
131
|
+
|
|
132
|
+
Porting:
|
|
133
|
+
Mirrors ``ac_trainer.R`` (``model_trainer``). Fidelity: exact.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
def advance_concept(
|
|
137
|
+
self,
|
|
138
|
+
concept: Concept,
|
|
139
|
+
x: pd.DataFrame,
|
|
140
|
+
y: pd.DataFrame,
|
|
141
|
+
usable: bool,
|
|
142
|
+
rsrc: dict[str, Any],
|
|
143
|
+
) -> dict[str, Any]:
|
|
144
|
+
raise NotImplementedError
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class TrainStatic(ModelTrainer):
|
|
148
|
+
"""Frozen concept trainer: neither memory nor model change after initial training.
|
|
149
|
+
|
|
150
|
+
Porting:
|
|
151
|
+
Mirrors ``ac_trainer.R`` (``train_static``). Fidelity: exact.
|
|
152
|
+
"""
|
|
153
|
+
|
|
154
|
+
def advance_concept(
|
|
155
|
+
self,
|
|
156
|
+
concept: Concept,
|
|
157
|
+
x: pd.DataFrame,
|
|
158
|
+
y: pd.DataFrame,
|
|
159
|
+
usable: bool,
|
|
160
|
+
rsrc: dict[str, Any],
|
|
161
|
+
) -> dict[str, Any]:
|
|
162
|
+
return {"concept": concept, "trained": False}
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class TrainRetrain(ModelTrainer):
|
|
166
|
+
"""Slides the concept window and retrains the model from scratch on each batch.
|
|
167
|
+
|
|
168
|
+
Porting:
|
|
169
|
+
Mirrors ``ac_trainer.R`` (``train_retrain``). Fidelity: exact.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
def advance_concept(
|
|
173
|
+
self,
|
|
174
|
+
concept: Concept,
|
|
175
|
+
x: pd.DataFrame,
|
|
176
|
+
y: pd.DataFrame,
|
|
177
|
+
usable: bool,
|
|
178
|
+
rsrc: dict[str, Any],
|
|
179
|
+
) -> dict[str, Any]:
|
|
180
|
+
concept = advance_window(concept, x, y, rsrc)
|
|
181
|
+
ft = full_train(concept, concept.memory, rsrc)
|
|
182
|
+
concept = ft["concept"]
|
|
183
|
+
if ft["trained"]:
|
|
184
|
+
concept.version["model"] += 1
|
|
185
|
+
return {"concept": concept, "trained": ft["trained"]}
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class TrainIncremental(ModelTrainer):
|
|
189
|
+
"""Slides the concept window and updates the existing model with the current batch only.
|
|
190
|
+
|
|
191
|
+
Porting:
|
|
192
|
+
Mirrors ``ac_trainer.R`` (``train_incremental``). Fidelity: exact.
|
|
193
|
+
"""
|
|
194
|
+
|
|
195
|
+
def __init__(self, epochs: int | None = None) -> None:
|
|
196
|
+
if epochs is not None and (isinstance(epochs, bool) or not isinstance(epochs, (int, float)) or epochs < 1):
|
|
197
|
+
raise ValueError("epochs must be None or a single number >= 1")
|
|
198
|
+
self.epochs: int | None = int(epochs) if epochs is not None else None
|
|
199
|
+
|
|
200
|
+
def advance_concept(
|
|
201
|
+
self,
|
|
202
|
+
concept: Concept,
|
|
203
|
+
x: pd.DataFrame,
|
|
204
|
+
y: pd.DataFrame,
|
|
205
|
+
usable: bool,
|
|
206
|
+
rsrc: dict[str, Any],
|
|
207
|
+
) -> dict[str, Any]:
|
|
208
|
+
concept = advance_window(concept, x, y, rsrc)
|
|
209
|
+
if not usable:
|
|
210
|
+
return {"concept": concept, "trained": False}
|
|
211
|
+
model = concept.model
|
|
212
|
+
if self.epochs is not None and hasattr(model, "epochs"):
|
|
213
|
+
model.epochs = self.epochs
|
|
214
|
+
y_fit = _prepare_target_for_model(y, model)
|
|
215
|
+
batch_df = pd.concat(
|
|
216
|
+
[concept.project(x).reset_index(drop=True), y_fit],
|
|
217
|
+
axis=1,
|
|
218
|
+
)
|
|
219
|
+
concept.model = model.fit(batch_df)
|
|
220
|
+
concept.version["model"] += 1
|
|
221
|
+
return {"concept": concept, "trained": True}
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
class ConceptPool(DalBase):
|
|
225
|
+
"""Stores concepts in fixed slots and selects/evicts them across recurring regimes.
|
|
226
|
+
|
|
227
|
+
Porting:
|
|
228
|
+
Mirrors ``ac_manager.R`` (``concept_pool``). Fidelity: exact.
|
|
229
|
+
"""
|
|
230
|
+
|
|
231
|
+
def __init__(
|
|
232
|
+
self,
|
|
233
|
+
model_selector: Any,
|
|
234
|
+
model_deleter: Any,
|
|
235
|
+
n_slots: int = 1,
|
|
236
|
+
history_order: str = "before",
|
|
237
|
+
history_init: str = "none",
|
|
238
|
+
) -> None:
|
|
239
|
+
if history_order not in ("before", "after"):
|
|
240
|
+
raise ValueError(f"history_order must be 'before' or 'after', got '{history_order}'")
|
|
241
|
+
if history_init not in ("none", "blocks"):
|
|
242
|
+
raise ValueError(f"history_init must be 'none' or 'blocks', got '{history_init}'")
|
|
243
|
+
if history_order == "after" and history_init == "none":
|
|
244
|
+
raise ValueError("history_order = 'after' requires history_init = 'blocks'")
|
|
245
|
+
|
|
246
|
+
self.model_selector = model_selector
|
|
247
|
+
self.model_deleter = model_deleter
|
|
248
|
+
self.n_slots: int = int(n_slots)
|
|
249
|
+
self.history_order: str = history_order
|
|
250
|
+
self.history_init: str = history_init
|
|
251
|
+
self.concept_storage: list[Concept] = [Concept() for _ in range(self.n_slots)]
|
|
252
|
+
|
|
253
|
+
def add_concept(self, concept: Concept) -> ConceptPool:
|
|
254
|
+
slot = concept.slot
|
|
255
|
+
if slot < 0:
|
|
256
|
+
empty = [i for i, cn in enumerate(self.concept_storage) if cn.qty == 0]
|
|
257
|
+
slot = empty[0] if empty else self.model_deleter.evict(self.concept_storage)
|
|
258
|
+
concept.slot = -1
|
|
259
|
+
self.concept_storage[slot] = concept
|
|
260
|
+
return self
|
|
261
|
+
|
|
262
|
+
def check_concept(self, X: pd.DataFrame, y: pd.DataFrame) -> dict[str, Any]:
|
|
263
|
+
valid = [i for i, cn in enumerate(self.concept_storage) if cn.qty > 0]
|
|
264
|
+
if not valid:
|
|
265
|
+
return {"mm": self, "sc": None}
|
|
266
|
+
sel = self.model_selector.select_model(self.concept_storage, valid, X, y)
|
|
267
|
+
self.concept_storage = sel["cl"]
|
|
268
|
+
if sel["sc"] is None:
|
|
269
|
+
return {"mm": self, "sc": None}
|
|
270
|
+
chosen = self.concept_storage[sel["sc"]]
|
|
271
|
+
chosen.slot = sel["sc"]
|
|
272
|
+
return {"mm": self, "sc": chosen}
|
|
273
|
+
|
|
274
|
+
def update_concept(
|
|
275
|
+
self,
|
|
276
|
+
concept: Concept,
|
|
277
|
+
X: pd.DataFrame,
|
|
278
|
+
y: pd.DataFrame,
|
|
279
|
+
stage: str = "before",
|
|
280
|
+
record: bool = True,
|
|
281
|
+
**kwargs: Any,
|
|
282
|
+
) -> Concept:
|
|
283
|
+
if self.model_selector is None:
|
|
284
|
+
return concept
|
|
285
|
+
before = self.history_order == "before"
|
|
286
|
+
if stage == "before":
|
|
287
|
+
return self.model_selector.update_concept(
|
|
288
|
+
concept, X, y, phase="observe", record=record and before, **kwargs
|
|
289
|
+
)
|
|
290
|
+
if not before and record and concept.model is not None:
|
|
291
|
+
concept = self.model_selector.update_concept(
|
|
292
|
+
concept, X, y, phase="observe", record=True, **kwargs
|
|
293
|
+
)
|
|
294
|
+
return self.model_selector.update_concept(concept, X, y, phase="adapt", **kwargs)
|
|
295
|
+
|
|
296
|
+
def init_history(self, concept: Concept, block_size: int, **kwargs: Any) -> Concept:
|
|
297
|
+
if self.history_init != "blocks" or self.model_selector is None:
|
|
298
|
+
return concept
|
|
299
|
+
return self.model_selector.init_history(concept, block_size, **kwargs)
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class ConceptPoolInactive(ConceptPool):
|
|
303
|
+
"""Inactive concept pool that never stores or reuses concepts.
|
|
304
|
+
|
|
305
|
+
Porting:
|
|
306
|
+
Mirrors ``ac_manager.R`` (``concept_pool_inactive``). Fidelity: exact.
|
|
307
|
+
"""
|
|
308
|
+
|
|
309
|
+
def __init__(self) -> None:
|
|
310
|
+
super().__init__(model_selector=None, model_deleter=None, n_slots=1)
|
|
311
|
+
|
|
312
|
+
def add_concept(self, concept: Concept) -> ConceptPoolInactive:
|
|
313
|
+
return self
|
|
314
|
+
|
|
315
|
+
def check_concept(self, X: pd.DataFrame, y: pd.DataFrame) -> dict[str, Any]:
|
|
316
|
+
return {"mm": self, "sc": None}
|