Metadata-Version: 2.4
Name: rwml
Version: 1.0.0
Summary: Read-Write Machine Learning: models that change their weights and their training data together, in one training run
Author: Yassine Baghoussi
License: Apache-2.0
Project-URL: Homepage, https://hesperon.com
Project-URL: Repository, https://github.com/hesperon/rwml
Project-URL: Issues, https://github.com/hesperon/rwml/issues
Keywords: time series,forecasting,LSTM,read-write machine learning,pytorch,robust training,data quality,anomalies,sensor data
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0
Requires-Dist: numpy
Provides-Extra: sarima
Requires-Dist: statsmodels; extra == "sarima"
Provides-Extra: bench
Requires-Dist: pandas; extra == "bench"
Requires-Dist: pyarrow; extra == "bench"
Requires-Dist: scipy; extra == "bench"
Requires-Dist: matplotlib; extra == "bench"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: statsmodels; extra == "dev"
Requires-Dist: pandas; extra == "dev"
Requires-Dist: pyarrow; extra == "dev"
Requires-Dist: scipy; extra == "dev"
Requires-Dist: matplotlib; extra == "dev"
Provides-Extra: release
Requires-Dist: torch==2.15.0; extra == "release"
Requires-Dist: numpy==2.5.5; extra == "release"
Requires-Dist: statsmodels==0.15.0; extra == "release"
Requires-Dist: pmdarima==2.1.1; extra == "release"
Dynamic: license-file

# rwml

[![tests](https://github.com/hesperon/rwml/actions/workflows/tests.yml/badge.svg)](https://github.com/hesperon/rwml/actions/workflows/tests.yml)
[![PyPI](https://img.shields.io/pypi/v/rwml)](https://pypi.org/project/rwml/)

Developed by [Hesperon AI](https://hesperon.com). Source: [github.com/hesperon/rwml](https://github.com/hesperon/rwml).

`rwml` is the library for **Read-Write Machine Learning**: models that change their weights and their training data
together, in one training run. A standard model only reads its data and changes its weights; a read-write model also
writes, guided by signals from inside the model (its errors, its internal state), and goes on learning from what it
wrote. The original training data is never modified; what the model wrote is kept on the model.

Version 1.0 covers time-series forecasting with recurrent networks (LSTM); read-write versions of other model
families (convolutional networks, decision trees and more) will be added as each is confirmed. The main use case is
training data with faults (outages, spikes, stuck values): on real building meters and on series with injected
faults, the confirmed methods lowered the error of the same LSTM by 8% to 43% on average, and by up to 95% on single
series (see "Results").

## Install

```bash
pip install rwml                 # CorrectorLSTM, RWLSTM, PastPropLSTM
pip install "rwml[sarima]"       # also the seasonal ARIMA estimator (needs statsmodels)
pip install "rwml[bench]"        # the benchmark tools: raw results, leaderboard, reproduction
```

From source: `git clone https://github.com/hesperon/rwml`, then `pip install .` in the repository folder.

Needs Python 3.10+, `torch` and `numpy`. The demo outputs in the docs were produced in the release environment
(`requirements-release.txt`, or `pip install "rwml[release]"`: Python 3.12.3, torch 2.15.0, CPU); other torch versions
give other digits of the same kind.

## Quickstart

`RWLSTM()`, the confirmed default, on a standardised series. It reads each training target's residual and gives the
targets it cannot explain loss weight 0 (it writes loss weights, not data):

```python
from rwml import RWLSTM, standardize

series, mu, sd = standardize(my_series, n_fit=440)      # my_series: your 1-D array
model = RWLSTM(season=12).fit(series[:440])            # = RWLSTM(read="residual", write="weight", season=12)
forecast = model.predict(series[440:-1])                # forecast[t] is for the value after series[440 + t]
model.written_                                          # the targets given loss weight 0; the series is unchanged

RWLSTM(season=12, threshold=float("inf"))              # writing off: the same LSTM, to compare with
```

`CorrectorLSTM()` reads its own hidden states and writes new values for training inputs:

```python
from rwml import CorrectorLSTM

model = CorrectorLSTM(season=12).fit(series[:440])      # the benchmarked defaults; season: 12 monthly, None if none
forecast = model.predict(series[440:-1])
model.corrected_series_                                 # the training series as written
model.written_                                          # positions written
model.corrections_                                      # every flagged value: bound, proposal, losses, outcome

CorrectorLSTM(threshold=float("inf"))                   # writing off: the plain LSTM
```

The methods (chosen by what they read and write; nothing else changes them):

| call | reads | writes |
|---|---|---|
| `RWLSTM()` = `RWLSTM(read="residual", write="weight")` (default) | each training target's robust residual | loss weight 0 for the targets it cannot explain |
| `CorrectorLSTM()` = `CorrectorLSTM(read="state", write="value")` (default) | its own hidden states (kernel estimator) | new values for training inputs |
| `RWLSTM(read="gradient", write="input")` | the loss gradient with respect to each training input | the training inputs |
| `PastPropLSTM(variant=...)` | the loss gradient with respect to the training series | the training series |

Which call reproduces which paper (`settings=` only sets the paper's hyperparameter values; it never changes what is
read or written, and the estimator must be the paper's):

| paper | call |
|---|---|
| Corrector LSTM, NCA 2024 | `CorrectorLSTM(estimator="sarima", settings="nca2024")` |
| Kernel Corrector LSTM, IDA 2024 | `CorrectorLSTM(estimator="kernel", settings="ida2024")` |
| RW-LSTM, ICDM 2025 | `RWLSTM(read="gradient", write="input", settings="icdm2025")` (`settings="reference"`: the original code as it ran) |
| PastProp-RNN, KDD MiLeTS 2020 (extended: arXiv 2106.13881) | `PastPropLSTM(variant="epoch" / "instance" / "selective")` |

The gradient method of the ICDM 2025 paper, `RWLSTM(read="gradient")`, works on windows:

```python
from rwml import RWLSTM, make_windows

X, y = make_windows(series, window=8)                   # X (n, 8), y (n, 1)
model = RWLSTM(read="gradient", write="input", settings="icdm2025").fit(X[:800], y[:800])
forecast = model.predict(X[800:])
changed = model.written_data_ - X[:800]                 # what the model wrote; X itself is never modified
```

Research methods (window writes: `WindowLSTM` with `TrimWrite`, `RollbackWrite`, `PatienceWrite`) are in
`rwml.experimental`. A worked example on a faulty meter:
[docs/tutorial.md](docs/tutorial.md). All documentation: [docs/README.md](docs/README.md); all parameters: [docs/parameters.md](docs/parameters.md). Which estimator to use:
[docs/choosing_an_estimator.md](docs/choosing_an_estimator.md).

## Results

Every result here comes from our own pre-registered protocols on fresh data: the rules and claims were committed
before any fit, on series never used to design the methods. They use different data and splits than the papers, so
the papers' figures are not directly comparable (differences: [docs/benchmarks.md](docs/benchmarks.md)). Error
reduction = 100 (1 - ratio), ratio = geometric mean over series of (MASE + 0.01) ratios; 95% bootstrap CIs.

**Largest single-series gains** (`RWLSTM()` against the same LSTM without writing):

| series | error reduction | what was wrong in its training data |
|---|---|---|
| FRED-MD T40 (a US macro series) | 94.9% | 18 injected faulty training values (6 spike, 4 level-shift, 4 stuck, 4 dropout) |
| BDG2 meter Lamb_education_Marc (a real building) | 93.1% | 251 training readings flagged by the dataset's cleaning |
| BDG2 meter Bull_office_Marco (a real building) | 78.6% | raw readings, faults left in (none flagged in training) |

**Averages:**

| data | series | `RWLSTM()` vs the same LSTM without writing | other confirmed results |
|---|---|---|---|
| 5% injected faults in training ([protocol](docs/protocol/winning_story.md), addendum 5) | 631 | **42.67%** [40.53%, 44.83%] (better on 517, worse on 4) | `CorrectorLSTM()` vs its LSTM: 22.63% [20.57%, 24.78%] |
| BDG2 building meters ([protocol](docs/protocol/bdg2_confirm.md)) | 300 | **10.32%** [7.99%, 12.72%] | `RWLSTM()` + ARIMA vs ARIMA: 3.99% [2.03%, 5.87%] |
| BDG2 building meters, second fresh draw ([protocol](docs/protocol/bdg2_confirm2.md)) | 300 | **9.74%** [7.96%, 11.61%] | `RWLSTM()` + ARIMA vs ARIMA: 3.16% [1.63%, 4.74%] |
| LEAD 1.0 building meters, labelled faults ([protocol](docs/protocol/lead_confirm.md)) | 164 | **8.38%** [6.38%, 10.51%]; 13.24% on the 44 with faults in training | |
| M4 + FRED-MD, mostly clean ([protocol](docs/protocol/rw_lstm.md), addendum 8) | 709 | **1.66%** [1.29%, 2.06%] | |
| M4 + pedestrian, `CorrectorLSTM()` ([protocol](docs/protocol/corrector_lstm.md), addenda 8 to 10) | 675 | | `CorrectorLSTM()` vs its LSTM: 0.17% [0.09%, 0.27%] |

- On building meters, `RWLSTM()` + ARIMA (the average of the two forecasts) has lower error than ARIMA: 3.99% and
  3.16% on the two BDG2 draws, while the same average built with the LSTM without writing does not beat ARIMA.
  `rwml.combine` averages forecasts.
- With 5% injected faults, `RWLSTM()` had 65% lower error than ARIMA and ETS run on the faulty data, and its error
  stayed near its clean-data value up to 10% faulty values.
- Every confirmed number was computed with the batched research trainer of the confirmations, shipped as
  `rwml.bench.reproduce` (one command per confirmation regenerates its numbers from the raw data and the
  pre-registered series lists). `RWLSTM` fits one series at a time; in aggregate the two agree (a pre-registered check
  on 60 BDG2 meters, [protocol](docs/protocol/package_check.md): 9.24% against 9.80% [6.86%, 12.82%]), single series differ (for example 11.9% against 8.4% on the
  median BDG2 meter; [docs/tutorial.md](docs/tutorial.md)). How `CorrectorLSTM()` works:
  [docs/methods/corrector_lstm.md](docs/methods/corrector_lstm.md).

**When to use it.** On training data with faults (sensors, meters, logs). Validate with writing off (see "Best
practice").

## Roadmap

Planned, each added as it is confirmed (pre-registered, on fresh data, as above):

- read-write versions of other model families: convolutional networks, decision trees and more;
- missing values accepted in the training data;
- multi-step forecasts;
- a built-in `RWLSTM()` + ARIMA forecast (today: fit ARIMA yourself and average with `rwml.combine`).

## Best practice

- **Compare with writing off.** Every rwml model has the same model with writing switched off (for the defaults:
  `threshold=float("inf")`), so you can validate on held-out data as with any model choice.
- **Inspect what the model wrote.** Every model records its writes (`written_`, `written_data_`, `corrections_` or
  `corrected_series_`, depending on the model), so each change to the training data can be reviewed.
- **Evidence.** Each result links its pre-registered protocol, with the series better, tied and worse. Known limits
  of each method: [docs/README.md](docs/README.md).

## Citation

R. Tuna, Y. Baghoussi, C. Soares, J. Mendes-Moreira. "Kernel Corrector LSTM". Advances in Intelligent Data Analysis
XXII (IDA 2024). arXiv:2404.18273.

Y. Baghoussi, C. Soares, J. Mendes-Moreira. "Corrector LSTM: built-in training data correction for improved
time-series forecasting". Neural Computing and Applications 36, 16213-16231 (2024). doi:10.1007/s00521-024-09962-x

Y. Baghoussi, C. Soares, J. Mendes-Moreira. "Read-write LSTM: A Novel Approach Integrating Backpropagation to Data
in LSTM". IEEE International Conference on Data Mining (ICDM), 2025. doi:10.1109/ICDM65498.2025.00012

A. Baptista, Y. Baghoussi, C. Soares, J. Mendes-Moreira, M. Arantes. "Pastprop-RNN: improved predictions of the future
by correcting the past". MiLeTS '20, 6th KDD Workshop on Mining and Learning from Time Series, 2020; extended version
arXiv:2106.13881.

## Licence

Apache-2.0
