Metadata-Version: 2.4
Name: datatunner
Version: 4.0.0
Summary: Scientific platform for optimal artificial-data proportion in deep learning experiments
Author: Gustavo Maia de Almeida
Author-email: Leandro Costa Rocha <leandrocrx@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/leandrocrx/datatunner
Project-URL: Repository, https://github.com/leandrocrx/datatunner
Project-URL: Issues, https://github.com/leandrocrx/datatunner/issues
Keywords: synthetic data,data augmentation,SMOTE,CTGAN,data-centric AI,reproducible experiments,AutoML
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
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 :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy<3,>=1.24
Requires-Dist: pandas<3,>=2
Requires-Dist: scikit-learn<2,>=1.3
Requires-Dist: scipy<2,>=1.10
Requires-Dist: matplotlib<4,>=3.7
Provides-Extra: tabular
Requires-Dist: imbalanced-learn<1,>=0.11; extra == "tabular"
Requires-Dist: sdv<2,>=1.12; extra == "tabular"
Requires-Dist: sdmetrics<1,>=0.14; extra == "tabular"
Provides-Extra: image
Requires-Dist: torch<3,>=2.1; extra == "image"
Requires-Dist: torchvision<1,>=0.16; extra == "image"
Requires-Dist: Pillow<13,>=10; extra == "image"
Provides-Extra: reporting
Requires-Dist: tabulate<1,>=0.9; extra == "reporting"
Requires-Dist: seaborn<1,>=0.13; extra == "reporting"
Provides-Extra: dev
Requires-Dist: pytest<9,>=8; extra == "dev"
Requires-Dist: pytest-cov<7,>=5; extra == "dev"
Requires-Dist: ruff<1,>=0.6; extra == "dev"
Requires-Dist: mypy<2,>=1.10; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Provides-Extra: full
Requires-Dist: imbalanced-learn<1,>=0.11; extra == "full"
Requires-Dist: sdv<2,>=1.12; extra == "full"
Requires-Dist: sdmetrics<1,>=0.14; extra == "full"
Requires-Dist: torch<3,>=2.1; extra == "full"
Requires-Dist: torchvision<1,>=0.16; extra == "full"
Requires-Dist: Pillow<13,>=10; extra == "full"
Requires-Dist: tabulate<1,>=0.9; extra == "full"
Requires-Dist: seaborn<1,>=0.13; extra == "full"
Dynamic: license-file

# DataTunner 4.0.0

**Scientific platform for optimal artificial-data proportion in deep learning experiments.**

DataTunner determines the optimal artificial-data fraction `alpha` (`alpha*`) under an
isolated validation protocol, with full provenance, statistical summaries, and held-out
final testing. It supports tabular datasets (SMOTE and CTGAN) and image datasets
(materialized data augmentation), and it can persist every trained model so the best
result can be chosen from the reports.

```text
alpha = n_synthetic / (n_real + n_synthetic)
```

## What's new in 4.0.0

- **Two selected alphas per experiment** — `alpha*` (best cost-benefit) and `alpha**`
  (best effective), each validated on the held-out test set.
- **Explicit public APIs** — `DataTunnerTabular` and `DataTunnerImage`, with lazy imports
  so tabular installs do not require PyTorch.
- **Model persistence** — set `artifact_dir` to save every trained model per alpha and
  repetition, the final models for the selected alphas, and a `models_index.json` catalog
  to choose the best result from the reports; `datatunner.load_model` reloads any artifact.
- **Python 3.10+** — modern typing across the package.

## Install

```bash
python -m pip install "datatunner[full]==4.0.0"   # everything (torch, SDV, imbalanced-learn)
```

Mechanism-specific extras keep the base install light:

```bash
pip install datatunner            # core only (numpy, pandas, sklearn, scipy, matplotlib)
pip install "datatunner[tabular]" # + imbalanced-learn and SDV/SDMetrics (SMOTE, CTGAN)
pip install "datatunner[image]"   # + torch / torchvision / Pillow (augmentation)
```

For local development and the complete test suite, install `.[dev,full]`. The image
feature is optional; image-only tests are skipped when PyTorch is not installed.

## Two alpha selections

Each experiment reports two alphas:

- `alpha*` (`report.alpha_star` / `report.selected`): the **best cost-benefit** candidate —
  the cheapest alpha whose validation confidence interval overlaps the best observed
  mean, so extra synthetic data would not buy a statistically distinguishable gain.
- `alpha**` (`report.alpha_star_star` / `report.best_effective`): the **best effective**
  candidate — the alpha with the best observed mean, regardless of synthetic-data cost.

Both are validated on the held-out test set: `report.final_test` (alpha*) and
`report.final_test_alpha_star_star` (alpha**).

## Saved model artifacts

Set `artifact_dir` to persist every trained model (each alpha and repetition) plus the
final models for the two selected alphas:

```python
config = ExperimentConfig(
    task_type="classification",
    data_type="tabular",
    target_column="target",
    metric=MetricSpec("f1_macro", "maximize"),
    artifact_dir="datatunner_artifacts/breast_cancer",
    # ...
)

report = DataTunnerTabular(config).run(df, build_model, SMOTEGenerator("target"))

# Paths are exposed by the report, including the best trial of each alpha.
best_path = report.candidates[0].best_model_path
final_path = report.final_test.model_path

from datatunner import load_model

model = load_model(best_path)
```

The run directory contains:

- `models/alpha_<value>/candidate_rep<r>_seed<s>.*` — one artifact per candidate trial.
- `models/final/alpha_star_alpha_<value>.*` and `models/final/alpha_star_star_alpha_<value>.*`
  — the final models for the selected alphas.
- `models_index.json` — catalog mapping every artifact to its alpha, seed, status, and
  metric value, so the best result can be chosen from the reports.
- `experiment_report.json` — full report as returned by `run`.

Tabular estimators are stored with `pickle` (`.pkl`); PyTorch modules are stored as
`state_dict` files (`.pt`) and require the same architecture through `model_factory` when
loading with `load_model(path, model_factory=...)`. Pickle artifacts execute code when
loaded, so only load files produced by your own experiment.

## Minimal tabular example

```python
from sklearn.datasets import load_breast_cancer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from datatunner import AlphaSpec, ExperimentConfig, MetricSpec, DataTunnerTabular
from datatunner.tabular.generators import SMOTEGenerator

df = load_breast_cancer(as_frame=True).frame

def build_model():
    return Pipeline([
        ("scale", StandardScaler()),
        ("mlp", MLPClassifier(hidden_layer_sizes=(128, 64, 32), max_iter=300, early_stopping=True)),
    ])

config = ExperimentConfig(
    task_type="classification",
    data_type="tabular",
    target_column="target",
    metric=MetricSpec("f1_macro", "maximize"),
    alpha=AlphaSpec(0.0, 0.5),
    repetitions=10,
    search_budget=6,
    search_method="grid",
    base_seed=42,
    artifact_dir="datatunner_artifacts/breast_cancer",
)

report = DataTunnerTabular(config).run(
    data=df,
    model_factory=build_model,
    generator=SMOTEGenerator("target"),
)
```

## Minimal image example

See `examples/image_oxford_pets_augmentation.py`. It uses Oxford-IIIT Pet binary labels and the native `DataTunnerImage` API.

## Citation

```bibtex
@software{datatunner2026,
  author = {Rocha, Leandro Costa and Maia de Almeida, Gustavo},
  title = {DataTunner: Optimal Artificial Data Proportion for Deep Learning},
  year = {2026},
  url = {https://github.com/leandrocrx/datatunner}
}
```

## Scientific warning

DataTunner provides engineering controls for alpha search, provenance, repeated seeds, validation isolation, and final testing. Scientific validity still depends on the dataset, baselines, number of repetitions, statistical analysis, and interpretation.

Custom training hooks receive the validation dataset during candidate trials. During the
final fit the validation argument is `None`; the test dataset is only passed to the
evaluation hook and is never exposed to the training hook. Image transforms must produce
images with the configured `image_size`. The tabular hook has the signature
`train_function(model, train_data, validation_data)`, while the image hook has the
signature `train_function(model, dataset, validation_dataset, config, seeds)`.

# DataTunner 4.0.0 (Português)

**Plataforma científica para a proporção ótima de dados artificiais em experimentos de
aprendizado profundo.**

O DataTunner determina a fração ótima de dados artificiais `alpha` (`alpha*`) sob um
protocolo de validação isolado, com proveniência completa, sumários estatísticos e teste
final em conjunto separado (holdout). A ferramenta suporta dados tabulares (SMOTE e
CTGAN) e dados de imagens (aumento de dados materializado), além de persistir cada
modelo treinado para que o melhor resultado possa ser escolhido a partir dos relatórios.

```text
alpha = n_sinteticos / (n_reais + n_sinteticos)
```

## Novidades da versão 4.0.0

- **Dois alphas selecionados por experimento** — `alpha*` (melhor custo-benefício) e
  `alpha**` (melhor resultado efetivo), ambos validados no conjunto de teste separado.
- **APIs públicas explícitas** — `DataTunnerTabular` e `DataTunnerImage`, com importação
  tardia para que instalações tabulares não exijam PyTorch.
- **Persistência de modelos** — defina `artifact_dir` para salvar cada modelo treinado por
  alpha e repetição, os modelos finais dos alphas selecionados e um catálogo
  `models_index.json` para escolher o melhor resultado com base nos relatórios;
  `datatunner.load_model` recarrega qualquer artefato.
- **Python 3.10+** — tipagem moderna em todo o pacote.

## Instalação

```bash
python -m pip install "datatunner[full]==4.0.0"   # tudo (torch, SDV, imbalanced-learn)
```

Extras por mecanismo mantêm a instalação base leve:

```bash
pip install datatunner            # apenas o núcleo (numpy, pandas, sklearn, scipy, matplotlib)
pip install "datatunner[tabular]" # + imbalanced-learn e SDV/SDMetrics (SMOTE, CTGAN)
pip install "datatunner[image]"   # + torch / torchvision / Pillow (aumento de dados)
```

Para desenvolvimento local e a suíte completa de testes, instale `.[dev,full]`. O recurso
de imagens é opcional; testes exclusivos de imagem são ignorados quando o PyTorch não
está instalado.

## Duas seleções de alpha

Cada experimento reporta dois alphas:

- `alpha*` (`report.alpha_star` / `report.selected`): o candidato de **melhor
  custo-benefício** — o menor alpha cujo intervalo de confiança na validação se sobrepõe
  à melhor média observada, de modo que mais dados sintéticos não trariam ganho
  estatisticamente distinguível.
- `alpha**` (`report.alpha_star_star` / `report.best_effective`): o candidato de **melhor
  resultado efetivo** — o alpha com a melhor média observada, independentemente do custo
  em dados sintéticos.

Ambos são validados no conjunto de teste separado: `report.final_test` (alpha*) e
`report.final_test_alpha_star_star` (alpha**).

## Artefatos de modelos salvos

Defina `artifact_dir` para persistir cada modelo treinado (por alpha e repetição) e os
modelos finais dos dois alphas selecionados:

```python
config = ExperimentConfig(
    task_type="classification",
    data_type="tabular",
    target_column="target",
    metric=MetricSpec("f1_macro", "maximize"),
    artifact_dir="datatunner_artifacts/breast_cancer",
    # ...
)

report = DataTunnerTabular(config).run(df, build_model, SMOTEGenerator("target"))

# Os caminhos são expostos pelo relatório, incluindo a melhor tentativa de cada alpha.
best_path = report.candidates[0].best_model_path
final_path = report.final_test.model_path

from datatunner import load_model

model = load_model(best_path)
```

O diretório da execução contém:

- `models/alpha_<valor>/candidate_rep<r>_seed<s>.*` — um artefato por tentativa candidata.
- `models/final/alpha_star_alpha_<valor>.*` e `models/final/alpha_star_star_alpha_<valor>.*`
  — os modelos finais dos alphas selecionados.
- `models_index.json` — catálogo que associa cada artefato ao seu alpha, semente, status e
  valor de métrica, permitindo escolher o melhor resultado a partir dos relatórios.
- `experiment_report.json` — relatório completo retornado por `run`.

Estimadores tabulares são armazenados com `pickle` (`.pkl`); módulos PyTorch são
armazenados como `state_dict` (`.pt`) e exigem a mesma arquitetura via `model_factory` ao
carregar com `load_model(path, model_factory=...)`. Artefatos em pickle executam código ao
serem carregados; carregue apenas arquivos produzidos pelo seu próprio experimento.

## Exemplo mínimo tabular

```python
from sklearn.datasets import load_breast_cancer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPClassifier
from datatunner import AlphaSpec, ExperimentConfig, MetricSpec, DataTunnerTabular
from datatunner.tabular.generators import SMOTEGenerator

df = load_breast_cancer(as_frame=True).frame

def build_model():
    return Pipeline([
        ("scale", StandardScaler()),
        ("mlp", MLPClassifier(hidden_layer_sizes=(128, 64, 32), max_iter=300, early_stopping=True)),
    ])

config = ExperimentConfig(
    task_type="classification",
    data_type="tabular",
    target_column="target",
    metric=MetricSpec("f1_macro", "maximize"),
    alpha=AlphaSpec(0.0, 0.5),
    repetitions=10,
    search_budget=6,
    search_method="grid",
    base_seed=42,
    artifact_dir="datatunner_artifacts/breast_cancer",
)

report = DataTunnerTabular(config).run(
    data=df,
    model_factory=build_model,
    generator=SMOTEGenerator("target"),
)
```

## Exemplo mínimo com imagens

Veja `examples/image_oxford_pets_augmentation.py`. O exemplo usa os rótulos binários do
Oxford-IIIT Pet e a API nativa `DataTunnerImage`.

## Citação

```bibtex
@software{datatunner2026,
  author = {Rocha, Leandro Costa and Maia de Almeida, Gustavo},
  title = {DataTunner: Optimal Artificial Data Proportion for Deep Learning},
  year = {2026},
  url = {https://github.com/leandrocrx/datatunner}
}
```

## Aviso científico

O DataTunner fornece controles de engenharia para busca de alpha, proveniência, sementes
repetidas, isolamento da validação e teste final. A validade científica ainda depende do
conjunto de dados, das linhas de base, do número de repetições, da análise estatística e
da interpretação.

Ganchos de treinamento personalizados recebem o conjunto de validação durante as
tentativas candidatas. No ajuste final o argumento de validação é `None`; o conjunto de
teste é passado apenas ao gancho de avaliação e nunca é exposto ao gancho de treinamento.
Transformações de imagem devem produzir imagens com o `image_size` configurado. O gancho
tabular tem a assinatura `train_function(model, train_data, validation_data)`, enquanto o
gancho de imagem tem a assinatura
`train_function(model, dataset, validation_dataset, config, seeds)`.
