pydaltoolboxdp 0.1.0__tar.gz

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,223 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[codz]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py.cover
50
+ *.lcov
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ cover/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ .pybuilder/
77
+ target/
78
+
79
+ # Jupyter Notebook
80
+ .ipynb_checkpoints
81
+
82
+ # IPython
83
+ profile_default/
84
+ ipython_config.py
85
+
86
+ # pyenv
87
+ # For a library or package, you might want to ignore these files since the code is
88
+ # intended to run in multiple environments; otherwise, check them in:
89
+ # .python-version
90
+
91
+ # pipenv
92
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
93
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
94
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
95
+ # install all needed dependencies.
96
+ # Pipfile.lock
97
+
98
+ # uv
99
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
100
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
101
+ # commonly ignored for libraries.
102
+ # uv.lock
103
+
104
+ # poetry
105
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
106
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
107
+ # commonly ignored for libraries.
108
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
109
+ # poetry.lock
110
+ # poetry.toml
111
+
112
+ # pdm
113
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
114
+ # pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
115
+ # https://pdm-project.org/en/latest/usage/project/#working-with-version-control
116
+ # pdm.lock
117
+ # pdm.toml
118
+ .pdm-python
119
+ .pdm-build/
120
+
121
+ # pixi
122
+ # Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
123
+ # pixi.lock
124
+ # Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
125
+ # in the .venv directory. It is recommended not to include this directory in version control.
126
+ .pixi/*
127
+ !.pixi/config.toml
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule*
134
+ celerybeat.pid
135
+
136
+ # Redis
137
+ *.rdb
138
+ *.aof
139
+ *.pid
140
+
141
+ # RabbitMQ
142
+ mnesia/
143
+ rabbitmq/
144
+ rabbitmq-data/
145
+
146
+ # ActiveMQ
147
+ activemq-data/
148
+
149
+ # SageMath parsed files
150
+ *.sage.py
151
+
152
+ # Environments
153
+ .env
154
+ .envrc
155
+ .venv
156
+ env/
157
+ venv/
158
+ ENV/
159
+ env.bak/
160
+ venv.bak/
161
+
162
+ # Conda environments
163
+ conda-meta/
164
+
165
+ # Spyder project settings
166
+ .spyderproject
167
+ .spyproject
168
+
169
+ # Rope project settings
170
+ .ropeproject
171
+
172
+ # mkdocs/Zensical documentation
173
+ /site
174
+
175
+ # mypy
176
+ .mypy_cache/
177
+ .dmypy.json
178
+ dmypy.json
179
+
180
+ # Pyre type checker
181
+ .pyre/
182
+
183
+ # pytype static type analyzer
184
+ .pytype/
185
+
186
+ # Cython debug symbols
187
+ cython_debug/
188
+
189
+ # PyCharm
190
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
191
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
192
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
193
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
194
+ # .idea/
195
+
196
+ # Abstra
197
+ # Abstra is an AI-powered process automation framework.
198
+ # Ignore directories containing user credentials, local state, and settings.
199
+ # Learn more at https://abstra.io/docs
200
+ .abstra/
201
+
202
+ # Visual Studio Code
203
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore that
204
+ # can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
205
+ # and can be added to the global gitignore or merged into this file. However, if you prefer, you
206
+ # could uncomment the following to ignore the entire vscode folder
207
+ # .vscode/
208
+ # Temporary file for partial code execution
209
+ tempCodeRunnerFile.py
210
+
211
+ # Ruff stuff:
212
+ .ruff_cache/
213
+
214
+ # PyPI configuration file
215
+ .pypirc
216
+
217
+ # Marimo
218
+ marimo/_static/
219
+ marimo/_lsp/
220
+ __marimo__/
221
+
222
+ # Streamlit
223
+ .streamlit/secrets.toml
@@ -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.
@@ -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,37 @@
1
+ # pydaltoolboxdp: Deep ++ Extensions for `pydaltoolbox`
2
+
3
+ `pydaltoolboxdp` is the Python implementation of the DAL ecosystem's **Deep ++**
4
+ layer. It provides deep-learning and advanced models that specialize the contracts
5
+ defined by `pydaltoolbox`, `pytspredit`, and `pyharbinger`.
6
+
7
+ The sibling R package, `daltoolboxdp`, is a thin `reticulate` interface to these
8
+ classes. Python algorithms live here once; they are not duplicated inside the R
9
+ package.
10
+
11
+ The project is in its initial porting phase. The implemented vertical slices are the
12
+ dense, denoising, and convolutional autoencoder families:
13
+
14
+ - `AutoencE`: transforms observations into their latent representation;
15
+ - `AutoencEd`: reconstructs observations after encoding.
16
+ - `AutoencDenoiseE`: learns robust latent representations from corrupted inputs;
17
+ - `AutoencDenoiseEd`: reconstructs clean observations after denoising training.
18
+ - `AutoencConvE`: learns compact representations of local patterns with Conv1D layers;
19
+ - `AutoencConvEd`: reconstructs windows with a convolutional encoder-decoder.
20
+
21
+ ## Installation
22
+
23
+ Development installation from this checkout:
24
+
25
+ ```bash
26
+ python -m pip install -e .
27
+ ```
28
+
29
+ On Python 3.14, prefer binary dependencies so `pyharbinger` selects the available
30
+ pure-Python `ruptures` wheel instead of attempting a local C compilation:
31
+
32
+ ```bash
33
+ python -m pip install --prefer-binary pydaltoolboxdp
34
+ ```
35
+
36
+ PyTorch is a core dependency because Deep ++ is specifically the deep-learning
37
+ extension layer. GPU use is optional; models run on CPU by default.
@@ -0,0 +1,77 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "pydaltoolboxdp"
7
+ version = "0.1.0"
8
+ description = "Deep ++ extensions for pydaltoolbox, pytspredit, and pyharbinger"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ maintainers = [
13
+ { name = "Eduardo Ogasawara", email = "eogasawara@ieee.org" },
14
+ ]
15
+ authors = [
16
+ { name = "Eduardo Ogasawara", email = "eogasawara@ieee.org" },
17
+ { name = "Diego Salles", email = "diego.salles@eic.cefet-rj.br" },
18
+ { name = "Erich Carvalho", email = "erich.carvalho@eic.cefet-rj.br" },
19
+ { name = "Janio Lima", email = "janio.lima@eic.cefet-rj.br" },
20
+ { name = "Joao Kongevold", email = "joao.kongevold@eic.cefet-rj.br" },
21
+ { name = "Lucas Tavares", email = "lucas.tavares@eic.cefet-rj.br" },
22
+ { name = "Eduardo Bezerra", email = "ebezerra@cefet-rj.br" },
23
+ { name = "CEFET/RJ" },
24
+ ]
25
+ keywords = [
26
+ "deep learning",
27
+ "autoencoder",
28
+ "time series",
29
+ "event detection",
30
+ "experiment line",
31
+ ]
32
+ classifiers = [
33
+ "Development Status :: 3 - Alpha",
34
+ "Intended Audience :: Science/Research",
35
+ "License :: OSI Approved :: MIT License",
36
+ "Programming Language :: Python :: 3",
37
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
38
+ ]
39
+ dependencies = [
40
+ "numpy>=1.23",
41
+ "pandas>=1.5",
42
+ "scipy>=1.9",
43
+ "torch>=2.0",
44
+ "pydaltoolbox>=0.25.0",
45
+ "pytspredit>=0.13.0",
46
+ "pyharbinger>=0.12.0",
47
+ ]
48
+
49
+ [project.optional-dependencies]
50
+ dev = ["pytest>=7", "ruff>=0.1", "build", "twine"]
51
+ docs = [
52
+ "jupytext>=1.16",
53
+ "nbconvert>=7",
54
+ "nbclient>=0.9",
55
+ "ipykernel>=6",
56
+ "matplotlib>=3.6",
57
+ ]
58
+
59
+ [project.urls]
60
+ Homepage = "https://github.com/cefet-rj-dal/pydaltoolboxdp"
61
+ Repository = "https://github.com/cefet-rj-dal/pydaltoolboxdp"
62
+ "Bug Tracker" = "https://github.com/cefet-rj-dal/pydaltoolboxdp/issues"
63
+
64
+ [tool.hatch.build.targets.wheel]
65
+ packages = ["src/pydaltoolboxdp"]
66
+
67
+ [tool.hatch.build.targets.sdist]
68
+ include = ["src/pydaltoolboxdp", "README.md", "LICENSE"]
69
+ exclude = ["develop", "notebooks", "examples", "tests"]
70
+
71
+ [tool.pytest.ini_options]
72
+ testpaths = ["tests"]
73
+ addopts = "-q"
74
+
75
+ [tool.ruff]
76
+ line-length = 100
77
+ target-version = "py310"
@@ -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)