pydaltoolboxdp 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.
@@ -0,0 +1,18 @@
1
+ """Deep ++ extensions for the Python DAL ecosystem.
2
+
3
+ The package owns the Python implementations consumed directly in Python and through
4
+ the sibling R package ``daltoolboxdp`` via ``reticulate``.
5
+ """
6
+
7
+ from .autoencoder import AutoencDenoiseE, AutoencDenoiseEd, AutoencE, AutoencEd
8
+ from .convolutional import AutoencConvE, AutoencConvEd
9
+
10
+ __all__ = [
11
+ "AutoencConvE",
12
+ "AutoencConvEd",
13
+ "AutoencDenoiseE",
14
+ "AutoencDenoiseEd",
15
+ "AutoencE",
16
+ "AutoencEd",
17
+ ]
18
+ __version__ = "0.1.0"
@@ -0,0 +1,171 @@
1
+ """Shared PyTorch training primitives used by Deep ++ models."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+
8
+ import numpy as np
9
+ from scipy.stats import ttest_ind
10
+ from torch import nn
11
+
12
+ VALIDATION_STRATEGIES = {"static", "dynamic"}
13
+ STOPPING_RULES = {"none", "patience", "sma", "ema", "h"}
14
+
15
+
16
+ @dataclass
17
+ class TrainingConfig:
18
+ batch_size: int = 1
19
+ epochs: int = 100
20
+ learning_rate: float = 0.001
21
+ validation_strategy: str = "static"
22
+ stopping_rule: str = "none"
23
+ val_ratio: float = 0.33
24
+ patience: int = 3
25
+ min_delta: float = 0.0
26
+ sma_window: int = 30
27
+ ema_alpha: float = 0.2
28
+ test_window: int = 30
29
+ p_value: float = 0.05
30
+ reshuffle_freq: int = 1
31
+
32
+
33
+ def int_list(
34
+ values,
35
+ default: Sequence[int] | None = None,
36
+ *,
37
+ allow_empty: bool = False,
38
+ ) -> list[int]:
39
+ """Normalize an integer or integer sequence into a list."""
40
+ if values is None:
41
+ values = default if default is not None else []
42
+ if isinstance(values, (int, np.integer)):
43
+ values = [int(values)]
44
+ result = [int(value) for value in values]
45
+ if not allow_empty and not result:
46
+ raise ValueError("at least one integer value is required")
47
+ if any(value <= 0 for value in result):
48
+ raise ValueError("layer sizes must be positive integers")
49
+ return result
50
+
51
+
52
+ def activation(name: str, negative_slope: float = 0.01) -> nn.Module:
53
+ """Build one of the activation modules supported by the R interface."""
54
+ name = str(name).lower()
55
+ modules = {
56
+ "relu": lambda: nn.ReLU(inplace=True),
57
+ "leaky_relu": lambda: nn.LeakyReLU(float(negative_slope), inplace=True),
58
+ "elu": lambda: nn.ELU(inplace=True),
59
+ "gelu": nn.GELU,
60
+ "selu": lambda: nn.SELU(inplace=True),
61
+ "tanh": nn.Tanh,
62
+ "sigmoid": nn.Sigmoid,
63
+ "softplus": nn.Softplus,
64
+ "identity": nn.Identity,
65
+ "none": nn.Identity,
66
+ }
67
+ try:
68
+ return modules[name]()
69
+ except KeyError as error:
70
+ raise ValueError(f"unsupported activation: {name}") from error
71
+
72
+
73
+ def dense_stack(
74
+ input_dim: int,
75
+ hidden_sizes,
76
+ output_dim: int,
77
+ *,
78
+ hidden_activation: str = "relu",
79
+ output_activation: str = "none",
80
+ negative_slope: float = 0.01,
81
+ ) -> nn.Sequential:
82
+ layers: list[nn.Module] = []
83
+ previous = int(input_dim)
84
+ for hidden_size in int_list(hidden_sizes, allow_empty=True):
85
+ layers.append(nn.Linear(previous, hidden_size))
86
+ layers.append(activation(hidden_activation, negative_slope))
87
+ previous = hidden_size
88
+ layers.append(nn.Linear(previous, int(output_dim)))
89
+ if output_activation.lower() not in {"none", "identity"}:
90
+ layers.append(activation(output_activation, negative_slope))
91
+ return nn.Sequential(*layers)
92
+
93
+
94
+ def validate_training_options(validation_strategy: str, stopping_rule: str) -> tuple[str, str]:
95
+ validation_strategy = str(validation_strategy).lower()
96
+ stopping_rule = str(stopping_rule).lower()
97
+ if validation_strategy not in VALIDATION_STRATEGIES:
98
+ raise ValueError(
99
+ f"validation_strategy must be one of {sorted(VALIDATION_STRATEGIES)}"
100
+ )
101
+ if stopping_rule not in STOPPING_RULES:
102
+ raise ValueError(f"stopping_rule must be one of {sorted(STOPPING_RULES)}")
103
+ return validation_strategy, stopping_rule
104
+
105
+
106
+ class StopController:
107
+ """Apply the stopping rules exposed by the original Deep ++ R API."""
108
+
109
+ def __init__(self, config: TrainingConfig) -> None:
110
+ self.rule = config.stopping_rule
111
+ self.min_delta = float(config.min_delta)
112
+ self.patience = int(config.patience)
113
+ self.sma_window = max(1, int(config.sma_window))
114
+ self.ema_alpha = float(config.ema_alpha)
115
+ self.test_window = max(2, int(config.test_window))
116
+ self.p_value = float(config.p_value)
117
+ self.best_value = float("inf")
118
+ self.best_state = None
119
+ self.patience_counter = 0
120
+ self.ema_value = None
121
+ self.history: list[float] = []
122
+
123
+ @staticmethod
124
+ def _clone_state(model: nn.Module) -> dict:
125
+ return {key: value.detach().clone() for key, value in model.state_dict().items()}
126
+
127
+ def _h_improved(self) -> bool:
128
+ if len(self.history) < 2 * self.test_window:
129
+ return len(self.history) == 1 or self.history[-1] < min(self.history[:-1])
130
+ previous = self.history[-2 * self.test_window : -self.test_window]
131
+ recent = self.history[-self.test_window :]
132
+ _, p_value = ttest_ind(previous, recent, equal_var=False, alternative="greater")
133
+ return bool(p_value < self.p_value)
134
+
135
+ def step(self, model: nn.Module, current: float) -> bool:
136
+ self.history.append(float(current))
137
+ if self.rule == "none":
138
+ self.best_state = self._clone_state(model)
139
+ return False
140
+ if self.rule == "h":
141
+ improved = self._h_improved()
142
+ if improved:
143
+ self.best_state = self._clone_state(model)
144
+ self.patience_counter = 0
145
+ else:
146
+ self.patience_counter += 1
147
+ return self.patience_counter > self.patience
148
+
149
+ if self.rule == "patience":
150
+ monitored = float(current)
151
+ elif self.rule == "sma":
152
+ monitored = float(np.mean(self.history[-self.sma_window :]))
153
+ elif self.rule == "ema":
154
+ if self.ema_value is None:
155
+ self.ema_value = float(current)
156
+ else:
157
+ self.ema_value = (
158
+ self.ema_alpha * float(current)
159
+ + (1.0 - self.ema_alpha) * self.ema_value
160
+ )
161
+ monitored = self.ema_value
162
+ else: # validated at construction; defensive for mutated configs
163
+ raise ValueError(f"unsupported stopping rule: {self.rule}")
164
+
165
+ if self.best_value - monitored > self.min_delta:
166
+ self.best_value = monitored
167
+ self.best_state = self._clone_state(model)
168
+ self.patience_counter = 0
169
+ else:
170
+ self.patience_counter += 1
171
+ return self.patience_counter > self.patience
@@ -0,0 +1,428 @@
1
+ """Dense Deep ++ autoencoders.
2
+
3
+ This module adapts the PyTorch implementation formerly embedded in
4
+ ``daltoolboxdp/inst/python`` into public classes that follow the
5
+ ``pydaltoolbox`` transformation contract.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+ import torch
13
+ from pydaltoolbox import AutoencBaseE, AutoencBaseEd
14
+ from torch import nn
15
+ from torch.utils.data import DataLoader, TensorDataset
16
+
17
+ from ._training import (
18
+ StopController,
19
+ TrainingConfig,
20
+ dense_stack,
21
+ int_list,
22
+ validate_training_options,
23
+ )
24
+
25
+ __all__ = ["AutoencE", "AutoencEd"]
26
+
27
+
28
+ class _DenseNetwork(nn.Module):
29
+ def __init__(
30
+ self,
31
+ input_size: int,
32
+ encoding_size: int,
33
+ encoder_hidden_sizes,
34
+ decoder_hidden_sizes,
35
+ activation: str,
36
+ output_activation: str,
37
+ negative_slope: float,
38
+ ) -> None:
39
+ super().__init__()
40
+ self.encoder = dense_stack(
41
+ input_size,
42
+ encoder_hidden_sizes,
43
+ encoding_size,
44
+ hidden_activation=activation,
45
+ negative_slope=negative_slope,
46
+ )
47
+ self.decoder = dense_stack(
48
+ encoding_size,
49
+ decoder_hidden_sizes,
50
+ input_size,
51
+ hidden_activation=activation,
52
+ output_activation=output_activation,
53
+ negative_slope=negative_slope,
54
+ )
55
+
56
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
57
+ return self.decoder(self.encoder(x))
58
+
59
+
60
+ class _DenseAutoencoderMixin:
61
+ def _initialize(
62
+ self,
63
+ *,
64
+ input_size: int,
65
+ encoding_size: int,
66
+ encoder_hidden_sizes=64,
67
+ decoder_hidden_sizes=None,
68
+ activation: str = "relu",
69
+ output_activation: str = "none",
70
+ batch_size: int = 1,
71
+ epochs: int = 100,
72
+ num_epochs: int | None = None,
73
+ learning_rate: float = 0.001,
74
+ validation_strategy: str = "static",
75
+ stopping_rule: str = "none",
76
+ negative_slope: float = 0.01,
77
+ val_ratio: float = 0.33,
78
+ patience: int = 3,
79
+ min_delta: float = 0.0,
80
+ sma_window: int = 30,
81
+ ema_alpha: float = 0.2,
82
+ test_window: int = 30,
83
+ p_value: float = 0.05,
84
+ reshuffle_freq: int = 1,
85
+ random_state: int | None = None,
86
+ device: str | None = None,
87
+ ) -> None:
88
+ if int(input_size) <= 0 or int(encoding_size) <= 0:
89
+ raise ValueError("input_size and encoding_size must be positive")
90
+ if int(batch_size) <= 0:
91
+ raise ValueError("batch_size must be positive")
92
+ if not 0 < float(val_ratio) < 1:
93
+ raise ValueError("val_ratio must be between 0 and 1")
94
+ validation_strategy, stopping_rule = validate_training_options(
95
+ validation_strategy, stopping_rule
96
+ )
97
+
98
+ self.input_size = int(input_size)
99
+ self.encoding_size = int(encoding_size)
100
+ self.encoder_hidden_sizes = int_list(encoder_hidden_sizes, default=[64])
101
+ self.decoder_hidden_sizes = (
102
+ list(reversed(self.encoder_hidden_sizes))
103
+ if decoder_hidden_sizes is None
104
+ else int_list(decoder_hidden_sizes, allow_empty=True)
105
+ )
106
+ self.activation = str(activation)
107
+ self.output_activation = str(output_activation)
108
+ self.batch_size = int(batch_size)
109
+ self.epochs = int(num_epochs if num_epochs is not None else epochs)
110
+ self.num_epochs = self.epochs
111
+ self.learning_rate = float(learning_rate)
112
+ self.validation_strategy = validation_strategy
113
+ self.stopping_rule = stopping_rule
114
+ self.negative_slope = float(negative_slope)
115
+ self.val_ratio = float(val_ratio)
116
+ self.patience = int(patience)
117
+ self.min_delta = float(min_delta)
118
+ self.sma_window = int(sma_window)
119
+ self.ema_alpha = float(ema_alpha)
120
+ self.test_window = int(test_window)
121
+ self.p_value = float(p_value)
122
+ self.reshuffle_freq = max(1, int(reshuffle_freq))
123
+ self.random_state = random_state
124
+ self.device = device or "cpu"
125
+ self.device_ = torch.device(self.device)
126
+
127
+ self.model = None
128
+ self.train_loss_: list[float] = []
129
+ self.val_loss_: list[float] = []
130
+ self.epochs_done_ = 0
131
+
132
+ def _seed(self) -> None:
133
+ if self.random_state is not None:
134
+ np.random.seed(int(self.random_state))
135
+ torch.manual_seed(int(self.random_state))
136
+ if torch.cuda.is_available():
137
+ torch.cuda.manual_seed_all(int(self.random_state))
138
+
139
+ def _build_model(self) -> None:
140
+ self._seed()
141
+ self.device_ = torch.device(self.device)
142
+ self.model = _DenseNetwork(
143
+ self.input_size,
144
+ self.encoding_size,
145
+ self.encoder_hidden_sizes,
146
+ self.decoder_hidden_sizes,
147
+ self.activation,
148
+ self.output_activation,
149
+ self.negative_slope,
150
+ ).float().to(self.device_)
151
+
152
+ def _array(self, data) -> np.ndarray:
153
+ array = data.to_numpy() if isinstance(data, pd.DataFrame) else np.asarray(data)
154
+ array = np.asarray(array, dtype=np.float32)
155
+ if array.ndim != 2:
156
+ raise ValueError("autoencoder data must be a two-dimensional array")
157
+ if array.shape[1] != self.input_size:
158
+ raise ValueError(
159
+ f"expected {self.input_size} features, received {array.shape[1]}"
160
+ )
161
+ if array.shape[0] == 0:
162
+ raise ValueError("autoencoder data must contain at least one observation")
163
+ if not np.isfinite(array).all():
164
+ raise ValueError("autoencoder data contains non-finite values")
165
+ return array
166
+
167
+ def _loader(self, array: np.ndarray, *, shuffle: bool) -> DataLoader:
168
+ tensor = torch.from_numpy(np.array(array, dtype=np.float32, copy=True))
169
+ return DataLoader(
170
+ TensorDataset(tensor, tensor),
171
+ batch_size=self.batch_size,
172
+ shuffle=shuffle,
173
+ drop_last=False,
174
+ )
175
+
176
+ def _split(self, length: int) -> tuple[np.ndarray, np.ndarray]:
177
+ if length < 2:
178
+ raise ValueError("validation requires at least two observations")
179
+ indices = np.arange(length)
180
+ np.random.shuffle(indices)
181
+ validation_size = min(length - 1, max(1, int(length * self.val_ratio)))
182
+ return indices[validation_size:], indices[:validation_size]
183
+
184
+ def _run_epoch(self, loader: DataLoader, optimizer=None) -> float:
185
+ criterion = nn.MSELoss()
186
+ losses: list[float] = []
187
+ if optimizer is None:
188
+ self.model.eval()
189
+ with torch.no_grad():
190
+ for features, targets in loader:
191
+ features = features.to(self.device_)
192
+ targets = targets.to(self.device_)
193
+ inputs = self._training_inputs(features)
194
+ losses.append(float(criterion(self.model(inputs), targets).item()))
195
+ else:
196
+ self.model.train()
197
+ for features, targets in loader:
198
+ features = features.to(self.device_)
199
+ targets = targets.to(self.device_)
200
+ inputs = self._training_inputs(features)
201
+ optimizer.zero_grad()
202
+ loss = criterion(self.model(inputs), targets)
203
+ loss.backward()
204
+ optimizer.step()
205
+ losses.append(float(loss.item()))
206
+ return float(np.mean(losses)) if losses else 0.0
207
+
208
+ def _training_inputs(self, features: torch.Tensor) -> torch.Tensor:
209
+ """Return the inputs used to optimize against the clean targets."""
210
+ return features
211
+
212
+ def fit(self, data, **kwargs):
213
+ """Train the autoencoder and return ``self``.
214
+
215
+ Training parameters may be overridden for this call. This is needed by adaptive
216
+ consumers such as Waypoint, which retrain an existing model for fewer epochs.
217
+ """
218
+ for name in (
219
+ "batch_size",
220
+ "epochs",
221
+ "learning_rate",
222
+ "validation_strategy",
223
+ "stopping_rule",
224
+ "val_ratio",
225
+ "patience",
226
+ "min_delta",
227
+ "sma_window",
228
+ "ema_alpha",
229
+ "test_window",
230
+ "p_value",
231
+ "reshuffle_freq",
232
+ ):
233
+ if name in kwargs and kwargs[name] is not None:
234
+ setattr(self, name, kwargs[name])
235
+ if kwargs.get("num_epochs") is not None:
236
+ self.epochs = int(kwargs["num_epochs"])
237
+ self.num_epochs = int(self.epochs)
238
+ self.validation_strategy, self.stopping_rule = validate_training_options(
239
+ self.validation_strategy, self.stopping_rule
240
+ )
241
+
242
+ array = self._array(data)
243
+ self._build_model()
244
+ optimizer = torch.optim.Adam(self.model.parameters(), lr=float(self.learning_rate))
245
+ config = TrainingConfig(
246
+ batch_size=int(self.batch_size),
247
+ epochs=int(self.epochs),
248
+ learning_rate=float(self.learning_rate),
249
+ validation_strategy=self.validation_strategy,
250
+ stopping_rule=self.stopping_rule,
251
+ val_ratio=float(self.val_ratio),
252
+ patience=int(self.patience),
253
+ min_delta=float(self.min_delta),
254
+ sma_window=int(self.sma_window),
255
+ ema_alpha=float(self.ema_alpha),
256
+ test_window=int(self.test_window),
257
+ p_value=float(self.p_value),
258
+ reshuffle_freq=max(1, int(self.reshuffle_freq)),
259
+ )
260
+ stopper = StopController(config)
261
+ self.train_loss_ = []
262
+ self.val_loss_ = []
263
+ self.epochs_done_ = 0
264
+
265
+ train_loader = None
266
+ validation_loader = None
267
+ if self.validation_strategy == "static" and self.stopping_rule != "none":
268
+ train_indices, validation_indices = self._split(len(array))
269
+ train_loader = self._loader(array[train_indices], shuffle=True)
270
+ validation_loader = self._loader(array[validation_indices], shuffle=False)
271
+ elif self.validation_strategy == "static":
272
+ train_loader = self._loader(array, shuffle=True)
273
+
274
+ for epoch in range(config.epochs):
275
+ self.epochs_done_ += 1
276
+ if self.validation_strategy == "dynamic" and (
277
+ epoch == 0 or self.epochs_done_ % config.reshuffle_freq == 0
278
+ ):
279
+ train_indices, validation_indices = self._split(len(array))
280
+ train_loader = self._loader(array[train_indices], shuffle=True)
281
+ validation_loader = self._loader(array[validation_indices], shuffle=False)
282
+ self.train_loss_.append(self._run_epoch(train_loader, optimizer))
283
+ if validation_loader is not None:
284
+ validation_loss = self._run_epoch(validation_loader)
285
+ self.val_loss_.append(validation_loss)
286
+ if stopper.step(self.model, validation_loss):
287
+ break
288
+
289
+ if stopper.best_state is not None:
290
+ self.model.load_state_dict(stopper.best_state)
291
+ return self
292
+
293
+ @property
294
+ def train_loss(self) -> list[float]:
295
+ """Compatibility view used by the R wrapper."""
296
+ return self.train_loss_
297
+
298
+ @property
299
+ def val_loss(self) -> list[float]:
300
+ """Compatibility view used by the R wrapper."""
301
+ return self.val_loss_
302
+
303
+ def _require_fitted(self) -> None:
304
+ if self.model is None:
305
+ raise RuntimeError("the autoencoder must be fitted before transform")
306
+
307
+ def encode(self, data) -> np.ndarray:
308
+ self._require_fitted()
309
+ loader = self._loader(self._array(data), shuffle=False)
310
+ result = []
311
+ self.model.eval()
312
+ with torch.no_grad():
313
+ for features, _ in loader:
314
+ encoded = self.model.encoder(features.to(self.device_))
315
+ result.append(encoded.cpu().numpy())
316
+ return np.concatenate(result, axis=0)
317
+
318
+ def reconstruct(self, data) -> np.ndarray:
319
+ self._require_fitted()
320
+ loader = self._loader(self._array(data), shuffle=False)
321
+ result = []
322
+ self.model.eval()
323
+ with torch.no_grad():
324
+ for features, _ in loader:
325
+ decoded = self.model(features.to(self.device_))
326
+ result.append(decoded.cpu().numpy())
327
+ return np.concatenate(result, axis=0)
328
+
329
+
330
+ class AutoencE(_DenseAutoencoderMixin, AutoencBaseE):
331
+ """Dense encoder that returns a learned latent representation.
332
+
333
+ References:
334
+ Hinton, G. E., and Salakhutdinov, R. R. (2006). Reducing the
335
+ Dimensionality of Data with Neural Networks. Science, 313(5786):504-507.
336
+ Paszke, A., et al. (2019). PyTorch: An Imperative Style,
337
+ High-Performance Deep Learning Library. NeurIPS 32.
338
+
339
+ Porting:
340
+ Mirrors ``autoenc_e.R`` and replaces its embedded ``inst/python/autoenc.py``
341
+ backend. Fidelity: exact in architecture and training contract; an optional
342
+ ``random_state`` makes stochastic execution reproducible.
343
+ """
344
+
345
+ def __init__(self, input_size: int, encoding_size: int, **kwargs) -> None:
346
+ AutoencBaseE.__init__(self, input_size, encoding_size)
347
+ self._initialize(input_size=input_size, encoding_size=encoding_size, **kwargs)
348
+
349
+ def transform(self, data, **kwargs) -> np.ndarray:
350
+ return self.encode(data)
351
+
352
+
353
+ class AutoencEd(_DenseAutoencoderMixin, AutoencBaseEd):
354
+ """Dense encoder-decoder that returns reconstructed observations.
355
+
356
+ References:
357
+ Hinton, G. E., and Salakhutdinov, R. R. (2006). Reducing the
358
+ Dimensionality of Data with Neural Networks. Science, 313(5786):504-507.
359
+ Paszke, A., et al. (2019). PyTorch: An Imperative Style,
360
+ High-Performance Deep Learning Library. NeurIPS 32.
361
+
362
+ Porting:
363
+ Mirrors ``autoenc_ed.R`` and replaces its embedded ``inst/python/autoenc.py``
364
+ backend. Fidelity: exact in architecture and training contract; an optional
365
+ ``random_state`` makes stochastic execution reproducible.
366
+ """
367
+
368
+ def __init__(self, input_size: int, encoding_size: int, **kwargs) -> None:
369
+ AutoencBaseEd.__init__(self, input_size, encoding_size)
370
+ self._initialize(input_size=input_size, encoding_size=encoding_size, **kwargs)
371
+
372
+ def transform(self, data, **kwargs) -> np.ndarray:
373
+ return self.reconstruct(data)
374
+
375
+
376
+ class _DenoisingAutoencoderMixin(_DenseAutoencoderMixin):
377
+ def _initialize(self, *, noise_factor: float = 0.3, **kwargs) -> None:
378
+ if float(noise_factor) < 0:
379
+ raise ValueError("noise_factor must be non-negative")
380
+ self.noise_factor = float(noise_factor)
381
+ super()._initialize(**kwargs)
382
+
383
+ def _training_inputs(self, features: torch.Tensor) -> torch.Tensor:
384
+ return features + torch.randn_like(features) * self.noise_factor
385
+
386
+
387
+ class AutoencDenoiseE(_DenoisingAutoencoderMixin, AutoencBaseE):
388
+ """Denoising encoder that learns latent representations from corrupted inputs.
389
+
390
+ References:
391
+ Vincent, P., Larochelle, H., Bengio, Y., and Manzagol, P. A. (2008).
392
+ Extracting and Composing Robust Features with Denoising Autoencoders.
393
+ Proceedings of ICML 2008, 1096-1103.
394
+
395
+ Porting:
396
+ Mirrors ``autoenc_denoise_e.R`` and replaces
397
+ ``inst/python/autoenc_denoise.py``. Fidelity: architecture, Gaussian input
398
+ corruption and clean reconstruction targets match the legacy backend.
399
+ """
400
+
401
+ def __init__(self, input_size: int, encoding_size: int, **kwargs) -> None:
402
+ AutoencBaseE.__init__(self, input_size, encoding_size)
403
+ self._initialize(input_size=input_size, encoding_size=encoding_size, **kwargs)
404
+
405
+ def transform(self, data, **kwargs) -> np.ndarray:
406
+ return self.encode(data)
407
+
408
+
409
+ class AutoencDenoiseEd(_DenoisingAutoencoderMixin, AutoencBaseEd):
410
+ """Denoising encoder-decoder that reconstructs clean observations.
411
+
412
+ References:
413
+ Vincent, P., Larochelle, H., Bengio, Y., and Manzagol, P. A. (2008).
414
+ Extracting and Composing Robust Features with Denoising Autoencoders.
415
+ Proceedings of ICML 2008, 1096-1103.
416
+
417
+ Porting:
418
+ Mirrors ``autoenc_denoise_ed.R`` and replaces
419
+ ``inst/python/autoenc_denoise.py``. Fidelity: architecture, Gaussian input
420
+ corruption and clean reconstruction targets match the legacy backend.
421
+ """
422
+
423
+ def __init__(self, input_size: int, encoding_size: int, **kwargs) -> None:
424
+ AutoencBaseEd.__init__(self, input_size, encoding_size)
425
+ self._initialize(input_size=input_size, encoding_size=encoding_size, **kwargs)
426
+
427
+ def transform(self, data, **kwargs) -> np.ndarray:
428
+ return self.reconstruct(data)
@@ -0,0 +1,183 @@
1
+ """One-dimensional convolutional Deep ++ autoencoders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ import torch
7
+ from pydaltoolbox import AutoencBaseE, AutoencBaseEd
8
+ from torch import nn
9
+ from torch.utils.data import DataLoader, TensorDataset
10
+
11
+ from .autoencoder import _DenseAutoencoderMixin
12
+
13
+ __all__ = ["AutoencConvE", "AutoencConvEd"]
14
+
15
+
16
+ class _ConvNetwork(nn.Module):
17
+ def __init__(
18
+ self,
19
+ input_size: int,
20
+ encoding_size: int,
21
+ hidden_channels: int,
22
+ bottleneck_channels: int,
23
+ kernel_size: int,
24
+ negative_slope: float,
25
+ ) -> None:
26
+ super().__init__()
27
+ padding = kernel_size // 2
28
+ self.input_size = int(input_size)
29
+ self.encoder_features = nn.Sequential(
30
+ nn.Conv1d(1, hidden_channels, kernel_size=kernel_size, padding=padding),
31
+ nn.LeakyReLU(negative_slope=negative_slope),
32
+ nn.Conv1d(
33
+ hidden_channels,
34
+ bottleneck_channels,
35
+ kernel_size=kernel_size,
36
+ padding=padding,
37
+ ),
38
+ nn.LeakyReLU(negative_slope=negative_slope),
39
+ )
40
+ self.encoder_projection = nn.Sequential(
41
+ nn.Flatten(),
42
+ nn.Linear(bottleneck_channels * self.input_size, encoding_size),
43
+ )
44
+ self.decoder_projection = nn.Sequential(
45
+ nn.Linear(encoding_size, bottleneck_channels * self.input_size),
46
+ nn.LeakyReLU(negative_slope=negative_slope),
47
+ nn.Unflatten(1, (bottleneck_channels, self.input_size)),
48
+ )
49
+ self.decoder = nn.Sequential(
50
+ nn.ConvTranspose1d(
51
+ bottleneck_channels,
52
+ hidden_channels,
53
+ kernel_size=kernel_size,
54
+ padding=padding,
55
+ ),
56
+ nn.LeakyReLU(negative_slope=negative_slope),
57
+ nn.ConvTranspose1d(
58
+ hidden_channels,
59
+ 1,
60
+ kernel_size=kernel_size,
61
+ padding=padding,
62
+ ),
63
+ nn.Sigmoid(),
64
+ )
65
+
66
+ def encode(self, x: torch.Tensor) -> torch.Tensor:
67
+ return self.encoder_projection(self.encoder_features(x))
68
+
69
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
70
+ latent = self.encode(x)
71
+ return self.decoder(self.decoder_projection(latent))
72
+
73
+
74
+ class _ConvAutoencoderMixin(_DenseAutoencoderMixin):
75
+ def _initialize(
76
+ self,
77
+ *,
78
+ hidden_channels: int = 16,
79
+ bottleneck_channels: int = 32,
80
+ kernel_size: int = 3,
81
+ **kwargs,
82
+ ) -> None:
83
+ if int(hidden_channels) <= 0 or int(bottleneck_channels) <= 0:
84
+ raise ValueError("convolutional channel counts must be positive")
85
+ if int(kernel_size) <= 0 or int(kernel_size) % 2 == 0:
86
+ raise ValueError("kernel_size must be a positive odd number")
87
+ self.hidden_channels = int(hidden_channels)
88
+ self.bottleneck_channels = int(bottleneck_channels)
89
+ self.kernel_size = int(kernel_size)
90
+ super()._initialize(**kwargs)
91
+
92
+ def _build_model(self) -> None:
93
+ self._seed()
94
+ self.device_ = torch.device(self.device)
95
+ self.model = _ConvNetwork(
96
+ self.input_size,
97
+ self.encoding_size,
98
+ self.hidden_channels,
99
+ self.bottleneck_channels,
100
+ self.kernel_size,
101
+ self.negative_slope,
102
+ ).float().to(self.device_)
103
+
104
+ def _loader(self, array: np.ndarray, *, shuffle: bool) -> DataLoader:
105
+ tensor = torch.from_numpy(
106
+ np.array(array[:, np.newaxis, :], dtype=np.float32, copy=True)
107
+ )
108
+ return DataLoader(
109
+ TensorDataset(tensor, tensor),
110
+ batch_size=self.batch_size,
111
+ shuffle=shuffle,
112
+ drop_last=False,
113
+ )
114
+
115
+ def encode(self, data) -> np.ndarray:
116
+ self._require_fitted()
117
+ loader = self._loader(self._array(data), shuffle=False)
118
+ result = []
119
+ self.model.eval()
120
+ with torch.no_grad():
121
+ for features, _ in loader:
122
+ encoded = self.model.encode(features.to(self.device_))
123
+ result.append(encoded.cpu().numpy())
124
+ return np.concatenate(result, axis=0)
125
+
126
+ def reconstruct(self, data) -> np.ndarray:
127
+ self._require_fitted()
128
+ loader = self._loader(self._array(data), shuffle=False)
129
+ result = []
130
+ self.model.eval()
131
+ with torch.no_grad():
132
+ for features, _ in loader:
133
+ decoded = self.model(features.to(self.device_))
134
+ result.append(decoded.cpu().numpy().squeeze(1))
135
+ return np.concatenate(result, axis=0)
136
+
137
+
138
+ class AutoencConvE(_ConvAutoencoderMixin, AutoencBaseE):
139
+ """Conv1D encoder for local patterns within observation windows.
140
+
141
+ References:
142
+ Masci, J., Meier, U., Ciresan, D., and Schmidhuber, J. (2011).
143
+ Stacked Convolutional Auto-Encoders for Hierarchical Feature Extraction.
144
+ ICANN 2011, 52-59.
145
+
146
+ Porting:
147
+ Mirrors ``autoenc_conv_e.R`` and replaces
148
+ ``inst/python/autoenc_conv.py``. Fidelity: the one-channel reshape,
149
+ convolutional architecture, LeakyReLU activations, linear bottleneck,
150
+ sigmoid reconstruction, optimizer and training contract match the legacy
151
+ backend.
152
+ """
153
+
154
+ def __init__(self, input_size: int, encoding_size: int, **kwargs) -> None:
155
+ AutoencBaseE.__init__(self, input_size, encoding_size)
156
+ self._initialize(input_size=input_size, encoding_size=encoding_size, **kwargs)
157
+
158
+ def transform(self, data, **kwargs) -> np.ndarray:
159
+ return self.encode(data)
160
+
161
+
162
+ class AutoencConvEd(_ConvAutoencoderMixin, AutoencBaseEd):
163
+ """Conv1D encoder-decoder that reconstructs observation windows.
164
+
165
+ References:
166
+ Masci, J., Meier, U., Ciresan, D., and Schmidhuber, J. (2011).
167
+ Stacked Convolutional Auto-Encoders for Hierarchical Feature Extraction.
168
+ ICANN 2011, 52-59.
169
+
170
+ Porting:
171
+ Mirrors ``autoenc_conv_ed.R`` and replaces
172
+ ``inst/python/autoenc_conv.py``. Fidelity: the one-channel reshape,
173
+ convolutional architecture, LeakyReLU activations, linear bottleneck,
174
+ sigmoid reconstruction, optimizer and training contract match the legacy
175
+ backend.
176
+ """
177
+
178
+ def __init__(self, input_size: int, encoding_size: int, **kwargs) -> None:
179
+ AutoencBaseEd.__init__(self, input_size, encoding_size)
180
+ self._initialize(input_size=input_size, encoding_size=encoding_size, **kwargs)
181
+
182
+ def transform(self, data, **kwargs) -> np.ndarray:
183
+ return self.reconstruct(data)
@@ -0,0 +1,76 @@
1
+ Metadata-Version: 2.5
2
+ Name: pydaltoolboxdp
3
+ Version: 0.1.0
4
+ Summary: Deep ++ extensions for pydaltoolbox, pytspredit, and pyharbinger
5
+ Project-URL: Homepage, https://github.com/cefet-rj-dal/pydaltoolboxdp
6
+ Project-URL: Repository, https://github.com/cefet-rj-dal/pydaltoolboxdp
7
+ Project-URL: Bug Tracker, https://github.com/cefet-rj-dal/pydaltoolboxdp/issues
8
+ Author: CEFET/RJ
9
+ Author-email: Eduardo Ogasawara <eogasawara@ieee.org>, Diego Salles <diego.salles@eic.cefet-rj.br>, Erich Carvalho <erich.carvalho@eic.cefet-rj.br>, Janio Lima <janio.lima@eic.cefet-rj.br>, Joao Kongevold <joao.kongevold@eic.cefet-rj.br>, Lucas Tavares <lucas.tavares@eic.cefet-rj.br>, Eduardo Bezerra <ebezerra@cefet-rj.br>
10
+ Maintainer-email: Eduardo Ogasawara <eogasawara@ieee.org>
11
+ License: MIT
12
+ License-File: LICENSE
13
+ Keywords: autoencoder,deep learning,event detection,experiment line,time series
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: numpy>=1.23
21
+ Requires-Dist: pandas>=1.5
22
+ Requires-Dist: pydaltoolbox>=0.25.0
23
+ Requires-Dist: pyharbinger>=0.12.0
24
+ Requires-Dist: pytspredit>=0.13.0
25
+ Requires-Dist: scipy>=1.9
26
+ Requires-Dist: torch>=2.0
27
+ Provides-Extra: dev
28
+ Requires-Dist: build; extra == 'dev'
29
+ Requires-Dist: pytest>=7; extra == 'dev'
30
+ Requires-Dist: ruff>=0.1; extra == 'dev'
31
+ Requires-Dist: twine; extra == 'dev'
32
+ Provides-Extra: docs
33
+ Requires-Dist: ipykernel>=6; extra == 'docs'
34
+ Requires-Dist: jupytext>=1.16; extra == 'docs'
35
+ Requires-Dist: matplotlib>=3.6; extra == 'docs'
36
+ Requires-Dist: nbclient>=0.9; extra == 'docs'
37
+ Requires-Dist: nbconvert>=7; extra == 'docs'
38
+ Description-Content-Type: text/markdown
39
+
40
+ # pydaltoolboxdp: Deep ++ Extensions for `pydaltoolbox`
41
+
42
+ `pydaltoolboxdp` is the Python implementation of the DAL ecosystem's **Deep ++**
43
+ layer. It provides deep-learning and advanced models that specialize the contracts
44
+ defined by `pydaltoolbox`, `pytspredit`, and `pyharbinger`.
45
+
46
+ The sibling R package, `daltoolboxdp`, is a thin `reticulate` interface to these
47
+ classes. Python algorithms live here once; they are not duplicated inside the R
48
+ package.
49
+
50
+ The project is in its initial porting phase. The implemented vertical slices are the
51
+ dense, denoising, and convolutional autoencoder families:
52
+
53
+ - `AutoencE`: transforms observations into their latent representation;
54
+ - `AutoencEd`: reconstructs observations after encoding.
55
+ - `AutoencDenoiseE`: learns robust latent representations from corrupted inputs;
56
+ - `AutoencDenoiseEd`: reconstructs clean observations after denoising training.
57
+ - `AutoencConvE`: learns compact representations of local patterns with Conv1D layers;
58
+ - `AutoencConvEd`: reconstructs windows with a convolutional encoder-decoder.
59
+
60
+ ## Installation
61
+
62
+ Development installation from this checkout:
63
+
64
+ ```bash
65
+ python -m pip install -e .
66
+ ```
67
+
68
+ On Python 3.14, prefer binary dependencies so `pyharbinger` selects the available
69
+ pure-Python `ruptures` wheel instead of attempting a local C compilation:
70
+
71
+ ```bash
72
+ python -m pip install --prefer-binary pydaltoolboxdp
73
+ ```
74
+
75
+ PyTorch is a core dependency because Deep ++ is specifically the deep-learning
76
+ extension layer. GPU use is optional; models run on CPU by default.
@@ -0,0 +1,8 @@
1
+ pydaltoolboxdp/__init__.py,sha256=qjJrxdL8_RGudWV9SsTJPqde8bNeunY5Gu-jmOVGBtI,512
2
+ pydaltoolboxdp/_training.py,sha256=o1vwXIa_s3SG--Y-QlTxRWYlEVPi7jMv6vtsd_vmflk,6316
3
+ pydaltoolboxdp/autoencoder.py,sha256=_ytkbM3OsLlMnl6VWvV0KogdwkW55GVUboRgpq3_mLA,17092
4
+ pydaltoolboxdp/convolutional.py,sha256=EOiP4pDLcuN3ZywpH9aFXd89dDtNN02PZoqu3_a-_OU,6598
5
+ pydaltoolboxdp-0.1.0.dist-info/METADATA,sha256=cBWUSI9zHGz0UOIIy4m8b3BHyKJ6G0qQjLvcQqQvdh4,3363
6
+ pydaltoolboxdp-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
7
+ pydaltoolboxdp-0.1.0.dist-info/licenses/LICENSE,sha256=KefIjDd37_uj9RCVim41oiJgwLnhD4MJYdwN9gpRcH8,1096
8
+ pydaltoolboxdp-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Data Analytics Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.