Add files using upload-large-folder tool
Browse files- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/._data +0 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/.gitignore +22 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/.gitmodules +9 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CONFIG_DESCRIPTION.md +78 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/.gitignore +1 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/README.md +49 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py +81 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py +110 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py +153 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/.gitignore +1 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/LICENSE +201 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/License.txt +15 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/README.md +50 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/pipeline_ctabgan.py +80 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/requirements.txt +6 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/train_sample_ctabgan.py +108 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/tune_ctabgan.py +150 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/pipeline_tvae.py +80 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/train_sample_tvae.py +117 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/tune_tvae.py +153 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/LICENSE.md +21 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/README.md +99 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/_compat_run.py +6 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/agg_results.ipynb +315 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__init__.py +12 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/data.py +719 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/deep.py +168 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/env.py +39 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/metrics.py +158 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/util.py +433 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/requirements.txt +22 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm.sh +5 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm_docker.sh +5 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__init__.py +0 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_catboost.py +145 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_mlp.py +176 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds.py +121 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds_simple.py +130 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_simple.py +141 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/pipeline.py +112 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/resample_privacy.py +257 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/sample.py +160 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/train.py +158 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_evaluation_model.py +145 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__init__.py +2 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/gaussian_multinomial_diffsuion.py +993 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/modules.py +486 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/utils.py +174 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_sample_r0.py +75 -0
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_train.py +42 -0
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/._data
ADDED
|
Binary file (220 Bytes). View file
|
|
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/.gitignore
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.DS_Store
|
| 2 |
+
__pycache__/
|
| 3 |
+
catboost_info/
|
| 4 |
+
**/**.pt
|
| 5 |
+
**/**.ipynb
|
| 6 |
+
!agg_results.ipynb
|
| 7 |
+
**/**.npy
|
| 8 |
+
**/**.gz
|
| 9 |
+
**/**.sh
|
| 10 |
+
**/**.obj
|
| 11 |
+
**/**.png
|
| 12 |
+
**/**.tar
|
| 13 |
+
**/**.code-workspace
|
| 14 |
+
**/**.csv
|
| 15 |
+
exp/**/**/results_catboost.json
|
| 16 |
+
exp/**/**/results_mlp.json
|
| 17 |
+
|
| 18 |
+
configs/
|
| 19 |
+
data/
|
| 20 |
+
junk/
|
| 21 |
+
RF/
|
| 22 |
+
exps/
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/.gitmodules
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[submodule "ctgan"]
|
| 2 |
+
# path = CTGAN/CTGAN
|
| 3 |
+
url = https://github.com/sdv-dev/CTGAN
|
| 4 |
+
[submodule "ctabgan"]
|
| 5 |
+
# path = CTAB-GAN
|
| 6 |
+
url = https://github.com/Team-TUD/CTAB-GAN
|
| 7 |
+
[submodule "ctabgan+"]
|
| 8 |
+
# path = CTAB-GAN-Plus
|
| 9 |
+
url = https://github.com/Team-TUD/CTAB-GAN-Plus
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CONFIG_DESCRIPTION.md
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Description of .toml config for TabDDPM
|
| 2 |
+
First of all, `train.T` and `eval.T` denote preprocessing for training and for evaluation, respectively.
|
| 3 |
+
|
| 4 |
+
Here we list non-obvious parameters.
|
| 5 |
+
|
| 6 |
+
Main part:
|
| 7 |
+
- `seed = 0` -- evaluation seed (and training, but for training it is fixed to 0)
|
| 8 |
+
- `parent_dir = "exp/abalone/check"` -- exp folder
|
| 9 |
+
- `real_data_path = "data/abalone/"`
|
| 10 |
+
- `model_type = "mlp"` -- model type that approximates the reverse process
|
| 11 |
+
- `num_numerical_features ` -- a number of numerical features in dataset
|
| 12 |
+
- `device = "cuda:0"`
|
| 13 |
+
|
| 14 |
+
Model params:
|
| 15 |
+
- `is_y_cond` -- false for regression, true for classification
|
| 16 |
+
- `d_in` -- input dimension (not necessary, since scripts calculate it automatically)
|
| 17 |
+
- `num_calsses` -- zero for regression, a number of classes for classification
|
| 18 |
+
- `rtdl_params` -- MLP parameters
|
| 19 |
+
|
| 20 |
+
```toml
|
| 21 |
+
seed = 0
|
| 22 |
+
parent_dir = "exp/abalone/check"
|
| 23 |
+
real_data_path = "data/abalone/"
|
| 24 |
+
model_type = "mlp"
|
| 25 |
+
num_numerical_features = 7
|
| 26 |
+
device = "cuda:0"
|
| 27 |
+
|
| 28 |
+
[model_params]
|
| 29 |
+
is_y_cond = false
|
| 30 |
+
d_in = 11
|
| 31 |
+
num_classes = 0
|
| 32 |
+
|
| 33 |
+
[model_params.rtdl_params]
|
| 34 |
+
d_layers = [
|
| 35 |
+
256,
|
| 36 |
+
256,
|
| 37 |
+
]
|
| 38 |
+
dropout = 0.0
|
| 39 |
+
|
| 40 |
+
[diffusion_params]
|
| 41 |
+
num_timesteps = 1000
|
| 42 |
+
gaussian_loss_type = "mse"
|
| 43 |
+
scheduler = "cosine"
|
| 44 |
+
|
| 45 |
+
[train.main]
|
| 46 |
+
steps = 1000
|
| 47 |
+
lr = 0.001
|
| 48 |
+
weight_decay = 1e-05
|
| 49 |
+
batch_size = 4096
|
| 50 |
+
|
| 51 |
+
[train.T]
|
| 52 |
+
seed = 0
|
| 53 |
+
normalization = "quantile"
|
| 54 |
+
num_nan_policy = "__none__"
|
| 55 |
+
cat_nan_policy = "__none__"
|
| 56 |
+
cat_min_frequency = "__none__"
|
| 57 |
+
cat_encoding = "__none__"
|
| 58 |
+
y_policy = "default"
|
| 59 |
+
|
| 60 |
+
[sample]
|
| 61 |
+
num_samples = 20800
|
| 62 |
+
batch_size = 10000
|
| 63 |
+
seed = 0
|
| 64 |
+
|
| 65 |
+
[eval.type]
|
| 66 |
+
eval_model = "catboost"
|
| 67 |
+
eval_type = "synthetic"
|
| 68 |
+
|
| 69 |
+
[eval.T]
|
| 70 |
+
seed = 0
|
| 71 |
+
normalization = "__none__"
|
| 72 |
+
num_nan_policy = "__none__"
|
| 73 |
+
cat_nan_policy = "__none__"
|
| 74 |
+
cat_min_frequency = "__none__"
|
| 75 |
+
cat_encoding = "__none__"
|
| 76 |
+
y_policy = "default"
|
| 77 |
+
|
| 78 |
+
```
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
**/**.csv
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/README.md
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CTAB-GAN+
|
| 2 |
+
This is the official git paper [CTAB-GAN+: Enhancing Tabular Data Synthesis](https://arxiv.org/abs/2204.00401). Current code is without differential privacy part.
|
| 3 |
+
If you have any question, please contact `z.zhao-8@tudelft.nl` for more information.
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
## Prerequisite
|
| 7 |
+
|
| 8 |
+
The required package version
|
| 9 |
+
```
|
| 10 |
+
numpy==1.21.0
|
| 11 |
+
torch==1.9.1
|
| 12 |
+
pandas==1.2.4
|
| 13 |
+
sklearn==0.24.1
|
| 14 |
+
dython==0.6.4.post1
|
| 15 |
+
scipy==1.4.1
|
| 16 |
+
```
|
| 17 |
+
The sklean package in newer version has updated its function for `sklearn.mixture.BayesianGaussianMixture`. Therefore, user should use this proposed sklearn version to successfully run the code!
|
| 18 |
+
|
| 19 |
+
## Example
|
| 20 |
+
`Experiment_Script_Adult.ipynb` `Experiment_Script_king.ipynb` are two example notebooks for training CTAB-GAN+ with Adult (classification) and king (regression) datasets. The datasets are alread under `Real_Datasets` folder.
|
| 21 |
+
The evaluation code is also provided.
|
| 22 |
+
|
| 23 |
+
## Problem type
|
| 24 |
+
|
| 25 |
+
You can either indicate your dataset problem type as Classification, Regression. If there is no problem type, you can leave the problem type as None as follows:
|
| 26 |
+
```
|
| 27 |
+
problem_type= {None: None}
|
| 28 |
+
```
|
| 29 |
+
|
| 30 |
+
## For large dataset
|
| 31 |
+
|
| 32 |
+
If your dataset has large number of column, you may encounter the problem that our currnet code cannot encode all of your data since CTAB-GAN+ will wrap the encoded data into an image-like format. What you can do is changing the line 378 and 385 in `model/synthesizer/ctabgan_synthesizer.py`. The number in the `slide` list
|
| 33 |
+
```
|
| 34 |
+
sides = [4, 8, 16, 24, 32]
|
| 35 |
+
```
|
| 36 |
+
is the side size of image. You can enlarge the list to [4, 8, 16, 24, 32, 64] or [4, 8, 16, 24, 32, 64, 128] for accepting larger dataset.
|
| 37 |
+
|
| 38 |
+
## Bibtex
|
| 39 |
+
|
| 40 |
+
To cite this paper, you could use this bibtex
|
| 41 |
+
|
| 42 |
+
```
|
| 43 |
+
@article{zhao2022ctab,
|
| 44 |
+
title={CTAB-GAN+: Enhancing Tabular Data Synthesis},
|
| 45 |
+
author={Zhao, Zilong and Kunar, Aditya and Birke, Robert and Chen, Lydia Y},
|
| 46 |
+
journal={arXiv preprint arXiv:2204.00401},
|
| 47 |
+
year={2022}
|
| 48 |
+
}
|
| 49 |
+
```
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tomli
|
| 2 |
+
import shutil
|
| 3 |
+
import os
|
| 4 |
+
import argparse
|
| 5 |
+
from train_sample_ctabganp import train_ctabgan, sample_ctabgan
|
| 6 |
+
from scripts.eval_catboost import train_catboost
|
| 7 |
+
import zero
|
| 8 |
+
import lib
|
| 9 |
+
from model.ctabgan import CTABGAN
|
| 10 |
+
|
| 11 |
+
def load_config(path) :
|
| 12 |
+
with open(path, 'rb') as f:
|
| 13 |
+
return tomli.load(f)
|
| 14 |
+
|
| 15 |
+
def save_file(parent_dir, config_path):
|
| 16 |
+
try:
|
| 17 |
+
dst = os.path.join(parent_dir)
|
| 18 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 19 |
+
shutil.copyfile(os.path.abspath(config_path), dst)
|
| 20 |
+
except shutil.SameFileError:
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
def main():
|
| 24 |
+
parser = argparse.ArgumentParser()
|
| 25 |
+
parser.add_argument('--config', metavar='FILE')
|
| 26 |
+
parser.add_argument('--train', action='store_true', default=False)
|
| 27 |
+
parser.add_argument('--sample', action='store_true', default=False)
|
| 28 |
+
parser.add_argument('--eval', action='store_true', default=False)
|
| 29 |
+
parser.add_argument('--change_val', action='store_true', default=False)
|
| 30 |
+
|
| 31 |
+
args = parser.parse_args()
|
| 32 |
+
raw_config = lib.load_config(args.config)
|
| 33 |
+
timer = zero.Timer()
|
| 34 |
+
timer.run()
|
| 35 |
+
save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
|
| 36 |
+
ctabgan = None
|
| 37 |
+
if args.train:
|
| 38 |
+
ctabgan = train_ctabgan(
|
| 39 |
+
parent_dir=raw_config['parent_dir'],
|
| 40 |
+
real_data_path=raw_config['real_data_path'],
|
| 41 |
+
train_params=raw_config['train_params'],
|
| 42 |
+
change_val=args.change_val,
|
| 43 |
+
device=raw_config['device']
|
| 44 |
+
)
|
| 45 |
+
if args.sample:
|
| 46 |
+
sample_ctabgan(
|
| 47 |
+
synthesizer=ctabgan,
|
| 48 |
+
parent_dir=raw_config['parent_dir'],
|
| 49 |
+
real_data_path=raw_config['real_data_path'],
|
| 50 |
+
num_samples=raw_config['sample']['num_samples'],
|
| 51 |
+
train_params=raw_config['train_params'],
|
| 52 |
+
change_val=args.change_val,
|
| 53 |
+
seed=raw_config['sample']['seed'],
|
| 54 |
+
device=raw_config['device']
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
|
| 58 |
+
if args.eval:
|
| 59 |
+
if raw_config['eval']['type']['eval_model'] == 'catboost':
|
| 60 |
+
train_catboost(
|
| 61 |
+
parent_dir=raw_config['parent_dir'],
|
| 62 |
+
real_data_path=raw_config['real_data_path'],
|
| 63 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 64 |
+
T_dict=raw_config['eval']['T'],
|
| 65 |
+
seed=raw_config['seed'],
|
| 66 |
+
change_val=args.change_val
|
| 67 |
+
)
|
| 68 |
+
# elif raw_config['eval']['type']['eval_model'] == 'mlp':
|
| 69 |
+
# train_mlp(
|
| 70 |
+
# parent_dir=raw_config['parent_dir'],
|
| 71 |
+
# real_data_path=raw_config['real_data_path'],
|
| 72 |
+
# eval_type=raw_config['eval']['type']['eval_type'],
|
| 73 |
+
# T_dict=raw_config['eval']['T'],
|
| 74 |
+
# seed=raw_config['seed'],
|
| 75 |
+
# change_val=args.change_val
|
| 76 |
+
# )
|
| 77 |
+
|
| 78 |
+
print(f'Elapsed time: {str(timer)}')
|
| 79 |
+
|
| 80 |
+
if __name__ == '__main__':
|
| 81 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import lib
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import argparse
|
| 5 |
+
from model.ctabgan import CTABGAN
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import torch
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def train_ctabgan(
|
| 12 |
+
parent_dir,
|
| 13 |
+
real_data_path,
|
| 14 |
+
train_params = {"batch_size": 512},
|
| 15 |
+
change_val=False,
|
| 16 |
+
device = "cpu"
|
| 17 |
+
):
|
| 18 |
+
real_data_path = Path(real_data_path)
|
| 19 |
+
parent_dir = Path(parent_dir)
|
| 20 |
+
device = torch.device(device)
|
| 21 |
+
|
| 22 |
+
if change_val:
|
| 23 |
+
X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
|
| 24 |
+
else:
|
| 25 |
+
X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
|
| 26 |
+
|
| 27 |
+
X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
|
| 28 |
+
|
| 29 |
+
X.columns = [str(_) for _ in X.columns]
|
| 30 |
+
|
| 31 |
+
ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name]
|
| 32 |
+
train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
|
| 33 |
+
|
| 34 |
+
print(train_params)
|
| 35 |
+
synthesizer = CTABGAN(
|
| 36 |
+
df = X,
|
| 37 |
+
test_ratio = 0.0,
|
| 38 |
+
**ctabgan_params,
|
| 39 |
+
**train_params,
|
| 40 |
+
device=device
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
synthesizer.fit()
|
| 44 |
+
|
| 45 |
+
# save_ctabgan(synthesizer, parent_dir)
|
| 46 |
+
with open(parent_dir / "ctabgan.obj", "wb") as f:
|
| 47 |
+
pickle.dump(synthesizer, f)
|
| 48 |
+
|
| 49 |
+
return synthesizer
|
| 50 |
+
|
| 51 |
+
def sample_ctabgan(
|
| 52 |
+
synthesizer,
|
| 53 |
+
parent_dir,
|
| 54 |
+
real_data_path,
|
| 55 |
+
num_samples,
|
| 56 |
+
train_params = {"batch_size": 512},
|
| 57 |
+
change_val=False,
|
| 58 |
+
device="cpu",
|
| 59 |
+
seed=0
|
| 60 |
+
):
|
| 61 |
+
real_data_path = Path(real_data_path)
|
| 62 |
+
parent_dir = Path(parent_dir)
|
| 63 |
+
device = torch.device(device)
|
| 64 |
+
|
| 65 |
+
if change_val:
|
| 66 |
+
X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
|
| 67 |
+
else:
|
| 68 |
+
X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
|
| 69 |
+
|
| 70 |
+
X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
|
| 71 |
+
|
| 72 |
+
X.columns = [str(_) for _ in X.columns]
|
| 73 |
+
|
| 74 |
+
ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name]
|
| 75 |
+
|
| 76 |
+
cat_features = ctabgan_params["categorical_columns"]
|
| 77 |
+
# if synthesizer is None:
|
| 78 |
+
# synthesizer = load_ctabgan(X, ctabgan_params, train_params, parent_dir)
|
| 79 |
+
with open(parent_dir / "ctabgan.obj", 'rb') as f:
|
| 80 |
+
synthesizer = pickle.load(f)
|
| 81 |
+
synthesizer.synthesizer.generator = synthesizer.synthesizer.generator.to(device)
|
| 82 |
+
gen_data = synthesizer.generate_samples(num_samples, seed)
|
| 83 |
+
|
| 84 |
+
y = gen_data['y'].values
|
| 85 |
+
if len(np.unique(y)) == 1:
|
| 86 |
+
y[0] = 0
|
| 87 |
+
y[1] = 1
|
| 88 |
+
|
| 89 |
+
X_cat = gen_data[cat_features].drop('y', axis=1, errors="ignore").values if len(cat_features) else None
|
| 90 |
+
X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
|
| 91 |
+
|
| 92 |
+
if X_num_train is not None:
|
| 93 |
+
np.save(parent_dir / 'X_num_train', X_num.astype(float))
|
| 94 |
+
if X_cat_train is not None:
|
| 95 |
+
np.save(parent_dir / 'X_cat_train', X_cat.astype(str))
|
| 96 |
+
np.save(parent_dir / 'y_train', y.astype(float).astype(int)) # only clf !!!
|
| 97 |
+
|
| 98 |
+
def main():
|
| 99 |
+
parser = argparse.ArgumentParser()
|
| 100 |
+
parser.add_argument('real_data_path', type=str)
|
| 101 |
+
parser.add_argument('parent_dir', type=str)
|
| 102 |
+
parser.add_argument('train_size', type=int)
|
| 103 |
+
args = parser.parse_args()
|
| 104 |
+
|
| 105 |
+
ctabgan = train_ctabgan(args.parent_dir, args.real_data_path, change_val=True)
|
| 106 |
+
sample_ctabgan(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
if __name__ == '__main__':
|
| 110 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from multiprocessing.sharedctypes import RawValue
|
| 2 |
+
from random import random
|
| 3 |
+
import tempfile
|
| 4 |
+
import subprocess
|
| 5 |
+
import lib
|
| 6 |
+
import os
|
| 7 |
+
import optuna
|
| 8 |
+
import argparse
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from train_sample_ctabganp import train_ctabgan, sample_ctabgan
|
| 11 |
+
from scripts.eval_catboost import train_catboost
|
| 12 |
+
|
| 13 |
+
parser = argparse.ArgumentParser()
|
| 14 |
+
parser.add_argument('data_path', type=str)
|
| 15 |
+
parser.add_argument('train_size', type=int)
|
| 16 |
+
parser.add_argument('eval_type', type=str)
|
| 17 |
+
parser.add_argument('device', type=str)
|
| 18 |
+
|
| 19 |
+
args = parser.parse_args()
|
| 20 |
+
real_data_path = args.data_path
|
| 21 |
+
eval_type = args.eval_type
|
| 22 |
+
train_size = args.train_size
|
| 23 |
+
device = args.device
|
| 24 |
+
assert eval_type in ('merged', 'synthetic')
|
| 25 |
+
|
| 26 |
+
def objective(trial):
|
| 27 |
+
|
| 28 |
+
lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
|
| 29 |
+
|
| 30 |
+
def suggest_dim(name):
|
| 31 |
+
t = trial.suggest_int(name, d_min, d_max)
|
| 32 |
+
return 2 ** t
|
| 33 |
+
|
| 34 |
+
# construct model
|
| 35 |
+
min_n_layers, max_n_layers, d_min, d_max = 1, 4, 6, 8
|
| 36 |
+
n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers)
|
| 37 |
+
d_first = [suggest_dim('d_first')] if n_layers else []
|
| 38 |
+
d_middle = (
|
| 39 |
+
[suggest_dim('d_middle')] * (n_layers - 2)
|
| 40 |
+
if n_layers > 2
|
| 41 |
+
else []
|
| 42 |
+
)
|
| 43 |
+
d_last = [suggest_dim('d_last')] if n_layers > 1 else []
|
| 44 |
+
d_layers = d_first + d_middle + d_last
|
| 45 |
+
####
|
| 46 |
+
|
| 47 |
+
steps = trial.suggest_categorical('steps', [1000, 5000, 10000])
|
| 48 |
+
# steps = trial.suggest_categorical('steps', [10])
|
| 49 |
+
batch_size = 2 ** trial.suggest_int('batch_size', 9, 11)
|
| 50 |
+
random_dim = 2 ** trial.suggest_int('random_dim', 4, 7)
|
| 51 |
+
num_channels = 2 ** trial.suggest_int('num_channels', 4, 6)
|
| 52 |
+
|
| 53 |
+
# steps = trial.suggest_categorical('steps', [1000])
|
| 54 |
+
|
| 55 |
+
num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3)))
|
| 56 |
+
|
| 57 |
+
train_params = {
|
| 58 |
+
"lr": lr,
|
| 59 |
+
"epochs": steps,
|
| 60 |
+
"class_dim": d_layers,
|
| 61 |
+
"batch_size": batch_size,
|
| 62 |
+
"random_dim": random_dim,
|
| 63 |
+
"num_channels": num_channels
|
| 64 |
+
}
|
| 65 |
+
trial.set_user_attr("train_params", train_params)
|
| 66 |
+
trial.set_user_attr("num_samples", num_samples)
|
| 67 |
+
|
| 68 |
+
score = 0.0
|
| 69 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 70 |
+
dir_ = Path(dir_)
|
| 71 |
+
ctabgan = train_ctabgan(
|
| 72 |
+
parent_dir=dir_,
|
| 73 |
+
real_data_path=real_data_path,
|
| 74 |
+
train_params=train_params,
|
| 75 |
+
change_val=True,
|
| 76 |
+
device=device
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
for sample_seed in range(5):
|
| 80 |
+
sample_ctabgan(
|
| 81 |
+
ctabgan,
|
| 82 |
+
parent_dir=dir_,
|
| 83 |
+
real_data_path=real_data_path,
|
| 84 |
+
num_samples=num_samples,
|
| 85 |
+
train_params=train_params,
|
| 86 |
+
change_val=True,
|
| 87 |
+
seed=sample_seed,
|
| 88 |
+
device=device
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
T_dict = {
|
| 92 |
+
"seed": 0,
|
| 93 |
+
"normalization": None,
|
| 94 |
+
"num_nan_policy": None,
|
| 95 |
+
"cat_nan_policy": None,
|
| 96 |
+
"cat_min_frequency": None,
|
| 97 |
+
"cat_encoding": None,
|
| 98 |
+
"y_policy": "default"
|
| 99 |
+
}
|
| 100 |
+
metrics = train_catboost(
|
| 101 |
+
parent_dir=dir_,
|
| 102 |
+
real_data_path=real_data_path,
|
| 103 |
+
eval_type=eval_type,
|
| 104 |
+
T_dict=T_dict,
|
| 105 |
+
change_val=True,
|
| 106 |
+
seed = 0
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
score += metrics.get_val_score()
|
| 110 |
+
return score / 5
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
study = optuna.create_study(
|
| 114 |
+
direction='maximize',
|
| 115 |
+
sampler=optuna.samplers.TPESampler(seed=0),
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
study.optimize(objective, n_trials=35, show_progress_bar=True)
|
| 119 |
+
|
| 120 |
+
os.makedirs(f"exp/{Path(real_data_path).name}/ctabgan-plus/", exist_ok=True)
|
| 121 |
+
config = {
|
| 122 |
+
"parent_dir": f"exp/{Path(real_data_path).name}/ctabgan-plus/",
|
| 123 |
+
"real_data_path": real_data_path,
|
| 124 |
+
"seed": 0,
|
| 125 |
+
"device": args.device,
|
| 126 |
+
"train_params": study.best_trial.user_attrs["train_params"],
|
| 127 |
+
"sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]},
|
| 128 |
+
"eval": {
|
| 129 |
+
"type": {"eval_model": "catboost", "eval_type": eval_type},
|
| 130 |
+
"T": {
|
| 131 |
+
"seed": 0,
|
| 132 |
+
"normalization": None,
|
| 133 |
+
"num_nan_policy": None,
|
| 134 |
+
"cat_nan_policy": None,
|
| 135 |
+
"cat_min_frequency": None,
|
| 136 |
+
"cat_encoding": None,
|
| 137 |
+
"y_policy": "default"
|
| 138 |
+
},
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
train_ctabgan(
|
| 143 |
+
parent_dir=f"exp/{Path(real_data_path).name}/ctabgan-plus/",
|
| 144 |
+
real_data_path=real_data_path,
|
| 145 |
+
train_params=study.best_trial.user_attrs["train_params"],
|
| 146 |
+
change_val=False,
|
| 147 |
+
device=device
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
lib.dump_config(config, config["parent_dir"]+"config.toml")
|
| 151 |
+
|
| 152 |
+
subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}',
|
| 153 |
+
'10', "ctabgan-plus", eval_type, "catboost", "5"], check=True)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/.gitignore
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
**/**.csv
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/License.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Distributed learning systems Lab at TU Delft & Generatrix, hereby disclaims all copyright interest in the program "CTAB-GAN" (which synthesizes tabular data)
|
| 2 |
+
|
| 3 |
+
Copyright 2020-2022 Distributed learning systems Lab at TU Delft & Generatrix.
|
| 4 |
+
|
| 5 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 6 |
+
you may not use this file except in compliance with the License.
|
| 7 |
+
You may obtain a copy of the License at
|
| 8 |
+
|
| 9 |
+
https://www.apache.org/licenses/LICENSE-2.0
|
| 10 |
+
|
| 11 |
+
Unless required by applicable law or agreed to in writing, software
|
| 12 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 13 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 14 |
+
See the License for the specific language governing permissions and
|
| 15 |
+
limitations under the License.
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/README.md
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# CTAB-GAN
|
| 2 |
+
This is the official git paper [CTAB-GAN: Effective Table Data Synthesizing](https://proceedings.mlr.press/v157/zhao21a.html). The paper is published on Asian Conference on Machine Learning (ACML 2021), please check our pdf on PMLR website for our newest version of [paper](https://proceedings.mlr.press/v157/zhao21a.html), it adds more content on time consumption analysis of training CTAB-GAN. If you have any question, please contact `z.zhao-8@tudelft.nl` for more information.
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
## Prerequisite
|
| 6 |
+
|
| 7 |
+
The required package version
|
| 8 |
+
```
|
| 9 |
+
numpy==1.21.0
|
| 10 |
+
torch==1.9.1
|
| 11 |
+
pandas==1.2.4
|
| 12 |
+
sklearn==0.24.1
|
| 13 |
+
dython==0.6.4.post1
|
| 14 |
+
scipy==1.4.1
|
| 15 |
+
```
|
| 16 |
+
|
| 17 |
+
## Example
|
| 18 |
+
`Experiment_Script_Adult.ipynb` is an example notebook for training CTAB-GAN with Adult dataset. The dataset is alread under `Real_Datasets` folder.
|
| 19 |
+
The evaluation code is also provided.
|
| 20 |
+
|
| 21 |
+
## For large dataset
|
| 22 |
+
|
| 23 |
+
If your dataset has large number of column, you may encounter the problem that our currnet code cannot encode all of your data since CTAB-GAN will wrap the encoded data into an image-like format. What you can do is changing the line 341 and 348 in `model/synthesizer/ctabgan_synthesizer.py`. The number in the `slide` list
|
| 24 |
+
```
|
| 25 |
+
sides = [4, 8, 16, 24, 32]
|
| 26 |
+
```
|
| 27 |
+
is the side size of image. You can enlarge the list to [4, 8, 16, 24, 32, 64] or [4, 8, 16, 24, 32, 64, 128] for accepting larger dataset.
|
| 28 |
+
|
| 29 |
+
## Bibtex
|
| 30 |
+
|
| 31 |
+
To cite this paper, you could use this bibtex
|
| 32 |
+
|
| 33 |
+
```
|
| 34 |
+
@InProceedings{zhao21,
|
| 35 |
+
title = {CTAB-GAN: Effective Table Data Synthesizing},
|
| 36 |
+
author = {Zhao, Zilong and Kunar, Aditya and Birke, Robert and Chen, Lydia Y.},
|
| 37 |
+
booktitle = {Proceedings of The 13th Asian Conference on Machine Learning},
|
| 38 |
+
pages = {97--112},
|
| 39 |
+
year = {2021},
|
| 40 |
+
editor = {Balasubramanian, Vineeth N. and Tsang, Ivor},
|
| 41 |
+
volume = {157},
|
| 42 |
+
series = {Proceedings of Machine Learning Research},
|
| 43 |
+
month = {17--19 Nov},
|
| 44 |
+
publisher = {PMLR},
|
| 45 |
+
pdf = {https://proceedings.mlr.press/v157/zhao21a/zhao21a.pdf},
|
| 46 |
+
url = {https://proceedings.mlr.press/v157/zhao21a.html}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
```
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/pipeline_ctabgan.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tomli
|
| 2 |
+
import shutil
|
| 3 |
+
import os
|
| 4 |
+
import argparse
|
| 5 |
+
from train_sample_ctabgan import train_ctabgan, sample_ctabgan
|
| 6 |
+
from scripts.eval_catboost import train_catboost
|
| 7 |
+
import zero
|
| 8 |
+
import lib
|
| 9 |
+
|
| 10 |
+
def load_config(path) :
|
| 11 |
+
with open(path, 'rb') as f:
|
| 12 |
+
return tomli.load(f)
|
| 13 |
+
|
| 14 |
+
def save_file(parent_dir, config_path):
|
| 15 |
+
try:
|
| 16 |
+
dst = os.path.join(parent_dir)
|
| 17 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 18 |
+
shutil.copyfile(os.path.abspath(config_path), dst)
|
| 19 |
+
except shutil.SameFileError:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
parser = argparse.ArgumentParser()
|
| 24 |
+
parser.add_argument('--config', metavar='FILE')
|
| 25 |
+
parser.add_argument('--train', action='store_true', default=False)
|
| 26 |
+
parser.add_argument('--sample', action='store_true', default=False)
|
| 27 |
+
parser.add_argument('--eval', action='store_true', default=False)
|
| 28 |
+
parser.add_argument('--change_val', action='store_true', default=False)
|
| 29 |
+
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
raw_config = lib.load_config(args.config)
|
| 32 |
+
timer = zero.Timer()
|
| 33 |
+
timer.run()
|
| 34 |
+
save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
|
| 35 |
+
ctabgan = None
|
| 36 |
+
if args.train:
|
| 37 |
+
ctabgan = train_ctabgan(
|
| 38 |
+
parent_dir=raw_config['parent_dir'],
|
| 39 |
+
real_data_path=raw_config['real_data_path'],
|
| 40 |
+
train_params=raw_config['train_params'],
|
| 41 |
+
change_val=args.change_val,
|
| 42 |
+
device=raw_config['device']
|
| 43 |
+
)
|
| 44 |
+
if args.sample:
|
| 45 |
+
sample_ctabgan(
|
| 46 |
+
synthesizer=ctabgan,
|
| 47 |
+
parent_dir=raw_config['parent_dir'],
|
| 48 |
+
real_data_path=raw_config['real_data_path'],
|
| 49 |
+
num_samples=raw_config['sample']['num_samples'],
|
| 50 |
+
train_params=raw_config['train_params'],
|
| 51 |
+
change_val=args.change_val,
|
| 52 |
+
seed=raw_config['sample']['seed'],
|
| 53 |
+
device=raw_config['device']
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
|
| 57 |
+
if args.eval:
|
| 58 |
+
if raw_config['eval']['type']['eval_model'] == 'catboost':
|
| 59 |
+
train_catboost(
|
| 60 |
+
parent_dir=raw_config['parent_dir'],
|
| 61 |
+
real_data_path=raw_config['real_data_path'],
|
| 62 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 63 |
+
T_dict=raw_config['eval']['T'],
|
| 64 |
+
seed=raw_config['seed'],
|
| 65 |
+
change_val=args.change_val
|
| 66 |
+
)
|
| 67 |
+
# elif raw_config['eval']['type']['eval_model'] == 'mlp':
|
| 68 |
+
# train_mlp(
|
| 69 |
+
# parent_dir=raw_config['parent_dir'],
|
| 70 |
+
# real_data_path=raw_config['real_data_path'],
|
| 71 |
+
# eval_type=raw_config['eval']['type']['eval_type'],
|
| 72 |
+
# T_dict=raw_config['eval']['T'],
|
| 73 |
+
# seed=raw_config['seed'],
|
| 74 |
+
# change_val=args.change_val
|
| 75 |
+
# )
|
| 76 |
+
|
| 77 |
+
print(f'Elapsed time: {str(timer)}')
|
| 78 |
+
|
| 79 |
+
if __name__ == '__main__':
|
| 80 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy==1.21.0
|
| 2 |
+
torch==1.9.1
|
| 3 |
+
pandas==1.2.4
|
| 4 |
+
sklearn==0.24.1
|
| 5 |
+
dython==0.6.4.post1
|
| 6 |
+
scipy==1.4.1
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/train_sample_ctabgan.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import lib
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import argparse
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from model.ctabgan import CTABGAN
|
| 7 |
+
import torch
|
| 8 |
+
import pickle
|
| 9 |
+
|
| 10 |
+
def train_ctabgan(
|
| 11 |
+
parent_dir,
|
| 12 |
+
real_data_path,
|
| 13 |
+
train_params = {"batch_size": 512},
|
| 14 |
+
change_val=False,
|
| 15 |
+
device = "cpu"
|
| 16 |
+
):
|
| 17 |
+
real_data_path = Path(real_data_path)
|
| 18 |
+
parent_dir = Path(parent_dir)
|
| 19 |
+
device = torch.device(device)
|
| 20 |
+
|
| 21 |
+
if change_val:
|
| 22 |
+
X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
|
| 23 |
+
else:
|
| 24 |
+
X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
|
| 25 |
+
|
| 26 |
+
X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
|
| 27 |
+
|
| 28 |
+
X.columns = [str(_) for _ in X.columns]
|
| 29 |
+
|
| 30 |
+
ctabgan_params = lib.load_json("CTAB-GAN/columns.json")[real_data_path.name]
|
| 31 |
+
train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
|
| 32 |
+
|
| 33 |
+
print(train_params)
|
| 34 |
+
synthesizer = CTABGAN(
|
| 35 |
+
df = X,
|
| 36 |
+
test_ratio = 0.0,
|
| 37 |
+
**ctabgan_params,
|
| 38 |
+
**train_params,
|
| 39 |
+
device=device
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
synthesizer.fit()
|
| 43 |
+
|
| 44 |
+
# save_ctabgan(synthesizer, parent_dir)
|
| 45 |
+
with open(parent_dir / "ctabgan.obj", "wb") as f:
|
| 46 |
+
pickle.dump(synthesizer, f)
|
| 47 |
+
|
| 48 |
+
return synthesizer
|
| 49 |
+
|
| 50 |
+
def sample_ctabgan(
|
| 51 |
+
synthesizer,
|
| 52 |
+
parent_dir,
|
| 53 |
+
real_data_path,
|
| 54 |
+
num_samples,
|
| 55 |
+
train_params = {"batch_size": 512},
|
| 56 |
+
change_val=False,
|
| 57 |
+
device="cpu",
|
| 58 |
+
seed=0
|
| 59 |
+
):
|
| 60 |
+
real_data_path = Path(real_data_path)
|
| 61 |
+
parent_dir = Path(parent_dir)
|
| 62 |
+
device = torch.device(device)
|
| 63 |
+
|
| 64 |
+
if change_val:
|
| 65 |
+
X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
|
| 66 |
+
else:
|
| 67 |
+
X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
|
| 68 |
+
|
| 69 |
+
X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
|
| 70 |
+
|
| 71 |
+
X.columns = [str(_) for _ in X.columns]
|
| 72 |
+
|
| 73 |
+
ctabgan_params = lib.load_json("CTAB-GAN/columns.json")[real_data_path.name]
|
| 74 |
+
|
| 75 |
+
cat_features = ctabgan_params["categorical_columns"]
|
| 76 |
+
# if synthesizer is None:
|
| 77 |
+
# synthesizer = load_ctabgan(X, ctabgan_params, train_params, parent_dir)
|
| 78 |
+
with open(parent_dir / "ctabgan.obj", 'rb') as f:
|
| 79 |
+
synthesizer = pickle.load(f)
|
| 80 |
+
synthesizer.synthesizer.generator = synthesizer.synthesizer.generator.to(device)
|
| 81 |
+
gen_data = synthesizer.generate_samples(num_samples, seed)
|
| 82 |
+
|
| 83 |
+
y = gen_data['y'].values
|
| 84 |
+
if len(np.unique(y)) == 1:
|
| 85 |
+
y[0] = 1
|
| 86 |
+
|
| 87 |
+
X_cat = gen_data[cat_features].drop('y', axis=1).values if len(cat_features) else None
|
| 88 |
+
X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
|
| 89 |
+
|
| 90 |
+
if X_num_train is not None:
|
| 91 |
+
np.save(parent_dir / 'X_num_train', X_num.astype(float))
|
| 92 |
+
if X_cat_train is not None:
|
| 93 |
+
np.save(parent_dir / 'X_cat_train', X_cat.astype(str))
|
| 94 |
+
np.save(parent_dir / 'y_train', y.astype(float).astype(int)) # only clf !!!
|
| 95 |
+
|
| 96 |
+
def main():
|
| 97 |
+
parser = argparse.ArgumentParser()
|
| 98 |
+
parser.add_argument('real_data_path', type=str)
|
| 99 |
+
parser.add_argument('parent_dir', type=str)
|
| 100 |
+
parser.add_argument('train_size', type=int)
|
| 101 |
+
args = parser.parse_args()
|
| 102 |
+
|
| 103 |
+
ctabgan = train_ctabgan(args.parent_dir, args.real_data_path, change_val=True)
|
| 104 |
+
sample_ctabgan(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == '__main__':
|
| 108 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/tune_ctabgan.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from multiprocessing.sharedctypes import RawValue
|
| 2 |
+
import tempfile
|
| 3 |
+
import subprocess
|
| 4 |
+
import lib
|
| 5 |
+
import os
|
| 6 |
+
import optuna
|
| 7 |
+
import argparse
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from train_sample_ctabgan import train_ctabgan, sample_ctabgan
|
| 10 |
+
from scripts.eval_catboost import train_catboost
|
| 11 |
+
|
| 12 |
+
parser = argparse.ArgumentParser()
|
| 13 |
+
parser.add_argument('data_path', type=str)
|
| 14 |
+
parser.add_argument('train_size', type=int)
|
| 15 |
+
parser.add_argument('eval_type', type=str)
|
| 16 |
+
parser.add_argument('device', type=str)
|
| 17 |
+
|
| 18 |
+
args = parser.parse_args()
|
| 19 |
+
real_data_path = args.data_path
|
| 20 |
+
eval_type = args.eval_type
|
| 21 |
+
train_size = args.train_size
|
| 22 |
+
device = args.device
|
| 23 |
+
assert eval_type in ('merged', 'synthetic')
|
| 24 |
+
|
| 25 |
+
def objective(trial):
|
| 26 |
+
|
| 27 |
+
lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
|
| 28 |
+
|
| 29 |
+
def suggest_dim(name):
|
| 30 |
+
t = trial.suggest_int(name, d_min, d_max)
|
| 31 |
+
return 2 ** t
|
| 32 |
+
|
| 33 |
+
# construct model
|
| 34 |
+
min_n_layers, max_n_layers, d_min, d_max = 1, 4, 6, 8
|
| 35 |
+
n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers)
|
| 36 |
+
d_first = [suggest_dim('d_first')] if n_layers else []
|
| 37 |
+
d_middle = (
|
| 38 |
+
[suggest_dim('d_middle')] * (n_layers - 2)
|
| 39 |
+
if n_layers > 2
|
| 40 |
+
else []
|
| 41 |
+
)
|
| 42 |
+
d_last = [suggest_dim('d_last')] if n_layers > 1 else []
|
| 43 |
+
d_layers = d_first + d_middle + d_last
|
| 44 |
+
####
|
| 45 |
+
|
| 46 |
+
steps = trial.suggest_categorical('steps', [1000, 5000, 10000])
|
| 47 |
+
# steps = trial.suggest_categorical('steps', [10])
|
| 48 |
+
batch_size = 2 ** trial.suggest_int('batch_size', 9, 11)
|
| 49 |
+
random_dim = 2 ** trial.suggest_int('random_dim', 4, 7)
|
| 50 |
+
num_channels = 2 ** trial.suggest_int('num_channels', 4, 6)
|
| 51 |
+
|
| 52 |
+
num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3)))
|
| 53 |
+
|
| 54 |
+
train_params = {
|
| 55 |
+
"lr": lr,
|
| 56 |
+
"epochs": steps,
|
| 57 |
+
"class_dim": d_layers,
|
| 58 |
+
"batch_size": batch_size,
|
| 59 |
+
"random_dim": random_dim,
|
| 60 |
+
"num_channels": num_channels
|
| 61 |
+
}
|
| 62 |
+
trial.set_user_attr("train_params", train_params)
|
| 63 |
+
trial.set_user_attr("num_samples", num_samples)
|
| 64 |
+
|
| 65 |
+
score = 0.0
|
| 66 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 67 |
+
dir_ = Path(dir_)
|
| 68 |
+
ctabgan = train_ctabgan(
|
| 69 |
+
parent_dir=dir_,
|
| 70 |
+
real_data_path=real_data_path,
|
| 71 |
+
train_params=train_params,
|
| 72 |
+
change_val=True,
|
| 73 |
+
device=device
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
for sample_seed in range(5):
|
| 77 |
+
sample_ctabgan(
|
| 78 |
+
ctabgan,
|
| 79 |
+
parent_dir=dir_,
|
| 80 |
+
real_data_path=real_data_path,
|
| 81 |
+
num_samples=num_samples,
|
| 82 |
+
train_params=train_params,
|
| 83 |
+
change_val=True,
|
| 84 |
+
seed=sample_seed,
|
| 85 |
+
device=device
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
T_dict = {
|
| 89 |
+
"seed": 0,
|
| 90 |
+
"normalization": None,
|
| 91 |
+
"num_nan_policy": None,
|
| 92 |
+
"cat_nan_policy": None,
|
| 93 |
+
"cat_min_frequency": None,
|
| 94 |
+
"cat_encoding": None,
|
| 95 |
+
"y_policy": "default"
|
| 96 |
+
}
|
| 97 |
+
metrics = train_catboost(
|
| 98 |
+
parent_dir=dir_,
|
| 99 |
+
real_data_path=real_data_path,
|
| 100 |
+
eval_type=eval_type,
|
| 101 |
+
T_dict=T_dict,
|
| 102 |
+
change_val=True,
|
| 103 |
+
seed = 0
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
score += metrics.get_val_score()
|
| 107 |
+
return score / 5
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
study = optuna.create_study(
|
| 111 |
+
direction='maximize',
|
| 112 |
+
sampler=optuna.samplers.TPESampler(seed=0),
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
study.optimize(objective, n_trials=35, show_progress_bar=True)
|
| 116 |
+
|
| 117 |
+
os.makedirs(f"exp/{Path(real_data_path).name}/ctabgan/", exist_ok=True)
|
| 118 |
+
config = {
|
| 119 |
+
"parent_dir": f"exp/{Path(real_data_path).name}/ctabgan/",
|
| 120 |
+
"real_data_path": real_data_path,
|
| 121 |
+
"seed": 0,
|
| 122 |
+
"device": args.device,
|
| 123 |
+
"train_params": study.best_trial.user_attrs["train_params"],
|
| 124 |
+
"sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]},
|
| 125 |
+
"eval": {
|
| 126 |
+
"type": {"eval_model": "catboost", "eval_type": eval_type},
|
| 127 |
+
"T": {
|
| 128 |
+
"seed": 0,
|
| 129 |
+
"normalization": None,
|
| 130 |
+
"num_nan_policy": None,
|
| 131 |
+
"cat_nan_policy": None,
|
| 132 |
+
"cat_min_frequency": None,
|
| 133 |
+
"cat_encoding": None,
|
| 134 |
+
"y_policy": "default"
|
| 135 |
+
},
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
train_ctabgan(
|
| 140 |
+
parent_dir=f"exp/{Path(real_data_path).name}/ctabgan/",
|
| 141 |
+
real_data_path=real_data_path,
|
| 142 |
+
train_params=study.best_trial.user_attrs["train_params"],
|
| 143 |
+
change_val=False,
|
| 144 |
+
device=device
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
lib.dump_config(config, config["parent_dir"]+"config.toml")
|
| 148 |
+
|
| 149 |
+
subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}',
|
| 150 |
+
'10', "ctabgan", eval_type, "catboost", "5"], check=True)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/pipeline_tvae.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tomli
|
| 2 |
+
import shutil
|
| 3 |
+
import os
|
| 4 |
+
import argparse
|
| 5 |
+
from train_sample_tvae import train_tvae, sample_tvae
|
| 6 |
+
from scripts.eval_catboost import train_catboost
|
| 7 |
+
import zero
|
| 8 |
+
import lib
|
| 9 |
+
|
| 10 |
+
def load_config(path) :
|
| 11 |
+
with open(path, 'rb') as f:
|
| 12 |
+
return tomli.load(f)
|
| 13 |
+
|
| 14 |
+
def save_file(parent_dir, config_path):
|
| 15 |
+
try:
|
| 16 |
+
dst = os.path.join(parent_dir)
|
| 17 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 18 |
+
shutil.copyfile(os.path.abspath(config_path), dst)
|
| 19 |
+
except shutil.SameFileError:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
parser = argparse.ArgumentParser()
|
| 24 |
+
parser.add_argument('--config', metavar='FILE')
|
| 25 |
+
parser.add_argument('--train', action='store_true', default=False)
|
| 26 |
+
parser.add_argument('--sample', action='store_true', default=False)
|
| 27 |
+
parser.add_argument('--eval', action='store_true', default=False)
|
| 28 |
+
parser.add_argument('--change_val', action='store_true', default=False)
|
| 29 |
+
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
raw_config = lib.load_config(args.config)
|
| 32 |
+
timer = zero.Timer()
|
| 33 |
+
timer.run()
|
| 34 |
+
save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
|
| 35 |
+
ctabgan = None
|
| 36 |
+
if args.train:
|
| 37 |
+
ctabgan = train_tvae(
|
| 38 |
+
parent_dir=raw_config['parent_dir'],
|
| 39 |
+
real_data_path=raw_config['real_data_path'],
|
| 40 |
+
train_params=raw_config['train_params'],
|
| 41 |
+
change_val=args.change_val,
|
| 42 |
+
device=raw_config['device']
|
| 43 |
+
)
|
| 44 |
+
if args.sample:
|
| 45 |
+
sample_tvae(
|
| 46 |
+
synthesizer=ctabgan,
|
| 47 |
+
parent_dir=raw_config['parent_dir'],
|
| 48 |
+
real_data_path=raw_config['real_data_path'],
|
| 49 |
+
num_samples=raw_config['sample']['num_samples'],
|
| 50 |
+
train_params=raw_config['train_params'],
|
| 51 |
+
change_val=args.change_val,
|
| 52 |
+
seed=raw_config['sample']['seed'],
|
| 53 |
+
device=raw_config['device']
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
|
| 57 |
+
if args.eval:
|
| 58 |
+
if raw_config['eval']['type']['eval_model'] == 'catboost':
|
| 59 |
+
train_catboost(
|
| 60 |
+
parent_dir=raw_config['parent_dir'],
|
| 61 |
+
real_data_path=raw_config['real_data_path'],
|
| 62 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 63 |
+
T_dict=raw_config['eval']['T'],
|
| 64 |
+
seed=raw_config['seed'],
|
| 65 |
+
change_val=args.change_val
|
| 66 |
+
)
|
| 67 |
+
# elif raw_config['eval']['type']['eval_model'] == 'mlp':
|
| 68 |
+
# train_mlp(
|
| 69 |
+
# parent_dir=raw_config['parent_dir'],
|
| 70 |
+
# real_data_path=raw_config['real_data_path'],
|
| 71 |
+
# eval_type=raw_config['eval']['type']['eval_type'],
|
| 72 |
+
# T_dict=raw_config['eval']['T'],
|
| 73 |
+
# seed=raw_config['seed'],
|
| 74 |
+
# change_val=args.change_val
|
| 75 |
+
# )
|
| 76 |
+
|
| 77 |
+
print(f'Elapsed time: {str(timer)}')
|
| 78 |
+
|
| 79 |
+
if __name__ == '__main__':
|
| 80 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/train_sample_tvae.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import lib
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import argparse
|
| 5 |
+
from CTGAN.ctgan import TVAESynthesizer
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import torch
|
| 8 |
+
import pickle
|
| 9 |
+
import warnings
|
| 10 |
+
from sklearn.exceptions import ConvergenceWarning
|
| 11 |
+
|
| 12 |
+
warnings.filterwarnings("ignore", category=ConvergenceWarning)
|
| 13 |
+
|
| 14 |
+
def train_tvae(
|
| 15 |
+
parent_dir,
|
| 16 |
+
real_data_path,
|
| 17 |
+
train_params = {"batch_size": 512},
|
| 18 |
+
change_val=False,
|
| 19 |
+
device = "cpu"
|
| 20 |
+
):
|
| 21 |
+
real_data_path = Path(real_data_path)
|
| 22 |
+
parent_dir = Path(parent_dir)
|
| 23 |
+
device = torch.device(device)
|
| 24 |
+
|
| 25 |
+
if change_val:
|
| 26 |
+
X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
|
| 27 |
+
else:
|
| 28 |
+
X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
|
| 29 |
+
|
| 30 |
+
X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
|
| 31 |
+
|
| 32 |
+
X.columns = [str(_) for _ in X.columns]
|
| 33 |
+
|
| 34 |
+
cat_features = list(map(str, range(X_num_train.shape[1], X_num_train.shape[1]+X_cat_train.shape[1]))) if X_cat_train is not None else []
|
| 35 |
+
if lib.load_json(real_data_path / "info.json")["task_type"] != "regression":
|
| 36 |
+
cat_features += ["y"]
|
| 37 |
+
|
| 38 |
+
train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
|
| 39 |
+
|
| 40 |
+
print(train_params)
|
| 41 |
+
synthesizer = TVAESynthesizer(
|
| 42 |
+
**train_params,
|
| 43 |
+
device=device
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
synthesizer.fit(X, cat_features)
|
| 47 |
+
|
| 48 |
+
# save_ctabgan(synthesizer, parent_dir)
|
| 49 |
+
with open(parent_dir / "tvae.obj", "wb") as f:
|
| 50 |
+
pickle.dump(synthesizer, f)
|
| 51 |
+
|
| 52 |
+
return synthesizer
|
| 53 |
+
|
| 54 |
+
def sample_tvae(
|
| 55 |
+
synthesizer,
|
| 56 |
+
parent_dir,
|
| 57 |
+
real_data_path,
|
| 58 |
+
num_samples,
|
| 59 |
+
train_params = {"batch_size": 512},
|
| 60 |
+
change_val=False,
|
| 61 |
+
device="cpu",
|
| 62 |
+
seed=0
|
| 63 |
+
):
|
| 64 |
+
real_data_path = Path(real_data_path)
|
| 65 |
+
parent_dir = Path(parent_dir)
|
| 66 |
+
device = torch.device(device)
|
| 67 |
+
|
| 68 |
+
if change_val:
|
| 69 |
+
X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
|
| 70 |
+
else:
|
| 71 |
+
X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
|
| 72 |
+
|
| 73 |
+
X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
|
| 74 |
+
|
| 75 |
+
X.columns = [str(_) for _ in X.columns]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
cat_features = list(map(str, range(X_num_train.shape[1], X_num_train.shape[1]+X_cat_train.shape[1]))) if X_cat_train is not None else []
|
| 79 |
+
if lib.load_json(real_data_path / "info.json")["task_type"] != "regression":
|
| 80 |
+
cat_features += ["y"]
|
| 81 |
+
|
| 82 |
+
with open(parent_dir / "tvae.obj", 'rb') as f:
|
| 83 |
+
synthesizer = pickle.load(f)
|
| 84 |
+
synthesizer.decoder = synthesizer.decoder.to(device)
|
| 85 |
+
|
| 86 |
+
gen_data = synthesizer.sample(num_samples, seed)
|
| 87 |
+
|
| 88 |
+
y = gen_data['y'].values
|
| 89 |
+
if len(np.unique(y)) == 1:
|
| 90 |
+
y[0] = 0
|
| 91 |
+
y[1] = 1
|
| 92 |
+
|
| 93 |
+
X_cat = gen_data[cat_features].drop('y', axis=1, errors="ignore").values if len(cat_features) else None
|
| 94 |
+
X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
|
| 95 |
+
|
| 96 |
+
if X_num_train is not None:
|
| 97 |
+
np.save(parent_dir / 'X_num_train', X_num.astype(float))
|
| 98 |
+
if X_cat_train is not None:
|
| 99 |
+
np.save(parent_dir / 'X_cat_train', X_cat.astype(str))
|
| 100 |
+
y = y.astype(float)
|
| 101 |
+
if lib.load_json(real_data_path / "info.json")["task_type"] != "regression":
|
| 102 |
+
y = y.astype(int)
|
| 103 |
+
np.save(parent_dir / 'y_train', y) # only clf !!!
|
| 104 |
+
|
| 105 |
+
def main():
|
| 106 |
+
parser = argparse.ArgumentParser()
|
| 107 |
+
parser.add_argument('real_data_path', type=str)
|
| 108 |
+
parser.add_argument('parent_dir', type=str)
|
| 109 |
+
parser.add_argument('train_size', type=int)
|
| 110 |
+
args = parser.parse_args()
|
| 111 |
+
|
| 112 |
+
ctabgan = train_tvae(args.parent_dir, args.real_data_path, change_val=True)
|
| 113 |
+
sample_tvae(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
if __name__ == '__main__':
|
| 117 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/tune_tvae.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from multiprocessing.sharedctypes import RawValue
|
| 2 |
+
import tempfile
|
| 3 |
+
import subprocess
|
| 4 |
+
import lib
|
| 5 |
+
import os
|
| 6 |
+
import optuna
|
| 7 |
+
import argparse
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from train_sample_tvae import train_tvae, sample_tvae
|
| 10 |
+
from scripts.eval_catboost import train_catboost
|
| 11 |
+
|
| 12 |
+
parser = argparse.ArgumentParser()
|
| 13 |
+
parser.add_argument('data_path', type=str)
|
| 14 |
+
parser.add_argument('train_size', type=int)
|
| 15 |
+
parser.add_argument('eval_type', type=str)
|
| 16 |
+
parser.add_argument('device', type=str)
|
| 17 |
+
|
| 18 |
+
args = parser.parse_args()
|
| 19 |
+
real_data_path = args.data_path
|
| 20 |
+
eval_type = args.eval_type
|
| 21 |
+
train_size = args.train_size
|
| 22 |
+
device = args.device
|
| 23 |
+
assert eval_type in ('merged', 'synthetic')
|
| 24 |
+
|
| 25 |
+
def objective(trial):
|
| 26 |
+
|
| 27 |
+
lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
|
| 28 |
+
|
| 29 |
+
def suggest_dim(name):
|
| 30 |
+
t = trial.suggest_int(name, d_min, d_max)
|
| 31 |
+
return 2 ** t
|
| 32 |
+
|
| 33 |
+
# construct model
|
| 34 |
+
min_n_layers, max_n_layers, d_min, d_max = 1, 3, 6, 9
|
| 35 |
+
n_layers = 2 * trial.suggest_int('n_layers', min_n_layers, max_n_layers)
|
| 36 |
+
d_first = [suggest_dim('d_first')] if n_layers else []
|
| 37 |
+
d_middle = (
|
| 38 |
+
[suggest_dim('d_middle')] * (n_layers - 2)
|
| 39 |
+
if n_layers > 2
|
| 40 |
+
else []
|
| 41 |
+
)
|
| 42 |
+
d_last = [suggest_dim('d_last')] if n_layers > 1 else []
|
| 43 |
+
d_layers = d_first + d_middle + d_last
|
| 44 |
+
####
|
| 45 |
+
|
| 46 |
+
steps = trial.suggest_categorical('steps', [5000, 20000, 30000])
|
| 47 |
+
# steps = trial.suggest_categorical('steps', [1000])
|
| 48 |
+
batch_size = trial.suggest_categorical('batch_size', [256, 4096])
|
| 49 |
+
|
| 50 |
+
num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3)))
|
| 51 |
+
embedding_dim = 2 ** trial.suggest_int('embedding_dim', 6, 10)
|
| 52 |
+
loss_factor = trial.suggest_loguniform('loss_factor', 0.001, 10)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
train_params = {
|
| 56 |
+
"lr": lr,
|
| 57 |
+
"epochs": steps,
|
| 58 |
+
"embedding_dim": embedding_dim,
|
| 59 |
+
"batch_size": batch_size,
|
| 60 |
+
"loss_factor": loss_factor,
|
| 61 |
+
"compress_dims": d_layers,
|
| 62 |
+
"decompress_dims": d_layers
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
trial.set_user_attr("train_params", train_params)
|
| 66 |
+
trial.set_user_attr("num_samples", num_samples)
|
| 67 |
+
|
| 68 |
+
score = 0.0
|
| 69 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 70 |
+
dir_ = Path(dir_)
|
| 71 |
+
ctabgan = train_tvae(
|
| 72 |
+
parent_dir=dir_,
|
| 73 |
+
real_data_path=real_data_path,
|
| 74 |
+
train_params=train_params,
|
| 75 |
+
change_val=True,
|
| 76 |
+
device=device
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
for sample_seed in range(5):
|
| 80 |
+
sample_tvae(
|
| 81 |
+
ctabgan,
|
| 82 |
+
parent_dir=dir_,
|
| 83 |
+
real_data_path=real_data_path,
|
| 84 |
+
num_samples=num_samples,
|
| 85 |
+
train_params=train_params,
|
| 86 |
+
change_val=True,
|
| 87 |
+
seed=sample_seed,
|
| 88 |
+
device=device
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
T_dict = {
|
| 92 |
+
"seed": 0,
|
| 93 |
+
"normalization": None,
|
| 94 |
+
"num_nan_policy": None,
|
| 95 |
+
"cat_nan_policy": None,
|
| 96 |
+
"cat_min_frequency": None,
|
| 97 |
+
"cat_encoding": None,
|
| 98 |
+
"y_policy": "default"
|
| 99 |
+
}
|
| 100 |
+
metrics = train_catboost(
|
| 101 |
+
parent_dir=dir_,
|
| 102 |
+
real_data_path=real_data_path,
|
| 103 |
+
eval_type=eval_type,
|
| 104 |
+
T_dict=T_dict,
|
| 105 |
+
change_val=True,
|
| 106 |
+
seed = 0
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
score += metrics.get_val_score()
|
| 110 |
+
return score / 5
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
study = optuna.create_study(
|
| 114 |
+
direction='maximize',
|
| 115 |
+
sampler=optuna.samplers.TPESampler(seed=0),
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
study.optimize(objective, n_trials=50, show_progress_bar=True)
|
| 119 |
+
|
| 120 |
+
os.makedirs(f"exp/{Path(real_data_path).name}/tvae/", exist_ok=True)
|
| 121 |
+
config = {
|
| 122 |
+
"parent_dir": f"exp/{Path(real_data_path).name}/tvae/",
|
| 123 |
+
"real_data_path": real_data_path,
|
| 124 |
+
"seed": 0,
|
| 125 |
+
"device": args.device,
|
| 126 |
+
"train_params": study.best_trial.user_attrs["train_params"],
|
| 127 |
+
"sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]},
|
| 128 |
+
"eval": {
|
| 129 |
+
"type": {"eval_model": "catboost", "eval_type": eval_type},
|
| 130 |
+
"T": {
|
| 131 |
+
"seed": 0,
|
| 132 |
+
"normalization": None,
|
| 133 |
+
"num_nan_policy": None,
|
| 134 |
+
"cat_nan_policy": None,
|
| 135 |
+
"cat_min_frequency": None,
|
| 136 |
+
"cat_encoding": None,
|
| 137 |
+
"y_policy": "default"
|
| 138 |
+
},
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
train_tvae(
|
| 143 |
+
parent_dir=f"exp/{Path(real_data_path).name}/tvae/",
|
| 144 |
+
real_data_path=real_data_path,
|
| 145 |
+
train_params=study.best_trial.user_attrs["train_params"],
|
| 146 |
+
change_val=False,
|
| 147 |
+
device=device
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
lib.dump_config(config, config["parent_dir"]+"config.toml")
|
| 151 |
+
|
| 152 |
+
subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}',
|
| 153 |
+
'10', "tvae", eval_type, "catboost", "5"], check=True)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2022 Akim Kotelnikov
|
| 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.
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/README.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# TabDDPM: Modelling Tabular Data with Diffusion Models
|
| 2 |
+
This is the official code for our paper "TabDDPM: Modelling Tabular Data with Diffusion Models" ([paper](https://arxiv.org/abs/2209.15421))
|
| 3 |
+
|
| 4 |
+
<!-- ## Results
|
| 5 |
+
You can view all the results and build your own tables with this [notebook](notebooks/Reports.ipynb). -->
|
| 6 |
+
|
| 7 |
+
## Setup the environment
|
| 8 |
+
1. Install [conda](https://docs.conda.io/en/latest/miniconda.html) (just to manage the env).
|
| 9 |
+
2. Run the following commands
|
| 10 |
+
```bash
|
| 11 |
+
export REPO_DIR=/path/to/the/code
|
| 12 |
+
cd $REPO_DIR
|
| 13 |
+
|
| 14 |
+
conda create -n tddpm python=3.9.7
|
| 15 |
+
conda activate tddpm
|
| 16 |
+
|
| 17 |
+
pip install torch==1.10.1+cu111 -f https://download.pytorch.org/whl/torch_stable.html
|
| 18 |
+
pip install -r requirements.txt
|
| 19 |
+
|
| 20 |
+
# if the following commands do not succeed, update conda
|
| 21 |
+
conda env config vars set PYTHONPATH=${PYTHONPATH}:${REPO_DIR}
|
| 22 |
+
conda env config vars set PROJECT_DIR=${REPO_DIR}
|
| 23 |
+
|
| 24 |
+
conda deactivate
|
| 25 |
+
conda activate tddpm
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
## Running the experiments
|
| 29 |
+
|
| 30 |
+
Here we describe the neccesary info for reproducing the experimental results.
|
| 31 |
+
Use `agg_results.ipynb` to print results for all dataset and all methods.
|
| 32 |
+
|
| 33 |
+
### Datasets
|
| 34 |
+
|
| 35 |
+
We upload the datasets used in the paper with our train/val/test splits (link below). We do not impose additional restrictions to the original dataset licenses, the sources of the data are listed in the paper appendix.
|
| 36 |
+
|
| 37 |
+
You could load the datasets with the following commands:
|
| 38 |
+
|
| 39 |
+
``` bash
|
| 40 |
+
conda activate tddpm
|
| 41 |
+
cd $PROJECT_DIR
|
| 42 |
+
wget "https://www.dropbox.com/s/rpckvcs3vx7j605/data.tar?dl=0" -O data.tar
|
| 43 |
+
tar -xvf data.tar
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
### File structure
|
| 47 |
+
`tab-ddpm/` -- implementation of the proposed method
|
| 48 |
+
`tuned_models/` -- tuned hyperparameters of evaluation model (CatBoost or MLP)
|
| 49 |
+
|
| 50 |
+
All main scripts are in `scripts/` folder:
|
| 51 |
+
|
| 52 |
+
- `scripts/pipeline.py` are used to train, sample and eval TabDDPM using a given config
|
| 53 |
+
- `scripts/tune_ddpm.py` -- tune hyperparameters of TabDDPM
|
| 54 |
+
- `scripts/eval_[catboost|mlp|simple].py` -- evaluate synthetic data using a tuned evaluation model or simple models
|
| 55 |
+
- `scripts/eval_seeds.py` -- eval using multiple sampling and multuple eval seeds
|
| 56 |
+
- `scripts/eval_seeds_simple.py` -- eval using multiple sampling and multuple eval seeds (for simple models)
|
| 57 |
+
- `scripts/tune_evaluation_model.py` -- tune hyperparameters of eval model (CatBoost or MLP)
|
| 58 |
+
- `scripts/resample_privacy.py` -- privacy calculation
|
| 59 |
+
|
| 60 |
+
Experiments folder (`exp/`):
|
| 61 |
+
- All results and synthetic data are stored in `exp/[ds_name]/[exp_name]/` folder
|
| 62 |
+
- `exp/[ds_name]/config.toml` is a base config for tuning TabDDPM
|
| 63 |
+
- `exp/[ds_name]/eval_[catboost|mlp].json` stores results of evaluation (`scripts/eval_seeds.py`)
|
| 64 |
+
|
| 65 |
+
To understand the structure of `config.toml` file, read `CONFIG_DESCRIPTION.md`.
|
| 66 |
+
|
| 67 |
+
Baselines:
|
| 68 |
+
- `smote/`
|
| 69 |
+
- `CTGAN/` -- TVAE [official repo](https://github.com/sdv-dev/CTGAN)
|
| 70 |
+
- `CTAB-GAN/` -- [official repo](https://github.com/Team-TUD/CTAB-GAN)
|
| 71 |
+
- `CTAB-GAN-Plus/` -- [official repo](https://github.com/Team-TUD/CTAB-GAN-Plus)
|
| 72 |
+
|
| 73 |
+
### Examples
|
| 74 |
+
|
| 75 |
+
<ins>Run TabDDPM tuning.</ins>
|
| 76 |
+
|
| 77 |
+
Template and example (`--eval_seeds` is optional):
|
| 78 |
+
```bash
|
| 79 |
+
python scripts/tune_ddpm.py [ds_name] [train_size] synthetic [catboost|mlp] [exp_name] --eval_seeds
|
| 80 |
+
python scripts/tune_ddpm.py churn2 6500 synthetic catboost ddpm_tune --eval_seeds
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
<ins>Run TabDDPM pipeline.</ins>
|
| 84 |
+
|
| 85 |
+
Template and example (`--train`, `--sample`, `--eval` are optional):
|
| 86 |
+
```bash
|
| 87 |
+
python scripts/pipeline.py --config [path_to_your_config] --train --sample --eval
|
| 88 |
+
python scripts/pipeline.py --config exp/churn2/ddpm_cb_best/config.toml --train --sample
|
| 89 |
+
```
|
| 90 |
+
It takes approximately 7min to run the script above (NVIDIA GeForce RTX 2080 Ti).
|
| 91 |
+
|
| 92 |
+
<ins>Run evaluation over seeds</ins>
|
| 93 |
+
Before running evaluation, you have to train the model with the given hyperparameters (the example above).
|
| 94 |
+
|
| 95 |
+
Template and example:
|
| 96 |
+
```bash
|
| 97 |
+
python scripts/eval_seeds.py --config [path_to_your_config] [n_eval_seeds] [ddpm|smote|ctabgan|ctabgan-plus|tvae] synthetic [catboost|mlp] [n_sample_seeds]
|
| 98 |
+
python scripts/eval_seeds.py --config exp/churn2/ddpm_cb_best/config.toml 10 ddpm synthetic catboost 5
|
| 99 |
+
```
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/_compat_run.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections, collections.abc
|
| 2 |
+
for _a in ('Sequence','MutableSequence','MutableMapping','Mapping','MutableSet','Set','Callable','Iterable','Iterator'):
|
| 3 |
+
if not hasattr(collections, _a): setattr(collections, _a, getattr(collections.abc, _a, None))
|
| 4 |
+
import sys, runpy
|
| 5 |
+
sys.argv = sys.argv[1:]
|
| 6 |
+
runpy.run_path(sys.argv[0], run_name='__main__')
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/agg_results.ipynb
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"## Aggregating results to DataFrame"
|
| 8 |
+
]
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"cell_type": "code",
|
| 12 |
+
"execution_count": 1,
|
| 13 |
+
"metadata": {},
|
| 14 |
+
"outputs": [],
|
| 15 |
+
"source": [
|
| 16 |
+
"import os\n",
|
| 17 |
+
"import lib\n",
|
| 18 |
+
"import numpy as np\n",
|
| 19 |
+
"import pandas as pd\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"DATASETS = [\n",
|
| 22 |
+
" \"abalone\",\n",
|
| 23 |
+
" \"adult\",\n",
|
| 24 |
+
" \"buddy\",\n",
|
| 25 |
+
" \"california\",\n",
|
| 26 |
+
" \"cardio\",\n",
|
| 27 |
+
" \"churn2\",\n",
|
| 28 |
+
" \"default\",\n",
|
| 29 |
+
" \"diabetes\",\n",
|
| 30 |
+
" \"fb-comments\",\n",
|
| 31 |
+
" \"gesture\",\n",
|
| 32 |
+
" \"higgs-small\",\n",
|
| 33 |
+
" \"house\",\n",
|
| 34 |
+
" \"insurance\",\n",
|
| 35 |
+
" \"king\",\n",
|
| 36 |
+
" \"miniboone\",\n",
|
| 37 |
+
" \"wilt\"\n",
|
| 38 |
+
"]\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"_REGRESSION = [\n",
|
| 41 |
+
" \"abalone\",\n",
|
| 42 |
+
" \"california\",\n",
|
| 43 |
+
" \"fb-comments\",\n",
|
| 44 |
+
" \"house\",\n",
|
| 45 |
+
" \"insurance\",\n",
|
| 46 |
+
" \"king\",\n",
|
| 47 |
+
"]\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"method2exp = {\n",
|
| 51 |
+
" \"real\": \"exp/{}/ddpm_cb_best/\",\n",
|
| 52 |
+
" \"tab-ddpm\": \"exp/{}/ddpm_cb_best/\",\n",
|
| 53 |
+
" \"smote\": \"exp/{}/smote/\",\n",
|
| 54 |
+
" \"ctabgan+\": \"exp/{}/ctabgan-plus/\",\n",
|
| 55 |
+
" \"ctabgan\": \"exp/{}/ctabgan/\",\n",
|
| 56 |
+
" \"tvae\": \"exp/{}/tvae/\"\n",
|
| 57 |
+
"}\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"eval_file = \"eval_catboost.json\"\n",
|
| 60 |
+
"show_std = False\n",
|
| 61 |
+
"df = pd.DataFrame(columns=[\"method\"] + [_[:3].upper() for _ in DATASETS])\n",
|
| 62 |
+
"\n",
|
| 63 |
+
"for algo in method2exp: \n",
|
| 64 |
+
" algo_res = []\n",
|
| 65 |
+
" for ds in DATASETS:\n",
|
| 66 |
+
" if not os.path.exists(os.path.join(method2exp[algo].format(ds), eval_file)):\n",
|
| 67 |
+
" algo_res.append(\"--\")\n",
|
| 68 |
+
" continue\n",
|
| 69 |
+
" metric = \"r2\" if ds in _REGRESSION else \"f1\"\n",
|
| 70 |
+
" res_dict = lib.load_json(os.path.join(method2exp[algo].format(ds), eval_file))\n",
|
| 71 |
+
"\n",
|
| 72 |
+
" if algo == \"real\":\n",
|
| 73 |
+
" res = f'{res_dict[\"real\"][\"test\"][metric + \"-mean\"]:.4f}' \n",
|
| 74 |
+
" if show_std: res += f'+-{res_dict[\"real\"][\"test\"][metric + \"-std\"]:.4f}'\n",
|
| 75 |
+
" else:\n",
|
| 76 |
+
" res = f'{res_dict[\"synthetic\"][\"test\"][metric + \"-mean\"]:.4f}'\n",
|
| 77 |
+
" if show_std: res += f'+-{res_dict[\"synthetic\"][\"test\"][metric + \"-std\"]:.4f}'\n",
|
| 78 |
+
"\n",
|
| 79 |
+
" algo_res.append(res)\n",
|
| 80 |
+
" df.loc[len(df)] = [algo] + algo_res"
|
| 81 |
+
]
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"execution_count": 2,
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"outputs": [
|
| 88 |
+
{
|
| 89 |
+
"data": {
|
| 90 |
+
"text/html": [
|
| 91 |
+
"<div>\n",
|
| 92 |
+
"<style scoped>\n",
|
| 93 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
| 94 |
+
" vertical-align: middle;\n",
|
| 95 |
+
" }\n",
|
| 96 |
+
"\n",
|
| 97 |
+
" .dataframe tbody tr th {\n",
|
| 98 |
+
" vertical-align: top;\n",
|
| 99 |
+
" }\n",
|
| 100 |
+
"\n",
|
| 101 |
+
" .dataframe thead th {\n",
|
| 102 |
+
" text-align: right;\n",
|
| 103 |
+
" }\n",
|
| 104 |
+
"</style>\n",
|
| 105 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
| 106 |
+
" <thead>\n",
|
| 107 |
+
" <tr style=\"text-align: right;\">\n",
|
| 108 |
+
" <th></th>\n",
|
| 109 |
+
" <th>method</th>\n",
|
| 110 |
+
" <th>ABA</th>\n",
|
| 111 |
+
" <th>ADU</th>\n",
|
| 112 |
+
" <th>BUD</th>\n",
|
| 113 |
+
" <th>CAL</th>\n",
|
| 114 |
+
" <th>CAR</th>\n",
|
| 115 |
+
" <th>CHU</th>\n",
|
| 116 |
+
" <th>DEF</th>\n",
|
| 117 |
+
" <th>DIA</th>\n",
|
| 118 |
+
" <th>FB-</th>\n",
|
| 119 |
+
" <th>GES</th>\n",
|
| 120 |
+
" <th>HIG</th>\n",
|
| 121 |
+
" <th>HOU</th>\n",
|
| 122 |
+
" <th>INS</th>\n",
|
| 123 |
+
" <th>KIN</th>\n",
|
| 124 |
+
" <th>MIN</th>\n",
|
| 125 |
+
" <th>WIL</th>\n",
|
| 126 |
+
" </tr>\n",
|
| 127 |
+
" </thead>\n",
|
| 128 |
+
" <tbody>\n",
|
| 129 |
+
" <tr>\n",
|
| 130 |
+
" <th>0</th>\n",
|
| 131 |
+
" <td>real</td>\n",
|
| 132 |
+
" <td>0.5562</td>\n",
|
| 133 |
+
" <td>0.8152</td>\n",
|
| 134 |
+
" <td>0.9063</td>\n",
|
| 135 |
+
" <td>0.8568</td>\n",
|
| 136 |
+
" <td>0.7379</td>\n",
|
| 137 |
+
" <td>0.7403</td>\n",
|
| 138 |
+
" <td>0.6880</td>\n",
|
| 139 |
+
" <td>0.7849</td>\n",
|
| 140 |
+
" <td>0.8371</td>\n",
|
| 141 |
+
" <td>0.6365</td>\n",
|
| 142 |
+
" <td>0.7238</td>\n",
|
| 143 |
+
" <td>0.6616</td>\n",
|
| 144 |
+
" <td>0.8137</td>\n",
|
| 145 |
+
" <td>0.9070</td>\n",
|
| 146 |
+
" <td>0.9342</td>\n",
|
| 147 |
+
" <td>0.8982</td>\n",
|
| 148 |
+
" </tr>\n",
|
| 149 |
+
" <tr>\n",
|
| 150 |
+
" <th>1</th>\n",
|
| 151 |
+
" <td>tab-ddpm</td>\n",
|
| 152 |
+
" <td>0.5499</td>\n",
|
| 153 |
+
" <td>0.7951</td>\n",
|
| 154 |
+
" <td>0.9057</td>\n",
|
| 155 |
+
" <td>0.8362</td>\n",
|
| 156 |
+
" <td>0.7374</td>\n",
|
| 157 |
+
" <td>0.7548</td>\n",
|
| 158 |
+
" <td>0.6910</td>\n",
|
| 159 |
+
" <td>0.7398</td>\n",
|
| 160 |
+
" <td>0.7128</td>\n",
|
| 161 |
+
" <td>0.5967</td>\n",
|
| 162 |
+
" <td>0.7218</td>\n",
|
| 163 |
+
" <td>0.6766</td>\n",
|
| 164 |
+
" <td>0.8092</td>\n",
|
| 165 |
+
" <td>0.8331</td>\n",
|
| 166 |
+
" <td>0.9362</td>\n",
|
| 167 |
+
" <td>0.9045</td>\n",
|
| 168 |
+
" </tr>\n",
|
| 169 |
+
" <tr>\n",
|
| 170 |
+
" <th>2</th>\n",
|
| 171 |
+
" <td>smote</td>\n",
|
| 172 |
+
" <td>0.5486</td>\n",
|
| 173 |
+
" <td>0.7912</td>\n",
|
| 174 |
+
" <td>0.8906</td>\n",
|
| 175 |
+
" <td>0.8397</td>\n",
|
| 176 |
+
" <td>0.7323</td>\n",
|
| 177 |
+
" <td>0.7432</td>\n",
|
| 178 |
+
" <td>0.6930</td>\n",
|
| 179 |
+
" <td>0.6835</td>\n",
|
| 180 |
+
" <td>0.8035</td>\n",
|
| 181 |
+
" <td>0.6579</td>\n",
|
| 182 |
+
" <td>0.7219</td>\n",
|
| 183 |
+
" <td>0.6625</td>\n",
|
| 184 |
+
" <td>0.8119</td>\n",
|
| 185 |
+
" <td>0.8416</td>\n",
|
| 186 |
+
" <td>0.9323</td>\n",
|
| 187 |
+
" <td>0.9127</td>\n",
|
| 188 |
+
" </tr>\n",
|
| 189 |
+
" <tr>\n",
|
| 190 |
+
" <th>3</th>\n",
|
| 191 |
+
" <td>ctabgan+</td>\n",
|
| 192 |
+
" <td>0.4672</td>\n",
|
| 193 |
+
" <td>0.7724</td>\n",
|
| 194 |
+
" <td>0.8844</td>\n",
|
| 195 |
+
" <td>0.5247</td>\n",
|
| 196 |
+
" <td>0.7327</td>\n",
|
| 197 |
+
" <td>0.7024</td>\n",
|
| 198 |
+
" <td>0.6865</td>\n",
|
| 199 |
+
" <td>0.7339</td>\n",
|
| 200 |
+
" <td>0.5088</td>\n",
|
| 201 |
+
" <td>0.4055</td>\n",
|
| 202 |
+
" <td>0.6639</td>\n",
|
| 203 |
+
" <td>0.5040</td>\n",
|
| 204 |
+
" <td>0.7966</td>\n",
|
| 205 |
+
" <td>0.4438</td>\n",
|
| 206 |
+
" <td>0.8920</td>\n",
|
| 207 |
+
" <td>0.7983</td>\n",
|
| 208 |
+
" </tr>\n",
|
| 209 |
+
" <tr>\n",
|
| 210 |
+
" <th>4</th>\n",
|
| 211 |
+
" <td>ctabgan</td>\n",
|
| 212 |
+
" <td>--</td>\n",
|
| 213 |
+
" <td>0.7831</td>\n",
|
| 214 |
+
" <td>0.8552</td>\n",
|
| 215 |
+
" <td>--</td>\n",
|
| 216 |
+
" <td>0.7171</td>\n",
|
| 217 |
+
" <td>0.6875</td>\n",
|
| 218 |
+
" <td>0.6437</td>\n",
|
| 219 |
+
" <td>0.7310</td>\n",
|
| 220 |
+
" <td>--</td>\n",
|
| 221 |
+
" <td>0.3922</td>\n",
|
| 222 |
+
" <td>0.5748</td>\n",
|
| 223 |
+
" <td>--</td>\n",
|
| 224 |
+
" <td>--</td>\n",
|
| 225 |
+
" <td>--</td>\n",
|
| 226 |
+
" <td>0.8892</td>\n",
|
| 227 |
+
" <td>0.9060</td>\n",
|
| 228 |
+
" </tr>\n",
|
| 229 |
+
" <tr>\n",
|
| 230 |
+
" <th>5</th>\n",
|
| 231 |
+
" <td>tvae</td>\n",
|
| 232 |
+
" <td>0.4328</td>\n",
|
| 233 |
+
" <td>0.7810</td>\n",
|
| 234 |
+
" <td>0.8638</td>\n",
|
| 235 |
+
" <td>0.7518</td>\n",
|
| 236 |
+
" <td>0.7174</td>\n",
|
| 237 |
+
" <td>0.7317</td>\n",
|
| 238 |
+
" <td>0.6564</td>\n",
|
| 239 |
+
" <td>0.7136</td>\n",
|
| 240 |
+
" <td>0.6853</td>\n",
|
| 241 |
+
" <td>0.4340</td>\n",
|
| 242 |
+
" <td>0.6378</td>\n",
|
| 243 |
+
" <td>0.4926</td>\n",
|
| 244 |
+
" <td>0.7842</td>\n",
|
| 245 |
+
" <td>0.8238</td>\n",
|
| 246 |
+
" <td>0.9125</td>\n",
|
| 247 |
+
" <td>0.5006</td>\n",
|
| 248 |
+
" </tr>\n",
|
| 249 |
+
" </tbody>\n",
|
| 250 |
+
"</table>\n",
|
| 251 |
+
"</div>"
|
| 252 |
+
],
|
| 253 |
+
"text/plain": [
|
| 254 |
+
" method ABA ADU BUD CAL CAR CHU DEF DIA \\\n",
|
| 255 |
+
"0 real 0.5562 0.8152 0.9063 0.8568 0.7379 0.7403 0.6880 0.7849 \n",
|
| 256 |
+
"1 tab-ddpm 0.5499 0.7951 0.9057 0.8362 0.7374 0.7548 0.6910 0.7398 \n",
|
| 257 |
+
"2 smote 0.5486 0.7912 0.8906 0.8397 0.7323 0.7432 0.6930 0.6835 \n",
|
| 258 |
+
"3 ctabgan+ 0.4672 0.7724 0.8844 0.5247 0.7327 0.7024 0.6865 0.7339 \n",
|
| 259 |
+
"4 ctabgan -- 0.7831 0.8552 -- 0.7171 0.6875 0.6437 0.7310 \n",
|
| 260 |
+
"5 tvae 0.4328 0.7810 0.8638 0.7518 0.7174 0.7317 0.6564 0.7136 \n",
|
| 261 |
+
"\n",
|
| 262 |
+
" FB- GES HIG HOU INS KIN MIN WIL \n",
|
| 263 |
+
"0 0.8371 0.6365 0.7238 0.6616 0.8137 0.9070 0.9342 0.8982 \n",
|
| 264 |
+
"1 0.7128 0.5967 0.7218 0.6766 0.8092 0.8331 0.9362 0.9045 \n",
|
| 265 |
+
"2 0.8035 0.6579 0.7219 0.6625 0.8119 0.8416 0.9323 0.9127 \n",
|
| 266 |
+
"3 0.5088 0.4055 0.6639 0.5040 0.7966 0.4438 0.8920 0.7983 \n",
|
| 267 |
+
"4 -- 0.3922 0.5748 -- -- -- 0.8892 0.9060 \n",
|
| 268 |
+
"5 0.6853 0.4340 0.6378 0.4926 0.7842 0.8238 0.9125 0.5006 "
|
| 269 |
+
]
|
| 270 |
+
},
|
| 271 |
+
"execution_count": 2,
|
| 272 |
+
"metadata": {},
|
| 273 |
+
"output_type": "execute_result"
|
| 274 |
+
}
|
| 275 |
+
],
|
| 276 |
+
"source": [
|
| 277 |
+
"df"
|
| 278 |
+
]
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"execution_count": null,
|
| 283 |
+
"metadata": {},
|
| 284 |
+
"outputs": [],
|
| 285 |
+
"source": []
|
| 286 |
+
}
|
| 287 |
+
],
|
| 288 |
+
"metadata": {
|
| 289 |
+
"kernelspec": {
|
| 290 |
+
"display_name": "Python 3.9.7 ('base')",
|
| 291 |
+
"language": "python",
|
| 292 |
+
"name": "python3"
|
| 293 |
+
},
|
| 294 |
+
"language_info": {
|
| 295 |
+
"codemirror_mode": {
|
| 296 |
+
"name": "ipython",
|
| 297 |
+
"version": 3
|
| 298 |
+
},
|
| 299 |
+
"file_extension": ".py",
|
| 300 |
+
"mimetype": "text/x-python",
|
| 301 |
+
"name": "python",
|
| 302 |
+
"nbconvert_exporter": "python",
|
| 303 |
+
"pygments_lexer": "ipython3",
|
| 304 |
+
"version": "3.9.7"
|
| 305 |
+
},
|
| 306 |
+
"orig_nbformat": 4,
|
| 307 |
+
"vscode": {
|
| 308 |
+
"interpreter": {
|
| 309 |
+
"hash": "a06af253165e97d0c1e75e8bf6d3252013856f30b8177e11b02d3fa36c37333d"
|
| 310 |
+
}
|
| 311 |
+
}
|
| 312 |
+
},
|
| 313 |
+
"nbformat": 4,
|
| 314 |
+
"nbformat_minor": 2
|
| 315 |
+
}
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from icecream import install
|
| 3 |
+
|
| 4 |
+
torch.set_num_threads(1)
|
| 5 |
+
install()
|
| 6 |
+
|
| 7 |
+
from . import env # noqa
|
| 8 |
+
from .data import * # noqa
|
| 9 |
+
from .deep import * # noqa
|
| 10 |
+
from .env import * # noqa
|
| 11 |
+
from .metrics import * # noqa
|
| 12 |
+
from .util import * # noqa
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/data.py
ADDED
|
@@ -0,0 +1,719 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import hashlib
|
| 2 |
+
from collections import Counter
|
| 3 |
+
from copy import deepcopy
|
| 4 |
+
from dataclasses import astuple, dataclass, replace
|
| 5 |
+
from importlib.resources import path
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Literal, Optional, Union, cast, Tuple, Dict, List
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from sklearn.model_selection import train_test_split
|
| 12 |
+
from sklearn.pipeline import make_pipeline
|
| 13 |
+
import sklearn.preprocessing
|
| 14 |
+
import torch
|
| 15 |
+
import os
|
| 16 |
+
from category_encoders import LeaveOneOutEncoder
|
| 17 |
+
from sklearn.impute import SimpleImputer
|
| 18 |
+
from sklearn.preprocessing import StandardScaler
|
| 19 |
+
from scipy.spatial.distance import cdist
|
| 20 |
+
|
| 21 |
+
from . import env, util
|
| 22 |
+
from .metrics import calculate_metrics as calculate_metrics_
|
| 23 |
+
from .util import TaskType, load_json
|
| 24 |
+
|
| 25 |
+
ArrayDict = Dict[str, np.ndarray]
|
| 26 |
+
TensorDict = Dict[str, torch.Tensor]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
CAT_MISSING_VALUE = '__nan__'
|
| 30 |
+
CAT_RARE_VALUE = '__rare__'
|
| 31 |
+
Normalization = Literal['standard', 'quantile', 'minmax']
|
| 32 |
+
NumNanPolicy = Literal['drop-rows', 'mean']
|
| 33 |
+
CatNanPolicy = Literal['most_frequent']
|
| 34 |
+
CatEncoding = Literal['one-hot', 'counter']
|
| 35 |
+
YPolicy = Literal['default']
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class StandardScaler1d(StandardScaler):
|
| 39 |
+
def partial_fit(self, X, *args, **kwargs):
|
| 40 |
+
assert X.ndim == 1
|
| 41 |
+
return super().partial_fit(X[:, None], *args, **kwargs)
|
| 42 |
+
|
| 43 |
+
def transform(self, X, *args, **kwargs):
|
| 44 |
+
assert X.ndim == 1
|
| 45 |
+
return super().transform(X[:, None], *args, **kwargs).squeeze(1)
|
| 46 |
+
|
| 47 |
+
def inverse_transform(self, X, *args, **kwargs):
|
| 48 |
+
assert X.ndim == 1
|
| 49 |
+
return super().inverse_transform(X[:, None], *args, **kwargs).squeeze(1)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def get_category_sizes(X: Union[torch.Tensor, np.ndarray]) -> List[int]:
|
| 53 |
+
"""Return K[i] s.t. F.one_hot(x[:,i], K[i]) is valid. Requires K[i] > max(x[:,i])."""
|
| 54 |
+
XT = X.T.cpu().tolist() if isinstance(X, torch.Tensor) else X.T.tolist()
|
| 55 |
+
return [int(np.max(x)) + 1 if len(x) > 0 else 0 for x in XT]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass(frozen=False)
|
| 59 |
+
class Dataset:
|
| 60 |
+
X_num: Optional[ArrayDict]
|
| 61 |
+
X_cat: Optional[ArrayDict]
|
| 62 |
+
y: ArrayDict
|
| 63 |
+
y_info: Dict[str, Any]
|
| 64 |
+
task_type: TaskType
|
| 65 |
+
n_classes: Optional[int]
|
| 66 |
+
|
| 67 |
+
@classmethod
|
| 68 |
+
def from_dir(cls, dir_: Union[Path, str]) -> 'Dataset':
|
| 69 |
+
dir_ = Path(dir_)
|
| 70 |
+
splits = [k for k in ['train', 'val', 'test'] if dir_.joinpath(f'y_{k}.npy').exists()]
|
| 71 |
+
|
| 72 |
+
def load(item) -> ArrayDict:
|
| 73 |
+
return {
|
| 74 |
+
x: cast(np.ndarray, np.load(dir_ / f'{item}_{x}.npy', allow_pickle=True)) # type: ignore[code]
|
| 75 |
+
for x in splits
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
if Path(dir_ / 'info.json').exists():
|
| 79 |
+
info = util.load_json(dir_ / 'info.json')
|
| 80 |
+
else:
|
| 81 |
+
info = None
|
| 82 |
+
return Dataset(
|
| 83 |
+
load('X_num') if dir_.joinpath('X_num_train.npy').exists() else None,
|
| 84 |
+
load('X_cat') if dir_.joinpath('X_cat_train.npy').exists() else None,
|
| 85 |
+
load('y'),
|
| 86 |
+
{},
|
| 87 |
+
TaskType(info['task_type']),
|
| 88 |
+
info.get('n_classes'),
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
@property
|
| 92 |
+
def is_binclass(self) -> bool:
|
| 93 |
+
return self.task_type == TaskType.BINCLASS
|
| 94 |
+
|
| 95 |
+
@property
|
| 96 |
+
def is_multiclass(self) -> bool:
|
| 97 |
+
return self.task_type == TaskType.MULTICLASS
|
| 98 |
+
|
| 99 |
+
@property
|
| 100 |
+
def is_regression(self) -> bool:
|
| 101 |
+
return self.task_type == TaskType.REGRESSION
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def n_num_features(self) -> int:
|
| 105 |
+
return 0 if self.X_num is None else self.X_num['train'].shape[1]
|
| 106 |
+
|
| 107 |
+
@property
|
| 108 |
+
def n_cat_features(self) -> int:
|
| 109 |
+
return 0 if self.X_cat is None else self.X_cat['train'].shape[1]
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def n_features(self) -> int:
|
| 113 |
+
return self.n_num_features + self.n_cat_features
|
| 114 |
+
|
| 115 |
+
def size(self, part: Optional[str]) -> int:
|
| 116 |
+
return sum(map(len, self.y.values())) if part is None else len(self.y[part])
|
| 117 |
+
|
| 118 |
+
@property
|
| 119 |
+
def nn_output_dim(self) -> int:
|
| 120 |
+
if self.is_multiclass:
|
| 121 |
+
assert self.n_classes is not None
|
| 122 |
+
return self.n_classes
|
| 123 |
+
else:
|
| 124 |
+
return 1
|
| 125 |
+
|
| 126 |
+
def get_category_sizes(self, part: str) -> List[int]:
|
| 127 |
+
return [] if self.X_cat is None else get_category_sizes(self.X_cat[part])
|
| 128 |
+
|
| 129 |
+
def calculate_metrics(
|
| 130 |
+
self,
|
| 131 |
+
predictions: Dict[str, np.ndarray],
|
| 132 |
+
prediction_type: Optional[str],
|
| 133 |
+
) -> Dict[str, Any]:
|
| 134 |
+
metrics = {
|
| 135 |
+
x: calculate_metrics_(
|
| 136 |
+
self.y[x], predictions[x], self.task_type, prediction_type, self.y_info
|
| 137 |
+
)
|
| 138 |
+
for x in predictions
|
| 139 |
+
}
|
| 140 |
+
if self.task_type == TaskType.REGRESSION:
|
| 141 |
+
score_key = 'rmse'
|
| 142 |
+
score_sign = -1
|
| 143 |
+
else:
|
| 144 |
+
score_key = 'accuracy'
|
| 145 |
+
score_sign = 1
|
| 146 |
+
for part_metrics in metrics.values():
|
| 147 |
+
part_metrics['score'] = score_sign * part_metrics[score_key]
|
| 148 |
+
return metrics
|
| 149 |
+
|
| 150 |
+
def change_val(dataset: Dataset, val_size: float = 0.2):
|
| 151 |
+
# should be done before transformations
|
| 152 |
+
|
| 153 |
+
y = np.concatenate([dataset.y['train'], dataset.y['val']], axis=0)
|
| 154 |
+
|
| 155 |
+
ixs = np.arange(y.shape[0])
|
| 156 |
+
if dataset.is_regression:
|
| 157 |
+
train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
|
| 158 |
+
else:
|
| 159 |
+
train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
|
| 160 |
+
|
| 161 |
+
dataset.y['train'] = y[train_ixs]
|
| 162 |
+
dataset.y['val'] = y[val_ixs]
|
| 163 |
+
|
| 164 |
+
if dataset.X_num is not None:
|
| 165 |
+
X_num = np.concatenate([dataset.X_num['train'], dataset.X_num['val']], axis=0)
|
| 166 |
+
dataset.X_num['train'] = X_num[train_ixs]
|
| 167 |
+
dataset.X_num['val'] = X_num[val_ixs]
|
| 168 |
+
|
| 169 |
+
if dataset.X_cat is not None:
|
| 170 |
+
X_cat = np.concatenate([dataset.X_cat['train'], dataset.X_cat['val']], axis=0)
|
| 171 |
+
dataset.X_cat['train'] = X_cat[train_ixs]
|
| 172 |
+
dataset.X_cat['val'] = X_cat[val_ixs]
|
| 173 |
+
|
| 174 |
+
return dataset
|
| 175 |
+
|
| 176 |
+
def num_process_nans(dataset: Dataset, policy: Optional[NumNanPolicy]) -> Dataset:
|
| 177 |
+
assert dataset.X_num is not None
|
| 178 |
+
nan_masks = {k: np.isnan(v) for k, v in dataset.X_num.items()}
|
| 179 |
+
if not any(x.any() for x in nan_masks.values()): # type: ignore[code]
|
| 180 |
+
assert policy is None
|
| 181 |
+
return dataset
|
| 182 |
+
|
| 183 |
+
assert policy is not None
|
| 184 |
+
if policy == 'drop-rows':
|
| 185 |
+
valid_masks = {k: ~v.any(1) for k, v in nan_masks.items()}
|
| 186 |
+
assert valid_masks[
|
| 187 |
+
'test'
|
| 188 |
+
].all(), 'Cannot drop test rows, since this will affect the final metrics.'
|
| 189 |
+
new_data = {}
|
| 190 |
+
for data_name in ['X_num', 'X_cat', 'y']:
|
| 191 |
+
data_dict = getattr(dataset, data_name)
|
| 192 |
+
if data_dict is not None:
|
| 193 |
+
new_data[data_name] = {
|
| 194 |
+
k: v[valid_masks[k]] for k, v in data_dict.items()
|
| 195 |
+
}
|
| 196 |
+
dataset = replace(dataset, **new_data)
|
| 197 |
+
elif policy == 'mean':
|
| 198 |
+
new_values = np.nanmean(dataset.X_num['train'], axis=0)
|
| 199 |
+
X_num = deepcopy(dataset.X_num)
|
| 200 |
+
for k, v in X_num.items():
|
| 201 |
+
num_nan_indices = np.where(nan_masks[k])
|
| 202 |
+
v[num_nan_indices] = np.take(new_values, num_nan_indices[1])
|
| 203 |
+
dataset = replace(dataset, X_num=X_num)
|
| 204 |
+
else:
|
| 205 |
+
assert util.raise_unknown('policy', policy)
|
| 206 |
+
return dataset
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# Inspired by: https://github.com/yandex-research/rtdl/blob/a4c93a32b334ef55d2a0559a4407c8306ffeeaee/lib/data.py#L20
|
| 210 |
+
def normalize(
|
| 211 |
+
X: ArrayDict, normalization: Normalization, seed: Optional[int], return_normalizer : bool = False
|
| 212 |
+
) -> ArrayDict:
|
| 213 |
+
X_train = X['train']
|
| 214 |
+
if normalization == 'standard':
|
| 215 |
+
normalizer = sklearn.preprocessing.StandardScaler()
|
| 216 |
+
elif normalization == 'minmax':
|
| 217 |
+
normalizer = sklearn.preprocessing.MinMaxScaler()
|
| 218 |
+
elif normalization == 'quantile':
|
| 219 |
+
normalizer = sklearn.preprocessing.QuantileTransformer(
|
| 220 |
+
output_distribution='normal',
|
| 221 |
+
n_quantiles=max(min(X['train'].shape[0] // 30, 1000), 10),
|
| 222 |
+
subsample=int(1e9),
|
| 223 |
+
random_state=seed,
|
| 224 |
+
)
|
| 225 |
+
# noise = 1e-3
|
| 226 |
+
# if noise > 0:
|
| 227 |
+
# assert seed is not None
|
| 228 |
+
# stds = np.std(X_train, axis=0, keepdims=True)
|
| 229 |
+
# noise_std = noise / np.maximum(stds, noise) # type: ignore[code]
|
| 230 |
+
# X_train = X_train + noise_std * np.random.default_rng(seed).standard_normal(
|
| 231 |
+
# X_train.shape
|
| 232 |
+
# )
|
| 233 |
+
else:
|
| 234 |
+
util.raise_unknown('normalization', normalization)
|
| 235 |
+
normalizer.fit(X_train)
|
| 236 |
+
if return_normalizer:
|
| 237 |
+
return {k: normalizer.transform(v) for k, v in X.items()}, normalizer
|
| 238 |
+
return {k: normalizer.transform(v) for k, v in X.items()}
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def cat_process_nans(X: ArrayDict, policy: Optional[CatNanPolicy]) -> ArrayDict:
|
| 242 |
+
assert X is not None
|
| 243 |
+
nan_masks = {k: np.asarray(v == CAT_MISSING_VALUE) for k, v in X.items()}
|
| 244 |
+
if any(np.asarray(x).any() for x in nan_masks.values()): # type: ignore[code]
|
| 245 |
+
if policy is None:
|
| 246 |
+
X_new = X
|
| 247 |
+
elif policy == 'most_frequent':
|
| 248 |
+
imputer = SimpleImputer(missing_values=CAT_MISSING_VALUE, strategy=policy) # type: ignore[code]
|
| 249 |
+
imputer.fit(X['train'])
|
| 250 |
+
X_new = {k: cast(np.ndarray, imputer.transform(v)) for k, v in X.items()}
|
| 251 |
+
else:
|
| 252 |
+
util.raise_unknown('categorical NaN policy', policy)
|
| 253 |
+
else:
|
| 254 |
+
assert policy is None
|
| 255 |
+
X_new = X
|
| 256 |
+
return X_new
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def cat_drop_rare(X: ArrayDict, min_frequency: float) -> ArrayDict:
|
| 260 |
+
assert 0.0 < min_frequency < 1.0
|
| 261 |
+
min_count = round(len(X['train']) * min_frequency)
|
| 262 |
+
X_new = {x: [] for x in X}
|
| 263 |
+
for column_idx in range(X['train'].shape[1]):
|
| 264 |
+
counter = Counter(X['train'][:, column_idx].tolist())
|
| 265 |
+
popular_categories = {k for k, v in counter.items() if v >= min_count}
|
| 266 |
+
for part in X_new:
|
| 267 |
+
X_new[part].append(
|
| 268 |
+
[
|
| 269 |
+
(x if x in popular_categories else CAT_RARE_VALUE)
|
| 270 |
+
for x in X[part][:, column_idx].tolist()
|
| 271 |
+
]
|
| 272 |
+
)
|
| 273 |
+
return {k: np.array(v).T for k, v in X_new.items()}
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def cat_encode(
|
| 277 |
+
X: ArrayDict,
|
| 278 |
+
encoding: Optional[CatEncoding],
|
| 279 |
+
y_train: Optional[np.ndarray],
|
| 280 |
+
seed: Optional[int],
|
| 281 |
+
return_encoder : bool = False
|
| 282 |
+
) -> Tuple[ArrayDict, bool, Optional[Any]]: # (X, is_converted_to_numerical)
|
| 283 |
+
if encoding != 'counter':
|
| 284 |
+
y_train = None
|
| 285 |
+
|
| 286 |
+
# Step 1. Map strings to 0-based ranges
|
| 287 |
+
|
| 288 |
+
if encoding is None:
|
| 289 |
+
unknown_value = np.iinfo('int64').max - 3
|
| 290 |
+
oe = sklearn.preprocessing.OrdinalEncoder(
|
| 291 |
+
handle_unknown='use_encoded_value', # type: ignore[code]
|
| 292 |
+
unknown_value=unknown_value, # type: ignore[code]
|
| 293 |
+
dtype='int64', # type: ignore[code]
|
| 294 |
+
).fit(X['train'])
|
| 295 |
+
encoder = make_pipeline(oe)
|
| 296 |
+
encoder.fit(X['train'])
|
| 297 |
+
X = {k: encoder.transform(v) for k, v in X.items()}
|
| 298 |
+
max_values = X['train'].max(axis=0)
|
| 299 |
+
for part in X.keys():
|
| 300 |
+
if part == 'train': continue
|
| 301 |
+
for column_idx in range(X[part].shape[1]):
|
| 302 |
+
X[part][X[part][:, column_idx] == unknown_value, column_idx] = (
|
| 303 |
+
max_values[column_idx] + 1
|
| 304 |
+
)
|
| 305 |
+
if return_encoder:
|
| 306 |
+
return (X, False, encoder)
|
| 307 |
+
return (X, False)
|
| 308 |
+
|
| 309 |
+
# Step 2. Encode.
|
| 310 |
+
|
| 311 |
+
elif encoding == 'one-hot':
|
| 312 |
+
ohe = sklearn.preprocessing.OneHotEncoder(
|
| 313 |
+
handle_unknown='ignore', sparse=False, dtype=np.float32 # type: ignore[code]
|
| 314 |
+
)
|
| 315 |
+
encoder = make_pipeline(ohe)
|
| 316 |
+
|
| 317 |
+
# encoder.steps.append(('ohe', ohe))
|
| 318 |
+
encoder.fit(X['train'])
|
| 319 |
+
X = {k: encoder.transform(v) for k, v in X.items()}
|
| 320 |
+
elif encoding == 'counter':
|
| 321 |
+
assert y_train is not None
|
| 322 |
+
assert seed is not None
|
| 323 |
+
loe = LeaveOneOutEncoder(sigma=0.1, random_state=seed, return_df=False)
|
| 324 |
+
encoder.steps.append(('loe', loe))
|
| 325 |
+
encoder.fit(X['train'], y_train)
|
| 326 |
+
X = {k: encoder.transform(v).astype('float32') for k, v in X.items()} # type: ignore[code]
|
| 327 |
+
if not isinstance(X['train'], pd.DataFrame):
|
| 328 |
+
X = {k: v.values for k, v in X.items()} # type: ignore[code]
|
| 329 |
+
else:
|
| 330 |
+
util.raise_unknown('encoding', encoding)
|
| 331 |
+
|
| 332 |
+
if return_encoder:
|
| 333 |
+
return X, True, encoder # type: ignore[code]
|
| 334 |
+
return (X, True)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def build_target(
|
| 338 |
+
y: ArrayDict, policy: Optional[YPolicy], task_type: TaskType
|
| 339 |
+
) -> Tuple[ArrayDict, Dict[str, Any]]:
|
| 340 |
+
info: Dict[str, Any] = {'policy': policy}
|
| 341 |
+
if policy is None:
|
| 342 |
+
pass
|
| 343 |
+
elif policy == 'default':
|
| 344 |
+
if task_type == TaskType.REGRESSION:
|
| 345 |
+
mean, std = float(y['train'].mean()), float(y['train'].std())
|
| 346 |
+
y = {k: (v - mean) / std for k, v in y.items()}
|
| 347 |
+
info['mean'] = mean
|
| 348 |
+
info['std'] = std
|
| 349 |
+
else:
|
| 350 |
+
util.raise_unknown('policy', policy)
|
| 351 |
+
return y, info
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
@dataclass(frozen=True)
|
| 355 |
+
class Transformations:
|
| 356 |
+
seed: int = 0
|
| 357 |
+
normalization: Optional[Normalization] = None
|
| 358 |
+
num_nan_policy: Optional[NumNanPolicy] = None
|
| 359 |
+
cat_nan_policy: Optional[CatNanPolicy] = None
|
| 360 |
+
cat_min_frequency: Optional[float] = None
|
| 361 |
+
cat_encoding: Optional[CatEncoding] = None
|
| 362 |
+
y_policy: Optional[YPolicy] = 'default'
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def transform_dataset(
|
| 366 |
+
dataset: Dataset,
|
| 367 |
+
transformations: Transformations,
|
| 368 |
+
cache_dir: Optional[Path],
|
| 369 |
+
return_transforms: bool = False
|
| 370 |
+
) -> Dataset:
|
| 371 |
+
# WARNING: the order of transformations matters. Moreover, the current
|
| 372 |
+
# implementation is not ideal in that sense.
|
| 373 |
+
if cache_dir is not None:
|
| 374 |
+
transformations_md5 = hashlib.md5(
|
| 375 |
+
str(transformations).encode('utf-8')
|
| 376 |
+
).hexdigest()
|
| 377 |
+
transformations_str = '__'.join(map(str, astuple(transformations)))
|
| 378 |
+
cache_path = (
|
| 379 |
+
cache_dir / f'cache__{transformations_str}__{transformations_md5}.pickle'
|
| 380 |
+
)
|
| 381 |
+
if cache_path.exists():
|
| 382 |
+
cache_transformations, value = util.load_pickle(cache_path)
|
| 383 |
+
if transformations == cache_transformations:
|
| 384 |
+
print(
|
| 385 |
+
f"Using cached features: {cache_dir.name + '/' + cache_path.name}"
|
| 386 |
+
)
|
| 387 |
+
return value
|
| 388 |
+
else:
|
| 389 |
+
raise RuntimeError(f'Hash collision for {cache_path}')
|
| 390 |
+
else:
|
| 391 |
+
cache_path = None
|
| 392 |
+
|
| 393 |
+
if dataset.X_num is not None:
|
| 394 |
+
dataset = num_process_nans(dataset, transformations.num_nan_policy)
|
| 395 |
+
|
| 396 |
+
num_transform = None
|
| 397 |
+
cat_transform = None
|
| 398 |
+
X_num = dataset.X_num
|
| 399 |
+
|
| 400 |
+
if X_num is not None and transformations.normalization is not None:
|
| 401 |
+
X_num, num_transform = normalize(
|
| 402 |
+
X_num,
|
| 403 |
+
transformations.normalization,
|
| 404 |
+
transformations.seed,
|
| 405 |
+
return_normalizer=True
|
| 406 |
+
)
|
| 407 |
+
num_transform = num_transform
|
| 408 |
+
|
| 409 |
+
if dataset.X_cat is None:
|
| 410 |
+
assert transformations.cat_nan_policy is None
|
| 411 |
+
assert transformations.cat_min_frequency is None
|
| 412 |
+
# assert transformations.cat_encoding is None
|
| 413 |
+
X_cat = None
|
| 414 |
+
else:
|
| 415 |
+
X_cat = cat_process_nans(dataset.X_cat, transformations.cat_nan_policy)
|
| 416 |
+
if transformations.cat_min_frequency is not None:
|
| 417 |
+
X_cat = cat_drop_rare(X_cat, transformations.cat_min_frequency)
|
| 418 |
+
X_cat, is_num, cat_transform = cat_encode(
|
| 419 |
+
X_cat,
|
| 420 |
+
transformations.cat_encoding,
|
| 421 |
+
dataset.y['train'],
|
| 422 |
+
transformations.seed,
|
| 423 |
+
return_encoder=True
|
| 424 |
+
)
|
| 425 |
+
if is_num:
|
| 426 |
+
X_num = (
|
| 427 |
+
X_cat
|
| 428 |
+
if X_num is None
|
| 429 |
+
else {x: np.hstack([X_num[x], X_cat[x]]) for x in X_num}
|
| 430 |
+
)
|
| 431 |
+
X_cat = None
|
| 432 |
+
|
| 433 |
+
y, y_info = build_target(dataset.y, transformations.y_policy, dataset.task_type)
|
| 434 |
+
|
| 435 |
+
dataset = replace(dataset, X_num=X_num, X_cat=X_cat, y=y, y_info=y_info)
|
| 436 |
+
dataset.num_transform = num_transform
|
| 437 |
+
dataset.cat_transform = cat_transform
|
| 438 |
+
|
| 439 |
+
if cache_path is not None:
|
| 440 |
+
util.dump_pickle((transformations, dataset), cache_path)
|
| 441 |
+
# if return_transforms:
|
| 442 |
+
# return dataset, num_transform, cat_transform
|
| 443 |
+
return dataset
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def build_dataset(
|
| 447 |
+
path: Union[str, Path],
|
| 448 |
+
transformations: Transformations,
|
| 449 |
+
cache: bool
|
| 450 |
+
) -> Dataset:
|
| 451 |
+
path = Path(path)
|
| 452 |
+
dataset = Dataset.from_dir(path)
|
| 453 |
+
return transform_dataset(dataset, transformations, path if cache else None)
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def prepare_tensors(
|
| 457 |
+
dataset: Dataset, device: Union[str, torch.device]
|
| 458 |
+
) -> Tuple[Optional[TensorDict], Optional[TensorDict], TensorDict]:
|
| 459 |
+
X_num, X_cat, Y = (
|
| 460 |
+
None if x is None else {k: torch.as_tensor(v) for k, v in x.items()}
|
| 461 |
+
for x in [dataset.X_num, dataset.X_cat, dataset.y]
|
| 462 |
+
)
|
| 463 |
+
if device.type != 'cpu':
|
| 464 |
+
X_num, X_cat, Y = (
|
| 465 |
+
None if x is None else {k: v.to(device) for k, v in x.items()}
|
| 466 |
+
for x in [X_num, X_cat, Y]
|
| 467 |
+
)
|
| 468 |
+
assert X_num is not None
|
| 469 |
+
assert Y is not None
|
| 470 |
+
if not dataset.is_multiclass:
|
| 471 |
+
Y = {k: v.float() for k, v in Y.items()}
|
| 472 |
+
return X_num, X_cat, Y
|
| 473 |
+
|
| 474 |
+
###############
|
| 475 |
+
## DataLoader##
|
| 476 |
+
###############
|
| 477 |
+
|
| 478 |
+
class TabDataset(torch.utils.data.Dataset):
|
| 479 |
+
def __init__(
|
| 480 |
+
self, dataset : Dataset, split : Literal['train', 'val', 'test']
|
| 481 |
+
):
|
| 482 |
+
super().__init__()
|
| 483 |
+
|
| 484 |
+
self.X_num = torch.from_numpy(dataset.X_num[split]) if dataset.X_num is not None else None
|
| 485 |
+
self.X_cat = torch.from_numpy(dataset.X_cat[split]) if dataset.X_cat is not None else None
|
| 486 |
+
self.y = torch.from_numpy(dataset.y[split])
|
| 487 |
+
|
| 488 |
+
assert self.y is not None
|
| 489 |
+
assert self.X_num is not None or self.X_cat is not None
|
| 490 |
+
|
| 491 |
+
def __len__(self):
|
| 492 |
+
return len(self.y)
|
| 493 |
+
|
| 494 |
+
def __getitem__(self, idx):
|
| 495 |
+
out_dict = {
|
| 496 |
+
'y': self.y[idx].long() if self.y is not None else None,
|
| 497 |
+
}
|
| 498 |
+
|
| 499 |
+
x = np.empty((0,))
|
| 500 |
+
if self.X_num is not None:
|
| 501 |
+
x = self.X_num[idx]
|
| 502 |
+
if self.X_cat is not None:
|
| 503 |
+
x = torch.cat([x, self.X_cat[idx]], dim=0)
|
| 504 |
+
return x.float(), out_dict
|
| 505 |
+
|
| 506 |
+
def prepare_dataloader(
|
| 507 |
+
dataset : Dataset,
|
| 508 |
+
split : str,
|
| 509 |
+
batch_size: int,
|
| 510 |
+
):
|
| 511 |
+
|
| 512 |
+
torch_dataset = TabDataset(dataset, split)
|
| 513 |
+
loader = torch.utils.data.DataLoader(
|
| 514 |
+
torch_dataset,
|
| 515 |
+
batch_size=batch_size,
|
| 516 |
+
shuffle=(split == 'train'),
|
| 517 |
+
num_workers=1,
|
| 518 |
+
)
|
| 519 |
+
while True:
|
| 520 |
+
yield from loader
|
| 521 |
+
|
| 522 |
+
def prepare_torch_dataloader(
|
| 523 |
+
dataset : Dataset,
|
| 524 |
+
split : str,
|
| 525 |
+
shuffle : bool,
|
| 526 |
+
batch_size: int,
|
| 527 |
+
) -> torch.utils.data.DataLoader:
|
| 528 |
+
|
| 529 |
+
torch_dataset = TabDataset(dataset, split)
|
| 530 |
+
loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=1)
|
| 531 |
+
|
| 532 |
+
return loader
|
| 533 |
+
|
| 534 |
+
def dataset_from_csv(paths : Dict[str, str], cat_features, target, T):
|
| 535 |
+
assert 'train' in paths
|
| 536 |
+
y = {}
|
| 537 |
+
X_num = {}
|
| 538 |
+
X_cat = {} if len(cat_features) else None
|
| 539 |
+
for split in paths.keys():
|
| 540 |
+
df = pd.read_csv(paths[split])
|
| 541 |
+
y[split] = df[target].to_numpy().astype(float)
|
| 542 |
+
if X_cat is not None:
|
| 543 |
+
X_cat[split] = df[cat_features].to_numpy().astype(str)
|
| 544 |
+
X_num[split] = df.drop(cat_features + [target], axis=1).to_numpy().astype(float)
|
| 545 |
+
|
| 546 |
+
dataset = Dataset(X_num, X_cat, y, {}, None, len(np.unique(y['train'])))
|
| 547 |
+
return transform_dataset(dataset, T, None)
|
| 548 |
+
|
| 549 |
+
class FastTensorDataLoader:
|
| 550 |
+
"""
|
| 551 |
+
A DataLoader-like object for a set of tensors that can be much faster than
|
| 552 |
+
TensorDataset + DataLoader because dataloader grabs individual indices of
|
| 553 |
+
the dataset and calls cat (slow).
|
| 554 |
+
Source: https://discuss.pytorch.org/t/dataloader-much-slower-than-manual-batching/27014/6
|
| 555 |
+
"""
|
| 556 |
+
def __init__(self, *tensors, batch_size=32, shuffle=False):
|
| 557 |
+
"""
|
| 558 |
+
Initialize a FastTensorDataLoader.
|
| 559 |
+
:param *tensors: tensors to store. Must have the same length @ dim 0.
|
| 560 |
+
:param batch_size: batch size to load.
|
| 561 |
+
:param shuffle: if True, shuffle the data *in-place* whenever an
|
| 562 |
+
iterator is created out of this object.
|
| 563 |
+
:returns: A FastTensorDataLoader.
|
| 564 |
+
"""
|
| 565 |
+
assert all(t.shape[0] == tensors[0].shape[0] for t in tensors)
|
| 566 |
+
self.tensors = tensors
|
| 567 |
+
|
| 568 |
+
self.dataset_len = self.tensors[0].shape[0]
|
| 569 |
+
self.batch_size = batch_size
|
| 570 |
+
self.shuffle = shuffle
|
| 571 |
+
|
| 572 |
+
# Calculate # batches
|
| 573 |
+
n_batches, remainder = divmod(self.dataset_len, self.batch_size)
|
| 574 |
+
if remainder > 0:
|
| 575 |
+
n_batches += 1
|
| 576 |
+
self.n_batches = n_batches
|
| 577 |
+
def __iter__(self):
|
| 578 |
+
if self.shuffle:
|
| 579 |
+
r = torch.randperm(self.dataset_len)
|
| 580 |
+
self.tensors = [t[r] for t in self.tensors]
|
| 581 |
+
self.i = 0
|
| 582 |
+
return self
|
| 583 |
+
|
| 584 |
+
def __next__(self):
|
| 585 |
+
if self.i >= self.dataset_len:
|
| 586 |
+
raise StopIteration
|
| 587 |
+
batch = tuple(t[self.i:self.i+self.batch_size] for t in self.tensors)
|
| 588 |
+
self.i += self.batch_size
|
| 589 |
+
return batch
|
| 590 |
+
|
| 591 |
+
def __len__(self):
|
| 592 |
+
return self.n_batches
|
| 593 |
+
|
| 594 |
+
def prepare_fast_dataloader(
|
| 595 |
+
D : Dataset,
|
| 596 |
+
split : str,
|
| 597 |
+
batch_size: int
|
| 598 |
+
):
|
| 599 |
+
if D.X_cat is not None:
|
| 600 |
+
if D.X_num is not None:
|
| 601 |
+
X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
|
| 602 |
+
else:
|
| 603 |
+
X = torch.from_numpy(D.X_cat[split]).float()
|
| 604 |
+
else:
|
| 605 |
+
X = torch.from_numpy(D.X_num[split]).float()
|
| 606 |
+
y = torch.from_numpy(D.y[split])
|
| 607 |
+
dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train'))
|
| 608 |
+
while True:
|
| 609 |
+
yield from dataloader
|
| 610 |
+
|
| 611 |
+
def prepare_fast_torch_dataloader(
|
| 612 |
+
D : Dataset,
|
| 613 |
+
split : str,
|
| 614 |
+
batch_size: int
|
| 615 |
+
):
|
| 616 |
+
if D.X_cat is not None:
|
| 617 |
+
X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
|
| 618 |
+
else:
|
| 619 |
+
X = torch.from_numpy(D.X_num[split]).float()
|
| 620 |
+
y = torch.from_numpy(D.y[split])
|
| 621 |
+
dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train'))
|
| 622 |
+
return dataloader
|
| 623 |
+
|
| 624 |
+
def round_columns(X_real, X_synth, columns):
|
| 625 |
+
for col in columns:
|
| 626 |
+
uniq = np.unique(X_real[:,col])
|
| 627 |
+
dist = cdist(X_synth[:, col][:, np.newaxis].astype(float), uniq[:, np.newaxis].astype(float))
|
| 628 |
+
X_synth[:, col] = uniq[dist.argmin(axis=1)]
|
| 629 |
+
return X_synth
|
| 630 |
+
|
| 631 |
+
def concat_features(D : Dataset):
|
| 632 |
+
if D.X_num is None:
|
| 633 |
+
assert D.X_cat is not None
|
| 634 |
+
X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_cat.items()}
|
| 635 |
+
elif D.X_cat is None:
|
| 636 |
+
assert D.X_num is not None
|
| 637 |
+
X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_num.items()}
|
| 638 |
+
else:
|
| 639 |
+
X = {
|
| 640 |
+
part: pd.concat(
|
| 641 |
+
[
|
| 642 |
+
pd.DataFrame(D.X_num[part], columns=range(D.n_num_features)),
|
| 643 |
+
pd.DataFrame(
|
| 644 |
+
D.X_cat[part],
|
| 645 |
+
columns=range(D.n_num_features, D.n_features),
|
| 646 |
+
),
|
| 647 |
+
],
|
| 648 |
+
axis=1,
|
| 649 |
+
)
|
| 650 |
+
for part in D.y.keys()
|
| 651 |
+
}
|
| 652 |
+
|
| 653 |
+
return X
|
| 654 |
+
|
| 655 |
+
def concat_to_pd(X_num, X_cat, y):
|
| 656 |
+
if X_num is None:
|
| 657 |
+
return pd.concat([
|
| 658 |
+
pd.DataFrame(X_cat, columns=list(range(X_cat.shape[1]))),
|
| 659 |
+
pd.DataFrame(y, columns=['y'])
|
| 660 |
+
], axis=1)
|
| 661 |
+
if X_cat is not None:
|
| 662 |
+
return pd.concat([
|
| 663 |
+
pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
|
| 664 |
+
pd.DataFrame(X_cat, columns=list(range(X_num.shape[1], X_num.shape[1] + X_cat.shape[1]))),
|
| 665 |
+
pd.DataFrame(y, columns=['y'])
|
| 666 |
+
], axis=1)
|
| 667 |
+
return pd.concat([
|
| 668 |
+
pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
|
| 669 |
+
pd.DataFrame(y, columns=['y'])
|
| 670 |
+
], axis=1)
|
| 671 |
+
|
| 672 |
+
def read_pure_data(path, split='train'):
|
| 673 |
+
y = np.load(os.path.join(path, f'y_{split}.npy'), allow_pickle=True)
|
| 674 |
+
X_num = None
|
| 675 |
+
X_cat = None
|
| 676 |
+
if os.path.exists(os.path.join(path, f'X_num_{split}.npy')):
|
| 677 |
+
X_num = np.load(os.path.join(path, f'X_num_{split}.npy'), allow_pickle=True)
|
| 678 |
+
if os.path.exists(os.path.join(path, f'X_cat_{split}.npy')):
|
| 679 |
+
X_cat = np.load(os.path.join(path, f'X_cat_{split}.npy'), allow_pickle=True)
|
| 680 |
+
|
| 681 |
+
return X_num, X_cat, y
|
| 682 |
+
|
| 683 |
+
def read_changed_val(path, val_size=0.2):
|
| 684 |
+
path = Path(path)
|
| 685 |
+
X_num_train, X_cat_train, y_train = read_pure_data(path, 'train')
|
| 686 |
+
X_num_val, X_cat_val, y_val = read_pure_data(path, 'val')
|
| 687 |
+
is_regression = load_json(path / 'info.json')['task_type'] == 'regression'
|
| 688 |
+
|
| 689 |
+
y = np.concatenate([y_train, y_val], axis=0)
|
| 690 |
+
|
| 691 |
+
ixs = np.arange(y.shape[0])
|
| 692 |
+
if is_regression:
|
| 693 |
+
train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
|
| 694 |
+
else:
|
| 695 |
+
train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
|
| 696 |
+
y_train = y[train_ixs]
|
| 697 |
+
y_val = y[val_ixs]
|
| 698 |
+
|
| 699 |
+
if X_num_train is not None:
|
| 700 |
+
X_num = np.concatenate([X_num_train, X_num_val], axis=0)
|
| 701 |
+
X_num_train = X_num[train_ixs]
|
| 702 |
+
X_num_val = X_num[val_ixs]
|
| 703 |
+
|
| 704 |
+
if X_cat_train is not None:
|
| 705 |
+
X_cat = np.concatenate([X_cat_train, X_cat_val], axis=0)
|
| 706 |
+
X_cat_train = X_cat[train_ixs]
|
| 707 |
+
X_cat_val = X_cat[val_ixs]
|
| 708 |
+
|
| 709 |
+
return X_num_train, X_cat_train, y_train, X_num_val, X_cat_val, y_val
|
| 710 |
+
|
| 711 |
+
#############
|
| 712 |
+
|
| 713 |
+
def load_dataset_info(dataset_dir_name: str) -> Dict[str, Any]:
|
| 714 |
+
path = Path("data/" + dataset_dir_name)
|
| 715 |
+
info = util.load_json(path / 'info.json')
|
| 716 |
+
info['size'] = info['train_size'] + info['val_size'] + info['test_size']
|
| 717 |
+
info['n_features'] = info['n_num_features'] + info['n_cat_features']
|
| 718 |
+
info['path'] = path
|
| 719 |
+
return info
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/deep.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import statistics
|
| 2 |
+
from dataclasses import dataclass
|
| 3 |
+
from typing import Any, Callable, Literal, cast
|
| 4 |
+
|
| 5 |
+
import rtdl
|
| 6 |
+
import torch
|
| 7 |
+
import torch.nn as nn
|
| 8 |
+
import torch.nn.functional as F
|
| 9 |
+
import torch.optim as optim
|
| 10 |
+
import zero
|
| 11 |
+
from torch import Tensor
|
| 12 |
+
|
| 13 |
+
from .util import TaskType
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def cos_sin(x: Tensor) -> Tensor:
|
| 17 |
+
return torch.cat([torch.cos(x), torch.sin(x)], -1)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class PeriodicOptions:
|
| 22 |
+
n: int # the output size is 2 * n
|
| 23 |
+
sigma: float
|
| 24 |
+
trainable: bool
|
| 25 |
+
initialization: Literal['log-linear', 'normal']
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Periodic(nn.Module):
|
| 29 |
+
def __init__(self, n_features: int, options: PeriodicOptions) -> None:
|
| 30 |
+
super().__init__()
|
| 31 |
+
if options.initialization == 'log-linear':
|
| 32 |
+
coefficients = options.sigma ** (torch.arange(options.n) / options.n)
|
| 33 |
+
coefficients = coefficients[None].repeat(n_features, 1)
|
| 34 |
+
else:
|
| 35 |
+
assert options.initialization == 'normal'
|
| 36 |
+
coefficients = torch.normal(0.0, options.sigma, (n_features, options.n))
|
| 37 |
+
if options.trainable:
|
| 38 |
+
self.coefficients = nn.Parameter(coefficients) # type: ignore[code]
|
| 39 |
+
else:
|
| 40 |
+
self.register_buffer('coefficients', coefficients)
|
| 41 |
+
|
| 42 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 43 |
+
assert x.ndim == 2
|
| 44 |
+
return cos_sin(2 * torch.pi * self.coefficients[None] * x[..., None])
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_n_parameters(m: nn.Module):
|
| 48 |
+
return sum(x.numel() for x in m.parameters() if x.requires_grad)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def get_loss_fn(task_type: TaskType) -> Callable[..., Tensor]:
|
| 52 |
+
return (
|
| 53 |
+
F.binary_cross_entropy_with_logits
|
| 54 |
+
if task_type == TaskType.BINCLASS
|
| 55 |
+
else F.cross_entropy
|
| 56 |
+
if task_type == TaskType.MULTICLASS
|
| 57 |
+
else F.mse_loss
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def default_zero_weight_decay_condition(module_name, module, parameter_name, parameter):
|
| 62 |
+
del module_name, parameter
|
| 63 |
+
return parameter_name.endswith('bias') or isinstance(
|
| 64 |
+
module,
|
| 65 |
+
(
|
| 66 |
+
nn.BatchNorm1d,
|
| 67 |
+
nn.LayerNorm,
|
| 68 |
+
nn.InstanceNorm1d,
|
| 69 |
+
rtdl.CLSToken,
|
| 70 |
+
rtdl.NumericalFeatureTokenizer,
|
| 71 |
+
rtdl.CategoricalFeatureTokenizer,
|
| 72 |
+
Periodic,
|
| 73 |
+
),
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def split_parameters_by_weight_decay(
|
| 78 |
+
model: nn.Module, zero_weight_decay_condition=default_zero_weight_decay_condition
|
| 79 |
+
) -> list[dict[str, Any]]:
|
| 80 |
+
parameters_info = {}
|
| 81 |
+
for module_name, module in model.named_modules():
|
| 82 |
+
for parameter_name, parameter in module.named_parameters():
|
| 83 |
+
full_parameter_name = (
|
| 84 |
+
f'{module_name}.{parameter_name}' if module_name else parameter_name
|
| 85 |
+
)
|
| 86 |
+
parameters_info.setdefault(full_parameter_name, ([], parameter))[0].append(
|
| 87 |
+
zero_weight_decay_condition(
|
| 88 |
+
module_name, module, parameter_name, parameter
|
| 89 |
+
)
|
| 90 |
+
)
|
| 91 |
+
params_with_wd = {'params': []}
|
| 92 |
+
params_without_wd = {'params': [], 'weight_decay': 0.0}
|
| 93 |
+
for full_parameter_name, (results, parameter) in parameters_info.items():
|
| 94 |
+
(params_without_wd if any(results) else params_with_wd)['params'].append(
|
| 95 |
+
parameter
|
| 96 |
+
)
|
| 97 |
+
return [params_with_wd, params_without_wd]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def make_optimizer(
|
| 101 |
+
config: dict[str, Any],
|
| 102 |
+
parameter_groups,
|
| 103 |
+
) -> optim.Optimizer:
|
| 104 |
+
if config['optimizer'] == 'FT-Transformer-default':
|
| 105 |
+
return optim.AdamW(parameter_groups, lr=1e-4, weight_decay=1e-5)
|
| 106 |
+
return getattr(optim, config['optimizer'])(
|
| 107 |
+
parameter_groups,
|
| 108 |
+
**{x: config[x] for x in ['lr', 'weight_decay', 'momentum'] if x in config},
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def get_lr(optimizer: optim.Optimizer) -> float:
|
| 113 |
+
return next(iter(optimizer.param_groups))['lr']
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def is_oom_exception(err: RuntimeError) -> bool:
|
| 117 |
+
return any(
|
| 118 |
+
x in str(err)
|
| 119 |
+
for x in [
|
| 120 |
+
'CUDA out of memory',
|
| 121 |
+
'CUBLAS_STATUS_ALLOC_FAILED',
|
| 122 |
+
'CUDA error: out of memory',
|
| 123 |
+
]
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def train_with_auto_virtual_batch(
|
| 128 |
+
optimizer,
|
| 129 |
+
loss_fn,
|
| 130 |
+
step,
|
| 131 |
+
batch,
|
| 132 |
+
chunk_size: int,
|
| 133 |
+
) -> tuple[Tensor, int]:
|
| 134 |
+
batch_size = len(batch)
|
| 135 |
+
random_state = zero.random.get_state()
|
| 136 |
+
loss = None
|
| 137 |
+
while chunk_size != 0:
|
| 138 |
+
try:
|
| 139 |
+
zero.random.set_state(random_state)
|
| 140 |
+
optimizer.zero_grad()
|
| 141 |
+
if batch_size <= chunk_size:
|
| 142 |
+
loss = loss_fn(*step(batch))
|
| 143 |
+
loss.backward()
|
| 144 |
+
else:
|
| 145 |
+
loss = None
|
| 146 |
+
for chunk in zero.iter_batches(batch, chunk_size):
|
| 147 |
+
chunk_loss = loss_fn(*step(chunk))
|
| 148 |
+
chunk_loss = chunk_loss * (len(chunk) / batch_size)
|
| 149 |
+
chunk_loss.backward()
|
| 150 |
+
if loss is None:
|
| 151 |
+
loss = chunk_loss.detach()
|
| 152 |
+
else:
|
| 153 |
+
loss += chunk_loss.detach()
|
| 154 |
+
except RuntimeError as err:
|
| 155 |
+
if not is_oom_exception(err):
|
| 156 |
+
raise
|
| 157 |
+
chunk_size //= 2
|
| 158 |
+
else:
|
| 159 |
+
break
|
| 160 |
+
if not chunk_size:
|
| 161 |
+
raise RuntimeError('Not enough memory even for batch_size=1')
|
| 162 |
+
optimizer.step()
|
| 163 |
+
return cast(Tensor, loss), chunk_size
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def process_epoch_losses(losses: list[Tensor]) -> tuple[list[float], float]:
|
| 167 |
+
losses_ = torch.stack(losses).tolist()
|
| 168 |
+
return losses_, statistics.mean(losses_)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/env.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Have not used in TabDDPM project.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import datetime
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import typing as ty
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
PROJ = Path('tab-ddpm/').absolute().resolve()
|
| 12 |
+
EXP = PROJ / 'exp'
|
| 13 |
+
DATA = PROJ / 'data'
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def get_path(path: ty.Union[str, Path]) -> Path:
|
| 17 |
+
if isinstance(path, str):
|
| 18 |
+
path = Path(path)
|
| 19 |
+
if not path.is_absolute():
|
| 20 |
+
path = PROJ / path
|
| 21 |
+
return path.resolve()
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_relative_path(path: ty.Union[str, Path]) -> Path:
|
| 25 |
+
return get_path(path).relative_to(PROJ)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def duplicate_path(
|
| 29 |
+
src: ty.Union[str, Path], alternative_project_dir: ty.Union[str, Path]
|
| 30 |
+
) -> None:
|
| 31 |
+
src = get_path(src)
|
| 32 |
+
alternative_project_dir = get_path(alternative_project_dir)
|
| 33 |
+
dst = alternative_project_dir / src.relative_to(PROJ)
|
| 34 |
+
dst.parent.mkdir(parents=True, exist_ok=True)
|
| 35 |
+
if dst.exists():
|
| 36 |
+
dst = dst.with_name(
|
| 37 |
+
dst.name + '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
|
| 38 |
+
)
|
| 39 |
+
(shutil.copytree if src.is_dir() else shutil.copyfile)(src, dst)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/metrics.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import enum
|
| 2 |
+
from typing import Any, Optional, Tuple, Dict, Union, cast
|
| 3 |
+
from functools import partial
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import scipy.special
|
| 7 |
+
import sklearn.metrics as skm
|
| 8 |
+
|
| 9 |
+
from . import util
|
| 10 |
+
from .util import TaskType
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class PredictionType(enum.Enum):
|
| 14 |
+
LOGITS = 'logits'
|
| 15 |
+
PROBS = 'probs'
|
| 16 |
+
|
| 17 |
+
class MetricsReport:
|
| 18 |
+
def __init__(self, report: dict, task_type: TaskType):
|
| 19 |
+
self._res = {k: {} for k in report.keys()}
|
| 20 |
+
if task_type in (TaskType.BINCLASS, TaskType.MULTICLASS):
|
| 21 |
+
self._metrics_names = ["acc", "f1"]
|
| 22 |
+
for k in report.keys():
|
| 23 |
+
self._res[k]["acc"] = report[k]["accuracy"]
|
| 24 |
+
self._res[k]["f1"] = report[k]["macro avg"]["f1-score"]
|
| 25 |
+
if task_type == TaskType.BINCLASS:
|
| 26 |
+
self._res[k]["roc_auc"] = report[k]["roc_auc"]
|
| 27 |
+
self._metrics_names.append("roc_auc")
|
| 28 |
+
|
| 29 |
+
elif task_type == TaskType.REGRESSION:
|
| 30 |
+
self._metrics_names = ["r2", "rmse"]
|
| 31 |
+
for k in report.keys():
|
| 32 |
+
self._res[k]["r2"] = report[k]["r2"]
|
| 33 |
+
self._res[k]["rmse"] = report[k]["rmse"]
|
| 34 |
+
else:
|
| 35 |
+
raise "Unknown TaskType!"
|
| 36 |
+
|
| 37 |
+
def get_splits_names(self) -> list[str]:
|
| 38 |
+
return self._res.keys()
|
| 39 |
+
|
| 40 |
+
def get_metrics_names(self) -> list[str]:
|
| 41 |
+
return self._metrics_names
|
| 42 |
+
|
| 43 |
+
def get_metric(self, split: str, metric: str) -> float:
|
| 44 |
+
return self._res[split][metric]
|
| 45 |
+
|
| 46 |
+
def get_val_score(self) -> float:
|
| 47 |
+
return self._res["val"]["r2"] if "r2" in self._res["val"] else self._res["val"]["f1"]
|
| 48 |
+
|
| 49 |
+
def get_test_score(self) -> float:
|
| 50 |
+
return self._res["test"]["r2"] if "r2" in self._res["test"] else self._res["test"]["f1"]
|
| 51 |
+
|
| 52 |
+
def print_metrics(self) -> None:
|
| 53 |
+
res = {
|
| 54 |
+
"val": {k: np.around(self._res["val"][k], 4) for k in self._res["val"]},
|
| 55 |
+
"test": {k: np.around(self._res["test"][k], 4) for k in self._res["test"]}
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
print("*"*100)
|
| 59 |
+
print("[val]")
|
| 60 |
+
print(res["val"])
|
| 61 |
+
print("[test]")
|
| 62 |
+
print(res["test"])
|
| 63 |
+
|
| 64 |
+
return res
|
| 65 |
+
|
| 66 |
+
class SeedsMetricsReport:
|
| 67 |
+
def __init__(self):
|
| 68 |
+
self._reports = []
|
| 69 |
+
|
| 70 |
+
def add_report(self, report: MetricsReport) -> None:
|
| 71 |
+
self._reports.append(report)
|
| 72 |
+
|
| 73 |
+
def get_mean_std(self) -> dict:
|
| 74 |
+
res = {k: {} for k in ["train", "val", "test"]}
|
| 75 |
+
for split in self._reports[0].get_splits_names():
|
| 76 |
+
for metric in self._reports[0].get_metrics_names():
|
| 77 |
+
res[split][metric] = [x.get_metric(split, metric) for x in self._reports]
|
| 78 |
+
|
| 79 |
+
agg_res = {k: {} for k in ["train", "val", "test"]}
|
| 80 |
+
for split in self._reports[0].get_splits_names():
|
| 81 |
+
for metric in self._reports[0].get_metrics_names():
|
| 82 |
+
for k, f in [("count", len), ("mean", np.mean), ("std", np.std)]:
|
| 83 |
+
agg_res[split][f"{metric}-{k}"] = f(res[split][metric])
|
| 84 |
+
self._res = res
|
| 85 |
+
self._agg_res = agg_res
|
| 86 |
+
|
| 87 |
+
return agg_res
|
| 88 |
+
|
| 89 |
+
def print_result(self) -> dict:
|
| 90 |
+
res = {split: {k: float(np.around(self._agg_res[split][k], 4)) for k in self._agg_res[split]} for split in ["val", "test"]}
|
| 91 |
+
print("="*100)
|
| 92 |
+
print("EVAL RESULTS:")
|
| 93 |
+
print("[val]")
|
| 94 |
+
print(res["val"])
|
| 95 |
+
print("[test]")
|
| 96 |
+
print(res["test"])
|
| 97 |
+
print("="*100)
|
| 98 |
+
return res
|
| 99 |
+
|
| 100 |
+
def calculate_rmse(
|
| 101 |
+
y_true: np.ndarray, y_pred: np.ndarray, std: Optional[float]
|
| 102 |
+
) -> float:
|
| 103 |
+
rmse = skm.mean_squared_error(y_true, y_pred) ** 0.5
|
| 104 |
+
if std is not None:
|
| 105 |
+
rmse *= std
|
| 106 |
+
return rmse
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def _get_labels_and_probs(
|
| 110 |
+
y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType]
|
| 111 |
+
) -> Tuple[np.ndarray, Optional[np.ndarray]]:
|
| 112 |
+
assert task_type in (TaskType.BINCLASS, TaskType.MULTICLASS)
|
| 113 |
+
|
| 114 |
+
if prediction_type is None:
|
| 115 |
+
return y_pred, None
|
| 116 |
+
|
| 117 |
+
if prediction_type == PredictionType.LOGITS:
|
| 118 |
+
probs = (
|
| 119 |
+
scipy.special.expit(y_pred)
|
| 120 |
+
if task_type == TaskType.BINCLASS
|
| 121 |
+
else scipy.special.softmax(y_pred, axis=1)
|
| 122 |
+
)
|
| 123 |
+
elif prediction_type == PredictionType.PROBS:
|
| 124 |
+
probs = y_pred
|
| 125 |
+
else:
|
| 126 |
+
util.raise_unknown('prediction_type', prediction_type)
|
| 127 |
+
|
| 128 |
+
assert probs is not None
|
| 129 |
+
labels = np.round(probs) if task_type == TaskType.BINCLASS else probs.argmax(axis=1)
|
| 130 |
+
return labels.astype('int64'), probs
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def calculate_metrics(
|
| 134 |
+
y_true: np.ndarray,
|
| 135 |
+
y_pred: np.ndarray,
|
| 136 |
+
task_type: Union[str, TaskType],
|
| 137 |
+
prediction_type: Optional[Union[str, PredictionType]],
|
| 138 |
+
y_info: Dict[str, Any],
|
| 139 |
+
) -> Dict[str, Any]:
|
| 140 |
+
# Example: calculate_metrics(y_true, y_pred, 'binclass', 'logits', {})
|
| 141 |
+
task_type = TaskType(task_type)
|
| 142 |
+
if prediction_type is not None:
|
| 143 |
+
prediction_type = PredictionType(prediction_type)
|
| 144 |
+
|
| 145 |
+
if task_type == TaskType.REGRESSION:
|
| 146 |
+
assert prediction_type is None
|
| 147 |
+
assert 'std' in y_info
|
| 148 |
+
rmse = calculate_rmse(y_true, y_pred, y_info['std'])
|
| 149 |
+
r2 = skm.r2_score(y_true, y_pred)
|
| 150 |
+
result = {'rmse': rmse, 'r2': r2}
|
| 151 |
+
else:
|
| 152 |
+
labels, probs = _get_labels_and_probs(y_pred, task_type, prediction_type)
|
| 153 |
+
result = cast(
|
| 154 |
+
Dict[str, Any], skm.classification_report(y_true, labels, output_dict=True)
|
| 155 |
+
)
|
| 156 |
+
if task_type == TaskType.BINCLASS:
|
| 157 |
+
result['roc_auc'] = skm.roc_auc_score(y_true, probs)
|
| 158 |
+
return result
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/util.py
ADDED
|
@@ -0,0 +1,433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import atexit
|
| 3 |
+
import enum
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
import pickle
|
| 7 |
+
import shutil
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
import uuid
|
| 11 |
+
from copy import deepcopy
|
| 12 |
+
from dataclasses import asdict, fields, is_dataclass
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from pprint import pprint
|
| 15 |
+
from typing import Any, Callable, List, Dict, Type, Optional, Tuple, TypeVar, Union, cast, get_args, get_origin
|
| 16 |
+
|
| 17 |
+
import __main__
|
| 18 |
+
import numpy as np
|
| 19 |
+
import tomli
|
| 20 |
+
import tomli_w
|
| 21 |
+
import torch
|
| 22 |
+
import zero
|
| 23 |
+
|
| 24 |
+
from . import env
|
| 25 |
+
|
| 26 |
+
RawConfig = Dict[str, Any]
|
| 27 |
+
Report = Dict[str, Any]
|
| 28 |
+
T = TypeVar('T')
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class Part(enum.Enum):
|
| 32 |
+
TRAIN = 'train'
|
| 33 |
+
VAL = 'val'
|
| 34 |
+
TEST = 'test'
|
| 35 |
+
|
| 36 |
+
def __str__(self) -> str:
|
| 37 |
+
return self.value
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TaskType(enum.Enum):
|
| 41 |
+
BINCLASS = 'binclass'
|
| 42 |
+
MULTICLASS = 'multiclass'
|
| 43 |
+
REGRESSION = 'regression'
|
| 44 |
+
|
| 45 |
+
def __str__(self) -> str:
|
| 46 |
+
return self.value
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Timer(zero.Timer):
|
| 50 |
+
@classmethod
|
| 51 |
+
def launch(cls) -> 'Timer':
|
| 52 |
+
timer = cls()
|
| 53 |
+
timer.run()
|
| 54 |
+
return timer
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def update_training_log(training_log, data, metrics):
|
| 58 |
+
def _update(log_part, data_part):
|
| 59 |
+
for k, v in data_part.items():
|
| 60 |
+
if isinstance(v, dict):
|
| 61 |
+
_update(log_part.setdefault(k, {}), v)
|
| 62 |
+
elif isinstance(v, list):
|
| 63 |
+
log_part.setdefault(k, []).extend(v)
|
| 64 |
+
else:
|
| 65 |
+
log_part.setdefault(k, []).append(v)
|
| 66 |
+
|
| 67 |
+
_update(training_log, data)
|
| 68 |
+
transposed_metrics = {}
|
| 69 |
+
for part, part_metrics in metrics.items():
|
| 70 |
+
for metric_name, value in part_metrics.items():
|
| 71 |
+
transposed_metrics.setdefault(metric_name, {})[part] = value
|
| 72 |
+
_update(training_log, transposed_metrics)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def raise_unknown(unknown_what: str, unknown_value: Any):
|
| 76 |
+
raise ValueError(f'Unknown {unknown_what}: {unknown_value}')
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _replace(data, condition, value):
|
| 80 |
+
def do(x):
|
| 81 |
+
if isinstance(x, dict):
|
| 82 |
+
return {k: do(v) for k, v in x.items()}
|
| 83 |
+
elif isinstance(x, list):
|
| 84 |
+
return [do(y) for y in x]
|
| 85 |
+
else:
|
| 86 |
+
return value if condition(x) else x
|
| 87 |
+
|
| 88 |
+
return do(data)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
_CONFIG_NONE = '__none__'
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def unpack_config(config: RawConfig) -> RawConfig:
|
| 95 |
+
config = cast(RawConfig, _replace(config, lambda x: x == _CONFIG_NONE, None))
|
| 96 |
+
return config
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def pack_config(config: RawConfig) -> RawConfig:
|
| 100 |
+
config = cast(RawConfig, _replace(config, lambda x: x is None, _CONFIG_NONE))
|
| 101 |
+
return config
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def load_config(path: Union[Path, str]) -> Any:
|
| 105 |
+
with open(path, 'rb') as f:
|
| 106 |
+
return unpack_config(tomli.load(f))
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def dump_config(config: Any, path: Union[Path, str]) -> None:
|
| 110 |
+
with open(path, 'wb') as f:
|
| 111 |
+
tomli_w.dump(pack_config(config), f)
|
| 112 |
+
# check that there are no bugs in all these "pack/unpack" things
|
| 113 |
+
assert config == load_config(path)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def load_json(path: Union[Path, str], **kwargs) -> Any:
|
| 117 |
+
return json.loads(Path(path).read_text(), **kwargs)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def dump_json(x: Any, path: Union[Path, str], **kwargs) -> None:
|
| 121 |
+
kwargs.setdefault('indent', 4)
|
| 122 |
+
Path(path).write_text(json.dumps(x, **kwargs) + '\n')
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def load_pickle(path: Union[Path, str], **kwargs) -> Any:
|
| 126 |
+
return pickle.loads(Path(path).read_bytes(), **kwargs)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def dump_pickle(x: Any, path: Union[Path, str], **kwargs) -> None:
|
| 130 |
+
Path(path).write_bytes(pickle.dumps(x, **kwargs))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def load(path: Union[Path, str], **kwargs) -> Any:
|
| 134 |
+
return globals()[f'load_{Path(path).suffix[1:]}'](Path(path), **kwargs)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def dump(x: Any, path: Union[Path, str], **kwargs) -> Any:
|
| 138 |
+
return globals()[f'dump_{Path(path).suffix[1:]}'](x, Path(path), **kwargs)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _get_output_item_path(
|
| 142 |
+
path: Union[str, Path], filename: str, must_exist: bool
|
| 143 |
+
) -> Path:
|
| 144 |
+
path = env.get_path(path)
|
| 145 |
+
if path.suffix == '.toml':
|
| 146 |
+
path = path.with_suffix('')
|
| 147 |
+
if path.is_dir():
|
| 148 |
+
path = path / filename
|
| 149 |
+
else:
|
| 150 |
+
assert path.name == filename
|
| 151 |
+
assert path.parent.exists()
|
| 152 |
+
if must_exist:
|
| 153 |
+
assert path.exists()
|
| 154 |
+
return path
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def load_report(path: Path) -> Report:
|
| 158 |
+
return load_json(_get_output_item_path(path, 'report.json', True))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def dump_report(report: dict, path: Path) -> None:
|
| 162 |
+
dump_json(report, _get_output_item_path(path, 'report.json', False))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def load_predictions(path: Path) -> Dict[str, np.ndarray]:
|
| 166 |
+
with np.load(_get_output_item_path(path, 'predictions.npz', True)) as predictions:
|
| 167 |
+
return {x: predictions[x] for x in predictions}
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def dump_predictions(predictions: Dict[str, np.ndarray], path: Path) -> None:
|
| 171 |
+
np.savez(_get_output_item_path(path, 'predictions.npz', False), **predictions)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def dump_metrics(metrics: Dict[str, Any], path: Path) -> None:
|
| 175 |
+
dump_json(metrics, _get_output_item_path(path, 'metrics.json', False))
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def load_checkpoint(path: Path, *args, **kwargs) -> Dict[str, np.ndarray]:
|
| 179 |
+
return torch.load(
|
| 180 |
+
_get_output_item_path(path, 'checkpoint.pt', True), *args, **kwargs
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def get_device() -> torch.device:
|
| 185 |
+
if torch.cuda.is_available():
|
| 186 |
+
assert os.environ.get('CUDA_VISIBLE_DEVICES') is not None
|
| 187 |
+
return torch.device('cuda:0')
|
| 188 |
+
else:
|
| 189 |
+
return torch.device('cpu')
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def _print_sep(c, size=100):
|
| 193 |
+
print(c * size)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def start(
|
| 197 |
+
config_cls: Type[T] = RawConfig,
|
| 198 |
+
argv: Optional[List[str]] = None,
|
| 199 |
+
patch_raw_config: Optional[Callable[[RawConfig], None]] = None,
|
| 200 |
+
) -> Tuple[T, Path, Report]: # config # output dir # report
|
| 201 |
+
parser = argparse.ArgumentParser()
|
| 202 |
+
parser.add_argument('config', metavar='FILE')
|
| 203 |
+
parser.add_argument('--force', action='store_true')
|
| 204 |
+
parser.add_argument('--continue', action='store_true', dest='continue_')
|
| 205 |
+
if argv is None:
|
| 206 |
+
program = __main__.__file__
|
| 207 |
+
args = parser.parse_args()
|
| 208 |
+
else:
|
| 209 |
+
program = argv[0]
|
| 210 |
+
try:
|
| 211 |
+
args = parser.parse_args(argv[1:])
|
| 212 |
+
except Exception:
|
| 213 |
+
print(
|
| 214 |
+
'Failed to parse `argv`.'
|
| 215 |
+
' Remember that the first item of `argv` must be the path (relative to'
|
| 216 |
+
' the project root) to the script/notebook.'
|
| 217 |
+
)
|
| 218 |
+
raise
|
| 219 |
+
args = parser.parse_args(argv)
|
| 220 |
+
|
| 221 |
+
snapshot_dir = os.environ.get('SNAPSHOT_PATH')
|
| 222 |
+
if snapshot_dir and Path(snapshot_dir).joinpath('CHECKPOINTS_RESTORED').exists():
|
| 223 |
+
assert args.continue_
|
| 224 |
+
|
| 225 |
+
config_path = env.get_path(args.config)
|
| 226 |
+
output_dir = config_path.with_suffix('')
|
| 227 |
+
_print_sep('=')
|
| 228 |
+
print(f'[output] {output_dir}')
|
| 229 |
+
_print_sep('=')
|
| 230 |
+
|
| 231 |
+
assert config_path.exists()
|
| 232 |
+
raw_config = load_config(config_path)
|
| 233 |
+
if patch_raw_config is not None:
|
| 234 |
+
patch_raw_config(raw_config)
|
| 235 |
+
if is_dataclass(config_cls):
|
| 236 |
+
config = from_dict(config_cls, raw_config)
|
| 237 |
+
full_raw_config = asdict(config)
|
| 238 |
+
else:
|
| 239 |
+
assert config_cls is dict
|
| 240 |
+
full_raw_config = config = raw_config
|
| 241 |
+
full_raw_config = asdict(config)
|
| 242 |
+
|
| 243 |
+
if output_dir.exists():
|
| 244 |
+
if args.force:
|
| 245 |
+
print('Removing the existing output and creating a new one...')
|
| 246 |
+
shutil.rmtree(output_dir)
|
| 247 |
+
output_dir.mkdir()
|
| 248 |
+
elif not args.continue_:
|
| 249 |
+
backup_output(output_dir)
|
| 250 |
+
print('The output directory already exists. Done!\n')
|
| 251 |
+
sys.exit()
|
| 252 |
+
elif output_dir.joinpath('DONE').exists():
|
| 253 |
+
backup_output(output_dir)
|
| 254 |
+
print('The "DONE" file already exists. Done!')
|
| 255 |
+
sys.exit()
|
| 256 |
+
else:
|
| 257 |
+
print('Continuing with the existing output...')
|
| 258 |
+
else:
|
| 259 |
+
print('Creating the output...')
|
| 260 |
+
output_dir.mkdir()
|
| 261 |
+
|
| 262 |
+
report = {
|
| 263 |
+
'program': str(env.get_relative_path(program)),
|
| 264 |
+
'environment': {},
|
| 265 |
+
'config': full_raw_config,
|
| 266 |
+
}
|
| 267 |
+
if torch.cuda.is_available(): # type: ignore[code]
|
| 268 |
+
report['environment'].update(
|
| 269 |
+
{
|
| 270 |
+
'CUDA_VISIBLE_DEVICES': os.environ.get('CUDA_VISIBLE_DEVICES'),
|
| 271 |
+
'gpus': zero.hardware.get_gpus_info(),
|
| 272 |
+
'torch.version.cuda': torch.version.cuda,
|
| 273 |
+
'torch.backends.cudnn.version()': torch.backends.cudnn.version(), # type: ignore[code]
|
| 274 |
+
'torch.cuda.nccl.version()': torch.cuda.nccl.version(), # type: ignore[code]
|
| 275 |
+
}
|
| 276 |
+
)
|
| 277 |
+
dump_report(report, output_dir)
|
| 278 |
+
dump_json(raw_config, output_dir / 'raw_config.json')
|
| 279 |
+
_print_sep('-')
|
| 280 |
+
pprint(full_raw_config, width=100)
|
| 281 |
+
_print_sep('-')
|
| 282 |
+
return cast(config_cls, config), output_dir, report
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
_LAST_SNAPSHOT_TIME = None
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def backup_output(output_dir: Path) -> None:
|
| 289 |
+
backup_dir = os.environ.get('TMP_OUTPUT_PATH')
|
| 290 |
+
snapshot_dir = os.environ.get('SNAPSHOT_PATH')
|
| 291 |
+
if backup_dir is None:
|
| 292 |
+
assert snapshot_dir is None
|
| 293 |
+
return
|
| 294 |
+
assert snapshot_dir is not None
|
| 295 |
+
|
| 296 |
+
try:
|
| 297 |
+
relative_output_dir = output_dir.relative_to(env.PROJ)
|
| 298 |
+
except ValueError:
|
| 299 |
+
return
|
| 300 |
+
|
| 301 |
+
for dir_ in [backup_dir, snapshot_dir]:
|
| 302 |
+
new_output_dir = dir_ / relative_output_dir
|
| 303 |
+
prev_backup_output_dir = new_output_dir.with_name(new_output_dir.name + '_prev')
|
| 304 |
+
new_output_dir.parent.mkdir(exist_ok=True, parents=True)
|
| 305 |
+
if new_output_dir.exists():
|
| 306 |
+
new_output_dir.rename(prev_backup_output_dir)
|
| 307 |
+
shutil.copytree(output_dir, new_output_dir)
|
| 308 |
+
# the case for evaluate.py which automatically creates configs
|
| 309 |
+
if output_dir.with_suffix('.toml').exists():
|
| 310 |
+
shutil.copyfile(
|
| 311 |
+
output_dir.with_suffix('.toml'), new_output_dir.with_suffix('.toml')
|
| 312 |
+
)
|
| 313 |
+
if prev_backup_output_dir.exists():
|
| 314 |
+
shutil.rmtree(prev_backup_output_dir)
|
| 315 |
+
|
| 316 |
+
global _LAST_SNAPSHOT_TIME
|
| 317 |
+
if _LAST_SNAPSHOT_TIME is None or time.time() - _LAST_SNAPSHOT_TIME > 10 * 60:
|
| 318 |
+
import nirvana_dl.snapshot # type: ignore[code]
|
| 319 |
+
|
| 320 |
+
nirvana_dl.snapshot.dump_snapshot()
|
| 321 |
+
_LAST_SNAPSHOT_TIME = time.time()
|
| 322 |
+
print('The snapshot was saved!')
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _get_scores(metrics: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, float]]:
|
| 326 |
+
return (
|
| 327 |
+
{k: v['score'] for k, v in metrics.items()}
|
| 328 |
+
if 'score' in next(iter(metrics.values()))
|
| 329 |
+
else None
|
| 330 |
+
)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def format_scores(metrics: Dict[str, Dict[str, Any]]) -> str:
|
| 334 |
+
return ' '.join(
|
| 335 |
+
f"[{x}] {metrics[x]['score']:.3f}"
|
| 336 |
+
for x in ['test', 'val', 'train']
|
| 337 |
+
if x in metrics
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def finish(output_dir: Path, report: dict) -> None:
|
| 342 |
+
print()
|
| 343 |
+
_print_sep('=')
|
| 344 |
+
|
| 345 |
+
metrics = report.get('metrics')
|
| 346 |
+
if metrics is not None:
|
| 347 |
+
scores = _get_scores(metrics)
|
| 348 |
+
if scores is not None:
|
| 349 |
+
dump_json(scores, output_dir / 'scores.json')
|
| 350 |
+
print(format_scores(metrics))
|
| 351 |
+
_print_sep('-')
|
| 352 |
+
|
| 353 |
+
dump_report(report, output_dir)
|
| 354 |
+
json_output_path = os.environ.get('JSON_OUTPUT_FILE')
|
| 355 |
+
if json_output_path:
|
| 356 |
+
try:
|
| 357 |
+
key = str(output_dir.relative_to(env.PROJ))
|
| 358 |
+
except ValueError:
|
| 359 |
+
pass
|
| 360 |
+
else:
|
| 361 |
+
json_output_path = Path(json_output_path)
|
| 362 |
+
try:
|
| 363 |
+
json_data = json.loads(json_output_path.read_text())
|
| 364 |
+
except (FileNotFoundError, json.decoder.JSONDecodeError):
|
| 365 |
+
json_data = {}
|
| 366 |
+
json_data[key] = load_json(output_dir / 'report.json')
|
| 367 |
+
json_output_path.write_text(json.dumps(json_data, indent=4))
|
| 368 |
+
shutil.copyfile(
|
| 369 |
+
json_output_path,
|
| 370 |
+
os.path.join(os.environ['SNAPSHOT_PATH'], 'json_output.json'),
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
output_dir.joinpath('DONE').touch()
|
| 374 |
+
backup_output(output_dir)
|
| 375 |
+
print(f'Done! | {report.get("time")} | {output_dir}')
|
| 376 |
+
_print_sep('=')
|
| 377 |
+
print()
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def from_dict(datacls: Type[T], data: dict) -> T:
|
| 381 |
+
assert is_dataclass(datacls)
|
| 382 |
+
data = deepcopy(data)
|
| 383 |
+
for field in fields(datacls):
|
| 384 |
+
if field.name not in data:
|
| 385 |
+
continue
|
| 386 |
+
if is_dataclass(field.type):
|
| 387 |
+
data[field.name] = from_dict(field.type, data[field.name])
|
| 388 |
+
elif (
|
| 389 |
+
get_origin(field.type) is Union
|
| 390 |
+
and len(get_args(field.type)) == 2
|
| 391 |
+
and get_args(field.type)[1] is type(None)
|
| 392 |
+
and is_dataclass(get_args(field.type)[0])
|
| 393 |
+
):
|
| 394 |
+
if data[field.name] is not None:
|
| 395 |
+
data[field.name] = from_dict(get_args(field.type)[0], data[field.name])
|
| 396 |
+
return datacls(**data)
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def replace_factor_with_value(
|
| 400 |
+
config: RawConfig,
|
| 401 |
+
key: str,
|
| 402 |
+
reference_value: int,
|
| 403 |
+
bounds: Tuple[float, float],
|
| 404 |
+
) -> None:
|
| 405 |
+
factor_key = key + '_factor'
|
| 406 |
+
if factor_key not in config:
|
| 407 |
+
assert key in config
|
| 408 |
+
else:
|
| 409 |
+
assert key not in config
|
| 410 |
+
factor = config.pop(factor_key)
|
| 411 |
+
assert bounds[0] <= factor <= bounds[1]
|
| 412 |
+
config[key] = int(factor * reference_value)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def get_temporary_copy(path: Union[str, Path]) -> Path:
|
| 416 |
+
path = env.get_path(path)
|
| 417 |
+
assert not path.is_dir() and not path.is_symlink()
|
| 418 |
+
tmp_path = path.with_name(
|
| 419 |
+
path.stem + '___' + str(uuid.uuid4()).replace('-', '') + path.suffix
|
| 420 |
+
)
|
| 421 |
+
shutil.copyfile(path, tmp_path)
|
| 422 |
+
atexit.register(lambda: tmp_path.unlink())
|
| 423 |
+
return tmp_path
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
def get_python():
|
| 427 |
+
python = Path('python3.9')
|
| 428 |
+
return str(python) if python.exists() else 'python'
|
| 429 |
+
|
| 430 |
+
def get_catboost_config(real_data_path, is_cv=False):
|
| 431 |
+
ds_name = Path(real_data_path).name
|
| 432 |
+
C = load_json(f'tuned_models/catboost/{ds_name}_cv.json')
|
| 433 |
+
return C
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/requirements.txt
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
catboost==1.0.3
|
| 2 |
+
category-encoders==2.3.0
|
| 3 |
+
dython==0.5.1
|
| 4 |
+
icecream==2.1.2
|
| 5 |
+
libzero==0.0.8
|
| 6 |
+
numpy==1.21.4
|
| 7 |
+
optuna==2.10.1
|
| 8 |
+
pandas==1.3.4
|
| 9 |
+
pyarrow==6.0.0
|
| 10 |
+
rtdl==0.0.9
|
| 11 |
+
scikit-learn==1.0.2
|
| 12 |
+
scipy==1.7.2
|
| 13 |
+
skorch==0.11.0
|
| 14 |
+
tomli-w==0.4.0
|
| 15 |
+
tomli==1.2.2
|
| 16 |
+
tqdm==4.62.3
|
| 17 |
+
|
| 18 |
+
# smote
|
| 19 |
+
imbalanced-learn==0.7.0
|
| 20 |
+
|
| 21 |
+
# tvae
|
| 22 |
+
rdt==0.6.4
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -e
|
| 3 |
+
cd /data/jialinzhang/synthetic_benchmark/tabddpm/code
|
| 4 |
+
export PYTHONPATH="$PWD:$PYTHONPATH"
|
| 5 |
+
python -m scripts.pipeline "$@"
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm_docker.sh
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
set -e
|
| 3 |
+
cd /workspace/tabddpm/code
|
| 4 |
+
export PYTHONPATH="$PWD:$PYTHONPATH"
|
| 5 |
+
python -m scripts.pipeline "$@"
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__init__.py
ADDED
|
File without changes
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_catboost.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from catboost import CatBoostClassifier, CatBoostRegressor
|
| 2 |
+
from sklearn.metrics import classification_report, r2_score
|
| 3 |
+
import numpy as np
|
| 4 |
+
import os
|
| 5 |
+
from sklearn.utils import shuffle
|
| 6 |
+
import zero
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import lib
|
| 9 |
+
from pprint import pprint
|
| 10 |
+
from lib import concat_features, read_pure_data, get_catboost_config, read_changed_val
|
| 11 |
+
|
| 12 |
+
def train_catboost(
|
| 13 |
+
parent_dir,
|
| 14 |
+
real_data_path,
|
| 15 |
+
eval_type,
|
| 16 |
+
T_dict,
|
| 17 |
+
seed = 0,
|
| 18 |
+
params = None,
|
| 19 |
+
change_val = True,
|
| 20 |
+
device = None # dummy
|
| 21 |
+
):
|
| 22 |
+
zero.improve_reproducibility(seed)
|
| 23 |
+
if eval_type != "real":
|
| 24 |
+
synthetic_data_path = os.path.join(parent_dir)
|
| 25 |
+
info = lib.load_json(os.path.join(real_data_path, 'info.json'))
|
| 26 |
+
T = lib.Transformations(**T_dict)
|
| 27 |
+
|
| 28 |
+
if change_val:
|
| 29 |
+
X_num_real, X_cat_real, y_real, X_num_val, X_cat_val, y_val = read_changed_val(real_data_path, val_size=0.2)
|
| 30 |
+
|
| 31 |
+
X = None
|
| 32 |
+
print('-'*100)
|
| 33 |
+
if eval_type == 'merged':
|
| 34 |
+
print('loading merged data...')
|
| 35 |
+
if not change_val:
|
| 36 |
+
X_num_real, X_cat_real, y_real = read_pure_data(real_data_path)
|
| 37 |
+
X_num_fake, X_cat_fake, y_fake = read_pure_data(synthetic_data_path)
|
| 38 |
+
|
| 39 |
+
###
|
| 40 |
+
# dists = privacy_metrics(real_data_path, synthetic_data_path)
|
| 41 |
+
# bad_fakes = dists.argsort()[:int(0.25 * len(y_fake))]
|
| 42 |
+
# X_num_fake = np.delete(X_num_fake, bad_fakes, axis=0)
|
| 43 |
+
# X_cat_fake = np.delete(X_cat_fake, bad_fakes, axis=0) if X_cat_fake is not None else None
|
| 44 |
+
# y_fake = np.delete(y_fake, bad_fakes, axis=0)
|
| 45 |
+
###
|
| 46 |
+
|
| 47 |
+
y = np.concatenate([y_real, y_fake], axis=0)
|
| 48 |
+
|
| 49 |
+
X_num = None
|
| 50 |
+
if X_num_real is not None:
|
| 51 |
+
X_num = np.concatenate([X_num_real, X_num_fake], axis=0)
|
| 52 |
+
|
| 53 |
+
X_cat = None
|
| 54 |
+
if X_cat_real is not None:
|
| 55 |
+
X_cat = np.concatenate([X_cat_real, X_cat_fake], axis=0)
|
| 56 |
+
|
| 57 |
+
elif eval_type == 'synthetic':
|
| 58 |
+
print(f'loading synthetic data: {parent_dir}')
|
| 59 |
+
X_num, X_cat, y = read_pure_data(synthetic_data_path)
|
| 60 |
+
|
| 61 |
+
elif eval_type == 'real':
|
| 62 |
+
print('loading real data...')
|
| 63 |
+
if not change_val:
|
| 64 |
+
X_num, X_cat, y = read_pure_data(real_data_path)
|
| 65 |
+
else:
|
| 66 |
+
raise "Choose eval method"
|
| 67 |
+
|
| 68 |
+
if not change_val:
|
| 69 |
+
X_num_val, X_cat_val, y_val = read_pure_data(real_data_path, 'val')
|
| 70 |
+
X_num_test, X_cat_test, y_test = read_pure_data(real_data_path, 'test')
|
| 71 |
+
|
| 72 |
+
D = lib.Dataset(
|
| 73 |
+
{'train': X_num, 'val': X_num_val, 'test': X_num_test} if X_num is not None else None,
|
| 74 |
+
{'train': X_cat, 'val': X_cat_val, 'test': X_cat_test} if X_cat is not None else None,
|
| 75 |
+
{'train': y, 'val': y_val, 'test': y_test},
|
| 76 |
+
{},
|
| 77 |
+
lib.TaskType(info['task_type']),
|
| 78 |
+
info.get('n_classes')
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
D = lib.transform_dataset(D, T, None)
|
| 82 |
+
X = concat_features(D)
|
| 83 |
+
print(f'Train size: {X["train"].shape}, Val size {X["val"].shape}')
|
| 84 |
+
|
| 85 |
+
if params is None:
|
| 86 |
+
catboost_config = get_catboost_config(real_data_path, is_cv=True)
|
| 87 |
+
else:
|
| 88 |
+
catboost_config = params
|
| 89 |
+
|
| 90 |
+
if 'cat_features' not in catboost_config:
|
| 91 |
+
catboost_config['cat_features'] = list(range(D.n_num_features, D.n_features))
|
| 92 |
+
|
| 93 |
+
for col in range(D.n_features):
|
| 94 |
+
for split in X.keys():
|
| 95 |
+
if col in catboost_config['cat_features']:
|
| 96 |
+
X[split][col] = X[split][col].astype(str)
|
| 97 |
+
else:
|
| 98 |
+
X[split][col] = X[split][col].astype(float)
|
| 99 |
+
print(T_dict)
|
| 100 |
+
pprint(catboost_config, width=100)
|
| 101 |
+
print('-'*100)
|
| 102 |
+
|
| 103 |
+
if D.is_regression:
|
| 104 |
+
model = CatBoostRegressor(
|
| 105 |
+
**catboost_config,
|
| 106 |
+
eval_metric='RMSE',
|
| 107 |
+
random_seed=seed
|
| 108 |
+
)
|
| 109 |
+
predict = model.predict
|
| 110 |
+
else:
|
| 111 |
+
model = CatBoostClassifier(
|
| 112 |
+
loss_function="MultiClass" if D.is_multiclass else "Logloss",
|
| 113 |
+
**catboost_config,
|
| 114 |
+
eval_metric='TotalF1',
|
| 115 |
+
random_seed=seed,
|
| 116 |
+
class_names=[str(i) for i in range(D.n_classes)] if D.is_multiclass else ["0", "1"]
|
| 117 |
+
)
|
| 118 |
+
predict = (
|
| 119 |
+
model.predict_proba
|
| 120 |
+
if D.is_multiclass
|
| 121 |
+
else lambda x: model.predict_proba(x)[:, 1]
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
model.fit(
|
| 125 |
+
X['train'], D.y['train'],
|
| 126 |
+
eval_set=(X['val'], D.y['val']),
|
| 127 |
+
verbose=100
|
| 128 |
+
)
|
| 129 |
+
predictions = {k: predict(v) for k, v in X.items()}
|
| 130 |
+
print(predictions['train'].shape)
|
| 131 |
+
|
| 132 |
+
report = {}
|
| 133 |
+
report['eval_type'] = eval_type
|
| 134 |
+
report['dataset'] = real_data_path
|
| 135 |
+
report['metrics'] = D.calculate_metrics(predictions, None if D.is_regression else 'probs')
|
| 136 |
+
|
| 137 |
+
metrics_report = lib.MetricsReport(report['metrics'], D.task_type)
|
| 138 |
+
metrics_report.print_metrics()
|
| 139 |
+
|
| 140 |
+
if parent_dir is not None:
|
| 141 |
+
lib.dump_json(report, os.path.join(parent_dir, "results_catboost.json"))
|
| 142 |
+
|
| 143 |
+
return metrics_report
|
| 144 |
+
|
| 145 |
+
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_mlp.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sklearn.metrics import classification_report, r2_score, f1_score
|
| 2 |
+
import numpy as np
|
| 3 |
+
import os
|
| 4 |
+
from sklearn.utils import shuffle
|
| 5 |
+
import zero
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import lib
|
| 8 |
+
from tab_ddpm.modules import MLP
|
| 9 |
+
from skorch.regressor import NeuralNetRegressor
|
| 10 |
+
from skorch.classifier import NeuralNetClassifier
|
| 11 |
+
from skorch.dataset import Dataset as SkDataset
|
| 12 |
+
from skorch.callbacks import EarlyStopping, EpochScoring
|
| 13 |
+
from skorch.helper import predefined_split
|
| 14 |
+
from torch.optim import AdamW
|
| 15 |
+
from torch.nn import MSELoss, BCEWithLogitsLoss, CrossEntropyLoss
|
| 16 |
+
|
| 17 |
+
def train_mlp(
|
| 18 |
+
parent_dir,
|
| 19 |
+
real_data_path,
|
| 20 |
+
eval_type,
|
| 21 |
+
T_dict,
|
| 22 |
+
params = None,
|
| 23 |
+
change_val = False,
|
| 24 |
+
seed = 0,
|
| 25 |
+
device = "cuda:0"
|
| 26 |
+
):
|
| 27 |
+
zero.improve_reproducibility(seed)
|
| 28 |
+
synthetic_data_path = os.path.join(parent_dir) if parent_dir is not None else None
|
| 29 |
+
info = lib.load_json(os.path.join(real_data_path, 'info.json'))
|
| 30 |
+
T = lib.Transformations(**T_dict)
|
| 31 |
+
|
| 32 |
+
if change_val:
|
| 33 |
+
X_num_real, X_cat_real, y_real, X_num_val, X_cat_val, y_val = lib.read_changed_val(real_data_path, val_size=0.2)
|
| 34 |
+
|
| 35 |
+
X = None
|
| 36 |
+
print('-'*100)
|
| 37 |
+
if eval_type == 'merged':
|
| 38 |
+
print('loading merged data...')
|
| 39 |
+
if not change_val:
|
| 40 |
+
X_num_real, X_cat_real, y_real = lib.read_pure_data(real_data_path)
|
| 41 |
+
X_num_fake, X_cat_fake, y_fake = lib.read_pure_data(synthetic_data_path)
|
| 42 |
+
y = np.concatenate([y_real, y_fake], axis=0)
|
| 43 |
+
|
| 44 |
+
X_num = None
|
| 45 |
+
if X_num_real is not None:
|
| 46 |
+
X_num = np.concatenate([X_num_real, X_num_fake], axis=0)
|
| 47 |
+
|
| 48 |
+
X_cat = None
|
| 49 |
+
if X_cat_real is not None:
|
| 50 |
+
X_cat = np.concatenate([X_cat_real, X_cat_fake], axis=0)
|
| 51 |
+
|
| 52 |
+
elif eval_type == 'synthetic':
|
| 53 |
+
print('loading synthetic data...')
|
| 54 |
+
X_num, X_cat, y = lib.read_pure_data(synthetic_data_path)
|
| 55 |
+
|
| 56 |
+
elif eval_type == 'real':
|
| 57 |
+
print('loading real data...')
|
| 58 |
+
if not change_val:
|
| 59 |
+
X_num, X_cat, y = lib.read_pure_data(real_data_path)
|
| 60 |
+
else:
|
| 61 |
+
raise "Choose eval method"
|
| 62 |
+
|
| 63 |
+
if not change_val:
|
| 64 |
+
X_num_val, X_cat_val, y_val = lib.read_pure_data(real_data_path, 'val')
|
| 65 |
+
X_num_test, X_cat_test, y_test = lib.read_pure_data(real_data_path, 'test')
|
| 66 |
+
|
| 67 |
+
D = lib.Dataset(
|
| 68 |
+
{'train': X_num, 'val': X_num_val, 'test': X_num_test} if X_num is not None else None,
|
| 69 |
+
{'train': X_cat, 'val': X_cat_val, 'test': X_cat_test} if X_cat is not None else None,
|
| 70 |
+
{'train': y, 'val': y_val, 'test': y_test},
|
| 71 |
+
{},
|
| 72 |
+
lib.TaskType(info['task_type']),
|
| 73 |
+
info.get('n_classes')
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
D = lib.transform_dataset(D, T, None)
|
| 77 |
+
X = lib.concat_features(D)
|
| 78 |
+
|
| 79 |
+
X["train"], D.y["train"] = shuffle(X["train"], D.y["train"], random_state=seed)
|
| 80 |
+
print(f'Train size: {X["train"].shape}, Val size {X["val"].shape}')
|
| 81 |
+
|
| 82 |
+
if params is None:
|
| 83 |
+
params = lib.load_json(f"tuned_models/mlp/{Path(real_data_path).name}_cv.json")
|
| 84 |
+
|
| 85 |
+
mlp_params = {}
|
| 86 |
+
if params is not None:
|
| 87 |
+
mlp_params["d_layers"] = params["d_layers"]
|
| 88 |
+
mlp_params["dropout"] = params["dropout"]
|
| 89 |
+
# mlp_params["n_blocks"] = params["n_blocks"]
|
| 90 |
+
# mlp_params["d_main"] = params["d_main"]
|
| 91 |
+
# mlp_params["d_hidden"] = params["d_hidden"]
|
| 92 |
+
# mlp_params["dropout_first"] = params["dropout_first"]
|
| 93 |
+
# mlp_params["dropout_second"] = params["dropout_second"]
|
| 94 |
+
mlp_params["d_in"] = X["train"].shape[1]
|
| 95 |
+
mlp_params["d_out"] = D.nn_output_dim
|
| 96 |
+
|
| 97 |
+
model = MLP.make_baseline(**mlp_params)
|
| 98 |
+
|
| 99 |
+
if D.is_regression:
|
| 100 |
+
y = {k: D.y[k].reshape(-1, 1).astype(np.float32) for k in D.y}
|
| 101 |
+
elif D.is_binclass:
|
| 102 |
+
y = {k: D.y[k].reshape(-1, 1).astype(np.float32) for k in D.y}
|
| 103 |
+
else:
|
| 104 |
+
y = {k: D.y[k].astype(np.int64) for k in D.y}
|
| 105 |
+
|
| 106 |
+
train_ds = SkDataset(X = X["train"].to_numpy(), y = y["train"])
|
| 107 |
+
val_ds = SkDataset(X = X["val"].to_numpy(), y = y["val"])
|
| 108 |
+
es = EarlyStopping(monitor="valid_loss", patience=16)
|
| 109 |
+
|
| 110 |
+
print('-'*100)
|
| 111 |
+
|
| 112 |
+
def f1(net, X, y):
|
| 113 |
+
y_pred = net.predict(X)
|
| 114 |
+
return f1_score(y, y_pred, average="macro")
|
| 115 |
+
|
| 116 |
+
def r2(net, X, y):
|
| 117 |
+
y_pred = net.predict(X)
|
| 118 |
+
return r2_score(y, y_pred)
|
| 119 |
+
|
| 120 |
+
if D.is_regression:
|
| 121 |
+
net = NeuralNetRegressor(
|
| 122 |
+
model,
|
| 123 |
+
criterion=MSELoss,
|
| 124 |
+
optimizer=AdamW,
|
| 125 |
+
lr=params["lr"],
|
| 126 |
+
optimizer__weight_decay=params["weight_decay"],
|
| 127 |
+
batch_size=128 if len(D.y["train"]) < 10_000 else 256,
|
| 128 |
+
max_epochs=1000,
|
| 129 |
+
train_split=predefined_split(val_ds),
|
| 130 |
+
iterator_train__shuffle=True,
|
| 131 |
+
device=device,
|
| 132 |
+
callbacks=[es, EpochScoring(r2, lower_is_better=False)],
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
else:
|
| 136 |
+
net = NeuralNetClassifier(
|
| 137 |
+
model,
|
| 138 |
+
criterion=BCEWithLogitsLoss if D.is_binclass else CrossEntropyLoss,
|
| 139 |
+
optimizer=AdamW,
|
| 140 |
+
lr=params["lr"],
|
| 141 |
+
optimizer__weight_decay=params["weight_decay"],
|
| 142 |
+
batch_size=128 if len(D.y["train"]) < 10_000 else 256,
|
| 143 |
+
max_epochs=1000,
|
| 144 |
+
train_split=predefined_split(val_ds),
|
| 145 |
+
iterator_train__shuffle=True,
|
| 146 |
+
device=device,
|
| 147 |
+
callbacks=[es, EpochScoring(f1, lower_is_better=False)],
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
net.fit(
|
| 151 |
+
X=train_ds.X,
|
| 152 |
+
y=train_ds.y
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
print("LAST:", len(net.history))
|
| 156 |
+
|
| 157 |
+
predictions = {k: net.predict_proba(v.to_numpy())[:, 1] if D.is_binclass else
|
| 158 |
+
net.predict_proba(v.to_numpy()) if D.is_multiclass else
|
| 159 |
+
net.predict(v.to_numpy())
|
| 160 |
+
for k, v in X.items()
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
report = {}
|
| 164 |
+
report['eval_type'] = eval_type
|
| 165 |
+
report['dataset'] = real_data_path
|
| 166 |
+
report['metrics'] = D.calculate_metrics(predictions, None if D.is_regression else 'probs')
|
| 167 |
+
|
| 168 |
+
metrics_report = lib.MetricsReport(report['metrics'], D.task_type)
|
| 169 |
+
metrics_report.print_metrics()
|
| 170 |
+
|
| 171 |
+
if parent_dir is not None:
|
| 172 |
+
lib.dump_json(report, os.path.join(parent_dir, "results_mlp.json"))
|
| 173 |
+
|
| 174 |
+
return metrics_report
|
| 175 |
+
|
| 176 |
+
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import subprocess
|
| 3 |
+
import tempfile
|
| 4 |
+
import lib
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from copy import deepcopy
|
| 9 |
+
from scripts.eval_catboost import train_catboost
|
| 10 |
+
from scripts.eval_mlp import train_mlp
|
| 11 |
+
from scripts.eval_simple import train_simple
|
| 12 |
+
|
| 13 |
+
pipeline = {
|
| 14 |
+
'ddpm': 'scripts/pipeline.py',
|
| 15 |
+
'smote': 'smote/pipeline_smote.py',
|
| 16 |
+
'ctabgan': 'CTAB-GAN/pipeline_ctabgan.py',
|
| 17 |
+
'ctabgan-plus': 'CTAB-GAN-Plus/pipeline_ctabgan.py',
|
| 18 |
+
'tvae': 'CTGAN/pipeline_tvae.py'
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
def eval_seeds(
|
| 22 |
+
raw_config,
|
| 23 |
+
n_seeds,
|
| 24 |
+
eval_type,
|
| 25 |
+
sampling_method="ddpm",
|
| 26 |
+
model_type="catboost",
|
| 27 |
+
n_datasets=1,
|
| 28 |
+
dump=True,
|
| 29 |
+
change_val=False
|
| 30 |
+
):
|
| 31 |
+
|
| 32 |
+
metrics_seeds_report = lib.SeedsMetricsReport()
|
| 33 |
+
parent_dir = Path(raw_config["parent_dir"])
|
| 34 |
+
|
| 35 |
+
if eval_type == 'real':
|
| 36 |
+
n_datasets = 1
|
| 37 |
+
|
| 38 |
+
temp_config = deepcopy(raw_config)
|
| 39 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 40 |
+
dir_ = Path(dir_)
|
| 41 |
+
temp_config["parent_dir"] = str(dir_)
|
| 42 |
+
if sampling_method == "ddpm":
|
| 43 |
+
shutil.copy2(parent_dir / "model.pt", temp_config["parent_dir"])
|
| 44 |
+
elif sampling_method in ["ctabgan", "ctabgan-plus"]:
|
| 45 |
+
shutil.copy2(parent_dir / "ctabgan.obj", temp_config["parent_dir"])
|
| 46 |
+
elif sampling_method == "tvae":
|
| 47 |
+
shutil.copy2(parent_dir / "tvae.obj", temp_config["parent_dir"])
|
| 48 |
+
|
| 49 |
+
for sample_seed in range(n_datasets):
|
| 50 |
+
temp_config['sample']['seed'] = sample_seed
|
| 51 |
+
lib.dump_config(temp_config, dir_ / "config.toml")
|
| 52 |
+
if eval_type != 'real' and n_datasets > 1:
|
| 53 |
+
subprocess.run(['python3.9', f'{pipeline[sampling_method]}', '--config', f'{str(dir_ / "config.toml")}', '--sample'], check=True)
|
| 54 |
+
|
| 55 |
+
T_dict = deepcopy(raw_config['eval']['T'])
|
| 56 |
+
for seed in range(n_seeds):
|
| 57 |
+
print(f'**Eval Iter: {sample_seed*n_seeds + (seed + 1)}/{n_seeds * n_datasets}**')
|
| 58 |
+
if model_type == "catboost":
|
| 59 |
+
T_dict["normalization"] = None
|
| 60 |
+
T_dict["cat_encoding"] = None
|
| 61 |
+
metric_report = train_catboost(
|
| 62 |
+
parent_dir=temp_config['parent_dir'],
|
| 63 |
+
real_data_path=temp_config['real_data_path'],
|
| 64 |
+
eval_type=eval_type,
|
| 65 |
+
T_dict=T_dict,
|
| 66 |
+
seed=seed,
|
| 67 |
+
change_val=change_val
|
| 68 |
+
)
|
| 69 |
+
elif model_type == "mlp":
|
| 70 |
+
T_dict["normalization"] = "quantile"
|
| 71 |
+
T_dict["cat_encoding"] = "one-hot"
|
| 72 |
+
metric_report = train_mlp(
|
| 73 |
+
parent_dir=temp_config['parent_dir'],
|
| 74 |
+
real_data_path=temp_config['real_data_path'],
|
| 75 |
+
eval_type=eval_type,
|
| 76 |
+
T_dict=T_dict,
|
| 77 |
+
seed=seed,
|
| 78 |
+
change_val=change_val
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
metrics_seeds_report.add_report(metric_report)
|
| 82 |
+
|
| 83 |
+
metrics_seeds_report.get_mean_std()
|
| 84 |
+
res = metrics_seeds_report.print_result()
|
| 85 |
+
if os.path.exists(parent_dir/ f"eval_{model_type}.json"):
|
| 86 |
+
eval_dict = lib.load_json(parent_dir / f"eval_{model_type}.json")
|
| 87 |
+
eval_dict = eval_dict | {eval_type: res}
|
| 88 |
+
else:
|
| 89 |
+
eval_dict = {eval_type: res}
|
| 90 |
+
|
| 91 |
+
if dump:
|
| 92 |
+
lib.dump_json(eval_dict, parent_dir / f"eval_{model_type}.json")
|
| 93 |
+
|
| 94 |
+
raw_config['sample']['seed'] = 0
|
| 95 |
+
lib.dump_config(raw_config, parent_dir / 'config.toml')
|
| 96 |
+
return res
|
| 97 |
+
|
| 98 |
+
def main():
|
| 99 |
+
parser = argparse.ArgumentParser()
|
| 100 |
+
parser.add_argument('--config', metavar='FILE')
|
| 101 |
+
parser.add_argument('n_seeds', type=int, default=10)
|
| 102 |
+
parser.add_argument('sampling_method', type=str, default="ddpm")
|
| 103 |
+
parser.add_argument('eval_type', type=str, default='synthetic')
|
| 104 |
+
parser.add_argument('model_type', type=str, default='catboost')
|
| 105 |
+
parser.add_argument('n_datasets', type=int, default=1)
|
| 106 |
+
parser.add_argument('--no_dump', action='store_false', default=True)
|
| 107 |
+
|
| 108 |
+
args = parser.parse_args()
|
| 109 |
+
raw_config = lib.load_config(args.config)
|
| 110 |
+
eval_seeds(
|
| 111 |
+
raw_config,
|
| 112 |
+
n_seeds=args.n_seeds,
|
| 113 |
+
sampling_method=args.sampling_method,
|
| 114 |
+
eval_type=args.eval_type,
|
| 115 |
+
model_type=args.model_type,
|
| 116 |
+
n_datasets=args.n_datasets,
|
| 117 |
+
dump=args.no_dump
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
if __name__ == '__main__':
|
| 121 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds_simple.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import subprocess
|
| 3 |
+
import tempfile
|
| 4 |
+
import lib
|
| 5 |
+
import os
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import numpy as np
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from eval_simple import train_simple
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
import shutil
|
| 12 |
+
|
| 13 |
+
pipeline = {
|
| 14 |
+
'ddpm': 'scripts/pipeline.py',
|
| 15 |
+
'smote': 'smote/pipeline_smote.py',
|
| 16 |
+
'ctabgan': 'CTAB-GAN/pipeline_ctabgan.py',
|
| 17 |
+
'ctabgan-plus': 'CTAB-GAN-Plus/pipeline_ctabganp.py',
|
| 18 |
+
'tvae': 'CTGAN/pipeline_tvae.py'
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def eval_seeds(
|
| 23 |
+
raw_config,
|
| 24 |
+
n_seeds,
|
| 25 |
+
eval_type,
|
| 26 |
+
sampling_method="ddpm",
|
| 27 |
+
model_type="simple",
|
| 28 |
+
n_datasets=1,
|
| 29 |
+
dump=True,
|
| 30 |
+
change_val=False
|
| 31 |
+
):
|
| 32 |
+
parent_dir = Path(raw_config["parent_dir"])
|
| 33 |
+
models = ["tree", "lr", "rf", "mlp"]
|
| 34 |
+
metrics_seeds_report = {
|
| 35 |
+
k: lib.SeedsMetricsReport() for k in models
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
if eval_type == 'real':
|
| 39 |
+
n_datasets = 1
|
| 40 |
+
|
| 41 |
+
T_dict = deepcopy(raw_config['eval']['T'])
|
| 42 |
+
T_dict["normalization"] = "minmax"
|
| 43 |
+
T_dict["cat_encoding"] = None
|
| 44 |
+
|
| 45 |
+
temp_config = deepcopy(raw_config)
|
| 46 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 47 |
+
dir_ = Path(dir_)
|
| 48 |
+
temp_config["parent_dir"] = str(dir_)
|
| 49 |
+
if sampling_method == "ddpm":
|
| 50 |
+
shutil.copy2(parent_dir / "model.pt", temp_config["parent_dir"])
|
| 51 |
+
elif sampling_method in ["ctabgan", "ctabgan-plus"]:
|
| 52 |
+
shutil.copy2(parent_dir / "ctabgan.obj", temp_config["parent_dir"])
|
| 53 |
+
elif sampling_method == "tvae":
|
| 54 |
+
shutil.copy2(parent_dir / "tvae.obj", temp_config["parent_dir"])
|
| 55 |
+
|
| 56 |
+
for sample_seed in range(n_datasets):
|
| 57 |
+
temp_config['sample']['seed'] = sample_seed
|
| 58 |
+
lib.dump_config(temp_config, dir_ / "config.toml")
|
| 59 |
+
if eval_type != 'real':
|
| 60 |
+
subprocess.run(['python3.9', f'{pipeline[sampling_method]}', '--config', f'{str(dir_ / "config.toml")}', '--sample'], check=True)
|
| 61 |
+
|
| 62 |
+
for seed in range(n_seeds):
|
| 63 |
+
print(f'**Eval Iter: {sample_seed*n_seeds + (seed + 1)}/{n_seeds * n_datasets}**')
|
| 64 |
+
for model in models:
|
| 65 |
+
metric_report = train_simple(
|
| 66 |
+
parent_dir=temp_config['parent_dir'],
|
| 67 |
+
real_data_path=temp_config['real_data_path'],
|
| 68 |
+
model_name=model,
|
| 69 |
+
eval_type=eval_type,
|
| 70 |
+
T_dict=T_dict,
|
| 71 |
+
seed=seed,
|
| 72 |
+
change_val=change_val
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
metrics_seeds_report[model].add_report(metric_report)
|
| 76 |
+
for k in models:
|
| 77 |
+
metrics_seeds_report[k].get_mean_std()
|
| 78 |
+
res = {
|
| 79 |
+
k: metrics_seeds_report[k].print_result() for k in models
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
m1, m2 = ("r2-mean", "rmse-mean") if "r2-mean" in res["tree"]["val"] else ("f1-mean", "acc-mean")
|
| 83 |
+
res["avg"] = {
|
| 84 |
+
"val": {
|
| 85 |
+
m1: np.around(np.mean([res[k]["val"][m1] for k in models]), 4),
|
| 86 |
+
m2: np.around(np.mean([res[k]["val"][m2] for k in models]), 4)
|
| 87 |
+
},
|
| 88 |
+
"test": {
|
| 89 |
+
m1: np.around(np.mean([res[k]["test"][m1] for k in models]), 4),
|
| 90 |
+
m2: np.around(np.mean([res[k]["test"][m2] for k in models]), 4)
|
| 91 |
+
},
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
if os.path.exists(parent_dir / f"eval_{model_type}.json"):
|
| 95 |
+
eval_dict = lib.load_json(parent_dir / f"eval_{model_type}.json")
|
| 96 |
+
eval_dict = eval_dict | {eval_type: res}
|
| 97 |
+
else:
|
| 98 |
+
eval_dict = {eval_type: res}
|
| 99 |
+
|
| 100 |
+
if dump:
|
| 101 |
+
lib.dump_json(eval_dict, parent_dir / f"eval_{model_type}.json")
|
| 102 |
+
|
| 103 |
+
raw_config['sample']['seed'] = 0
|
| 104 |
+
lib.dump_config(raw_config, parent_dir / 'config.toml')
|
| 105 |
+
return res
|
| 106 |
+
|
| 107 |
+
def main():
|
| 108 |
+
parser = argparse.ArgumentParser()
|
| 109 |
+
parser.add_argument('--config', metavar='FILE')
|
| 110 |
+
parser.add_argument('n_seeds', type=int, default=10)
|
| 111 |
+
parser.add_argument('sampling_method', type=str, default="ddpm")
|
| 112 |
+
parser.add_argument('eval_type', type=str, default='synthetic')
|
| 113 |
+
parser.add_argument('model_type', type=str, default='catboost')
|
| 114 |
+
parser.add_argument('n_datasets', type=int, default=1)
|
| 115 |
+
parser.add_argument('--no_dump', action='store_false', default=True)
|
| 116 |
+
|
| 117 |
+
args = parser.parse_args()
|
| 118 |
+
raw_config = lib.load_config(args.config)
|
| 119 |
+
eval_seeds(
|
| 120 |
+
raw_config,
|
| 121 |
+
n_seeds=args.n_seeds,
|
| 122 |
+
sampling_method=args.sampling_method,
|
| 123 |
+
eval_type=args.eval_type,
|
| 124 |
+
model_type=args.model_type,
|
| 125 |
+
n_datasets=args.n_datasets,
|
| 126 |
+
dump=args.no_dump
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
if __name__ == '__main__':
|
| 130 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_simple.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import os
|
| 3 |
+
from sklearn.utils import shuffle
|
| 4 |
+
import zero
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import lib
|
| 7 |
+
from lib import concat_features, read_pure_data, read_changed_val
|
| 8 |
+
from sklearn.utils import shuffle
|
| 9 |
+
import lib
|
| 10 |
+
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
|
| 11 |
+
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
|
| 12 |
+
from sklearn.linear_model import LogisticRegression, Ridge
|
| 13 |
+
from sklearn.neural_network import MLPClassifier, MLPRegressor
|
| 14 |
+
|
| 15 |
+
def train_simple(
|
| 16 |
+
parent_dir,
|
| 17 |
+
real_data_path,
|
| 18 |
+
eval_type,
|
| 19 |
+
T_dict,
|
| 20 |
+
model_name = "tree",
|
| 21 |
+
seed = 0,
|
| 22 |
+
change_val = True,
|
| 23 |
+
params = None, # dummy
|
| 24 |
+
device = None # dummy
|
| 25 |
+
):
|
| 26 |
+
zero.improve_reproducibility(seed)
|
| 27 |
+
if eval_type != "real":
|
| 28 |
+
synthetic_data_path = os.path.join(parent_dir)
|
| 29 |
+
|
| 30 |
+
T_dict["normalization"] = "minmax"
|
| 31 |
+
T_dict["cat_encoding"] = None
|
| 32 |
+
T = lib.Transformations(**T_dict)
|
| 33 |
+
info = lib.load_json(os.path.join(real_data_path, 'info.json'))
|
| 34 |
+
|
| 35 |
+
if change_val:
|
| 36 |
+
X_num_real, X_cat_real, y_real, X_num_val, X_cat_val, y_val = read_changed_val(real_data_path, val_size=0.2)
|
| 37 |
+
|
| 38 |
+
X = None
|
| 39 |
+
print('-'*100)
|
| 40 |
+
if eval_type == 'merged':
|
| 41 |
+
print('loading merged data...')
|
| 42 |
+
if not change_val:
|
| 43 |
+
X_num_real, X_cat_real, y_real = read_pure_data(real_data_path)
|
| 44 |
+
X_num_fake, X_cat_fake, y_fake = read_pure_data(synthetic_data_path)
|
| 45 |
+
|
| 46 |
+
###
|
| 47 |
+
# dists = privacy_metrics(real_data_path, synthetic_data_path)
|
| 48 |
+
# bad_fakes = dists.argsort()[:int(0.25 * len(y_fake))]
|
| 49 |
+
# X_num_fake = np.delete(X_num_fake, bad_fakes, axis=0)
|
| 50 |
+
# X_cat_fake = np.delete(X_cat_fake, bad_fakes, axis=0) if X_cat_fake is not None else None
|
| 51 |
+
# y_fake = np.delete(y_fake, bad_fakes, axis=0)
|
| 52 |
+
###
|
| 53 |
+
|
| 54 |
+
y = np.concatenate([y_real, y_fake], axis=0)
|
| 55 |
+
|
| 56 |
+
X_num = None
|
| 57 |
+
if X_num_real is not None:
|
| 58 |
+
X_num = np.concatenate([X_num_real, X_num_fake], axis=0)
|
| 59 |
+
|
| 60 |
+
X_cat = None
|
| 61 |
+
if X_cat_real is not None:
|
| 62 |
+
X_cat = np.concatenate([X_cat_real, X_cat_fake], axis=0)
|
| 63 |
+
|
| 64 |
+
elif eval_type == 'synthetic':
|
| 65 |
+
print(f'loading synthetic data: {parent_dir}')
|
| 66 |
+
X_num, X_cat, y = read_pure_data(synthetic_data_path)
|
| 67 |
+
|
| 68 |
+
elif eval_type == 'real':
|
| 69 |
+
print('loading real data...')
|
| 70 |
+
if not change_val:
|
| 71 |
+
X_num, X_cat, y = read_pure_data(real_data_path)
|
| 72 |
+
else:
|
| 73 |
+
raise "Choose eval method"
|
| 74 |
+
|
| 75 |
+
if not change_val:
|
| 76 |
+
X_num_val, X_cat_val, y_val = read_pure_data(real_data_path, 'val')
|
| 77 |
+
X_num_test, X_cat_test, y_test = read_pure_data(real_data_path, 'test')
|
| 78 |
+
|
| 79 |
+
D = lib.Dataset(
|
| 80 |
+
{'train': X_num, 'val': X_num_val, 'test': X_num_test} if X_num is not None else None,
|
| 81 |
+
{'train': X_cat, 'val': X_cat_val, 'test': X_cat_test} if X_cat is not None else None,
|
| 82 |
+
{'train': y, 'val': y_val, 'test': y_test},
|
| 83 |
+
{},
|
| 84 |
+
lib.TaskType(info['task_type']),
|
| 85 |
+
info.get('n_classes')
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
D = lib.transform_dataset(D, T, None)
|
| 89 |
+
X = concat_features(D)
|
| 90 |
+
# ixs = np.random.choice(len(D.y["train"]), min(info["train_size"], len(D.y["train"])), replace=False)
|
| 91 |
+
# X["train"] = X["train"].iloc[ixs]
|
| 92 |
+
# D.y["train"] = D.y["train"][ixs]
|
| 93 |
+
|
| 94 |
+
print(f'Train size: {X["train"].shape}, Val size {X["val"].shape}')
|
| 95 |
+
print(T_dict)
|
| 96 |
+
print('-'*100)
|
| 97 |
+
|
| 98 |
+
if D.is_regression:
|
| 99 |
+
models = {
|
| 100 |
+
"tree": DecisionTreeRegressor(max_depth=28, random_state=seed),
|
| 101 |
+
"rf": RandomForestRegressor(max_depth=28, random_state=seed),
|
| 102 |
+
"lr": Ridge(max_iter=500, random_state=seed),
|
| 103 |
+
"mlp": MLPRegressor(max_iter=100, random_state=seed)
|
| 104 |
+
}
|
| 105 |
+
else:
|
| 106 |
+
models = {
|
| 107 |
+
"tree": DecisionTreeClassifier(max_depth=28, random_state=seed),
|
| 108 |
+
"rf": RandomForestClassifier(max_depth=28, random_state=seed),
|
| 109 |
+
"lr": LogisticRegression(max_iter=500, n_jobs=2, random_state=seed),
|
| 110 |
+
"mlp": MLPClassifier(max_iter=100, random_state=seed)
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
model = models[model_name]
|
| 114 |
+
|
| 115 |
+
predict = (
|
| 116 |
+
model.predict
|
| 117 |
+
if D.is_regression
|
| 118 |
+
else model.predict_proba
|
| 119 |
+
if D.is_multiclass
|
| 120 |
+
else lambda x: model.predict_proba(x)[:, 1]
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
model.fit(X['train'], D.y['train'])
|
| 124 |
+
|
| 125 |
+
predictions = {k: predict(v) for k, v in X.items()}
|
| 126 |
+
|
| 127 |
+
report = {}
|
| 128 |
+
report['eval_type'] = eval_type
|
| 129 |
+
report['dataset'] = real_data_path
|
| 130 |
+
report['metrics'] = D.calculate_metrics(predictions, None if D.is_regression else 'probs')
|
| 131 |
+
|
| 132 |
+
metrics_report = lib.MetricsReport(report['metrics'], D.task_type)
|
| 133 |
+
print(model.__class__.__name__)
|
| 134 |
+
metrics_report.print_metrics()
|
| 135 |
+
|
| 136 |
+
# if parent_dir is not None:
|
| 137 |
+
# lib.dump_json(report, os.path.join(parent_dir, "results_catboost.json"))
|
| 138 |
+
|
| 139 |
+
return metrics_report
|
| 140 |
+
|
| 141 |
+
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/pipeline.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tomli
|
| 2 |
+
import shutil
|
| 3 |
+
import os
|
| 4 |
+
import argparse
|
| 5 |
+
from scripts.train import train
|
| 6 |
+
from scripts.sample import sample
|
| 7 |
+
from scripts.eval_catboost import train_catboost
|
| 8 |
+
from scripts.eval_mlp import train_mlp
|
| 9 |
+
from scripts.eval_simple import train_simple
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import zero
|
| 13 |
+
import lib
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
def load_config(path) :
|
| 17 |
+
with open(path, 'rb') as f:
|
| 18 |
+
return tomli.load(f)
|
| 19 |
+
|
| 20 |
+
def save_file(parent_dir, config_path):
|
| 21 |
+
try:
|
| 22 |
+
dst = os.path.join(parent_dir)
|
| 23 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 24 |
+
shutil.copyfile(os.path.abspath(config_path), dst)
|
| 25 |
+
except shutil.SameFileError:
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
parser = argparse.ArgumentParser()
|
| 30 |
+
parser.add_argument('--config', metavar='FILE')
|
| 31 |
+
parser.add_argument('--train', action='store_true', default=False)
|
| 32 |
+
parser.add_argument('--sample', action='store_true', default=False)
|
| 33 |
+
parser.add_argument('--eval', action='store_true', default=False)
|
| 34 |
+
parser.add_argument('--change_val', action='store_true', default=False)
|
| 35 |
+
|
| 36 |
+
args = parser.parse_args()
|
| 37 |
+
raw_config = lib.load_config(args.config)
|
| 38 |
+
if 'device' in raw_config:
|
| 39 |
+
device = torch.device(raw_config['device'])
|
| 40 |
+
else:
|
| 41 |
+
device = torch.device('cuda:1')
|
| 42 |
+
|
| 43 |
+
timer = zero.Timer()
|
| 44 |
+
timer.run()
|
| 45 |
+
save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
|
| 46 |
+
|
| 47 |
+
if args.train:
|
| 48 |
+
train(
|
| 49 |
+
**raw_config['train']['main'],
|
| 50 |
+
**raw_config['diffusion_params'],
|
| 51 |
+
parent_dir=raw_config['parent_dir'],
|
| 52 |
+
real_data_path=raw_config['real_data_path'],
|
| 53 |
+
model_type=raw_config['model_type'],
|
| 54 |
+
model_params=raw_config['model_params'],
|
| 55 |
+
T_dict=raw_config['train']['T'],
|
| 56 |
+
num_numerical_features=raw_config['num_numerical_features'],
|
| 57 |
+
device=device,
|
| 58 |
+
change_val=args.change_val
|
| 59 |
+
)
|
| 60 |
+
if args.sample:
|
| 61 |
+
sample(
|
| 62 |
+
num_samples=raw_config['sample']['num_samples'],
|
| 63 |
+
batch_size=raw_config['sample']['batch_size'],
|
| 64 |
+
disbalance=raw_config['sample'].get('disbalance', None),
|
| 65 |
+
**raw_config['diffusion_params'],
|
| 66 |
+
parent_dir=raw_config['parent_dir'],
|
| 67 |
+
real_data_path=raw_config['real_data_path'],
|
| 68 |
+
model_path=os.path.join(raw_config['parent_dir'], 'model.pt'),
|
| 69 |
+
model_type=raw_config['model_type'],
|
| 70 |
+
model_params=raw_config['model_params'],
|
| 71 |
+
T_dict=raw_config['train']['T'],
|
| 72 |
+
num_numerical_features=raw_config['num_numerical_features'],
|
| 73 |
+
device=device,
|
| 74 |
+
seed=raw_config['sample'].get('seed', 0),
|
| 75 |
+
change_val=args.change_val
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
|
| 79 |
+
if args.eval:
|
| 80 |
+
if raw_config['eval']['type']['eval_model'] == 'catboost':
|
| 81 |
+
train_catboost(
|
| 82 |
+
parent_dir=raw_config['parent_dir'],
|
| 83 |
+
real_data_path=raw_config['real_data_path'],
|
| 84 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 85 |
+
T_dict=raw_config['eval']['T'],
|
| 86 |
+
seed=raw_config['seed'],
|
| 87 |
+
change_val=args.change_val
|
| 88 |
+
)
|
| 89 |
+
elif raw_config['eval']['type']['eval_model'] == 'mlp':
|
| 90 |
+
train_mlp(
|
| 91 |
+
parent_dir=raw_config['parent_dir'],
|
| 92 |
+
real_data_path=raw_config['real_data_path'],
|
| 93 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 94 |
+
T_dict=raw_config['eval']['T'],
|
| 95 |
+
seed=raw_config['seed'],
|
| 96 |
+
change_val=args.change_val,
|
| 97 |
+
device=device
|
| 98 |
+
)
|
| 99 |
+
elif raw_config['eval']['type']['eval_model'] == 'simple':
|
| 100 |
+
train_simple(
|
| 101 |
+
parent_dir=raw_config['parent_dir'],
|
| 102 |
+
real_data_path=raw_config['real_data_path'],
|
| 103 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 104 |
+
T_dict=raw_config['eval']['T'],
|
| 105 |
+
seed=raw_config['seed'],
|
| 106 |
+
change_val=args.change_val
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
print(f'Elapsed time: {str(timer)}')
|
| 110 |
+
|
| 111 |
+
if __name__ == '__main__':
|
| 112 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/resample_privacy.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Adapted from https://github.com/Team-TUD/CTAB-GAN/tree/main/model/eval
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import lib
|
| 7 |
+
import os
|
| 8 |
+
import shutil
|
| 9 |
+
import zero
|
| 10 |
+
from sample import sample
|
| 11 |
+
from smote.sample_smote import sample_smote
|
| 12 |
+
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder
|
| 13 |
+
from sklearn.metrics import pairwise_distances
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import tempfile
|
| 16 |
+
from eval_seeds import eval_seeds
|
| 17 |
+
import numpy as np
|
| 18 |
+
import subprocess
|
| 19 |
+
import warnings
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
zero.improve_reproducibility(0)
|
| 23 |
+
|
| 24 |
+
warnings.filterwarnings("ignore", category=FutureWarning)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def privacy_metrics(real_path,fake_path, data_percent=15):
|
| 28 |
+
|
| 29 |
+
"""
|
| 30 |
+
Returns privacy metrics
|
| 31 |
+
|
| 32 |
+
Inputs:
|
| 33 |
+
1) real_path -> path to real data
|
| 34 |
+
2) fake_path -> path to corresponding synthetic data
|
| 35 |
+
3) data_percent -> percentage of data to be sampled from real and synthetic datasets for computing privacy metrics
|
| 36 |
+
Outputs:
|
| 37 |
+
1) List containing the 5th percentile distance to closest record (DCR) between real and synthetic as well as within real and synthetic datasets
|
| 38 |
+
along with 5th percentile of nearest neighbour distance ratio (NNDR) between real and synthetic as well as within real and synthetic datasets
|
| 39 |
+
|
| 40 |
+
"""
|
| 41 |
+
task_type = lib.load_json(real_path + "/info.json")["task_type"]
|
| 42 |
+
X_num_real, X_cat_real, y_real = lib.read_pure_data(real_path, 'train')
|
| 43 |
+
X_num_fake, X_cat_fake, y_fake = lib.read_pure_data(fake_path, 'train')
|
| 44 |
+
|
| 45 |
+
if task_type == 'regression':
|
| 46 |
+
X_num_real = np.concatenate([X_num_real, y_real[:, np.newaxis]], axis=1)
|
| 47 |
+
X_num_fake = np.concatenate([X_num_fake, y_fake[:, np.newaxis]], axis=1)
|
| 48 |
+
else:
|
| 49 |
+
if X_cat_fake is None:
|
| 50 |
+
X_cat_real = y_real[:, np.newaxis].astype(int).astype(str)
|
| 51 |
+
X_cat_fake = y_fake[:, np.newaxis].astype(int).astype(str)
|
| 52 |
+
else:
|
| 53 |
+
X_cat_real = np.concatenate([X_cat_real, y_real[:, np.newaxis].astype(int).astype(str)], axis=1)
|
| 54 |
+
X_cat_fake = np.concatenate([X_cat_fake, y_fake[:, np.newaxis].astype(int).astype(str)], axis=1)
|
| 55 |
+
|
| 56 |
+
if len(y_real) > 50000:
|
| 57 |
+
ixs = np.random.choice(len(y_real), 50000, replace=False)
|
| 58 |
+
X_num_real = X_num_real[ixs]
|
| 59 |
+
X_cat_real = X_cat_real[ixs] if X_cat_real is not None else None
|
| 60 |
+
|
| 61 |
+
if len(y_fake) > 50000:
|
| 62 |
+
ixs = np.random.choice(len(y_fake), 50000, replace=False)
|
| 63 |
+
X_num_fake = X_num_fake[ixs]
|
| 64 |
+
X_cat_fake = X_cat_fake[ixs] if X_cat_fake is not None else None
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
mm = MinMaxScaler().fit(X_num_real)
|
| 68 |
+
X_real = mm.transform(X_num_real)
|
| 69 |
+
X_fake = mm.transform(X_num_fake)
|
| 70 |
+
if X_cat_real is not None:
|
| 71 |
+
ohe = OneHotEncoder().fit(X_cat_real)
|
| 72 |
+
X_cat_real = ohe.transform(X_cat_real) / np.sqrt(2)
|
| 73 |
+
X_cat_fake = ohe.transform(X_cat_fake) / np.sqrt(2)
|
| 74 |
+
|
| 75 |
+
X_real = np.concatenate([X_real, X_cat_real.todense()], axis=1)
|
| 76 |
+
X_fake = np.concatenate([X_fake, X_cat_fake.todense()], axis=1)
|
| 77 |
+
|
| 78 |
+
# X_real = np.unique(X_real, axis=0)
|
| 79 |
+
# X_fake = np.unique(X_fake, axis=0)
|
| 80 |
+
|
| 81 |
+
# Computing pair-wise distances between real and synthetic
|
| 82 |
+
dist_rf = pairwise_distances(X_fake, Y=X_real, metric='l2', n_jobs=-1)
|
| 83 |
+
# Computing pair-wise distances within real
|
| 84 |
+
# dist_rr = pairwise_distances(X_real, Y=None, metric='l2', n_jobs=-1)
|
| 85 |
+
# Computing pair-wise distances within synthetic
|
| 86 |
+
# dist_ff = pairwise_distances(X_fake, Y=None, metric='l2', n_jobs=-1)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# Removes distances of data points to themselves to avoid 0s within real and synthetic
|
| 90 |
+
# rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1)
|
| 91 |
+
# rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1)
|
| 92 |
+
|
| 93 |
+
# Computing first and second smallest nearest neighbour distances between real and synthetic
|
| 94 |
+
smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))]
|
| 95 |
+
smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))]
|
| 96 |
+
# Computing first and second smallest nearest neighbour distances within real
|
| 97 |
+
# smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))]
|
| 98 |
+
# smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))]
|
| 99 |
+
# Computing first and second smallest nearest neighbour distances within synthetic
|
| 100 |
+
# smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))]
|
| 101 |
+
# smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))]
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# Computing 5th percentiles for DCR and NNDR between and within real and synthetic datasets
|
| 105 |
+
min_dist_rf = np.array([i[0] for i in smallest_two_rf])
|
| 106 |
+
fifth_perc_rf = np.percentile(min_dist_rf,5)
|
| 107 |
+
# min_dist_rr = np.array([i[0] for i in smallest_two_rr])
|
| 108 |
+
# fifth_perc_rr = np.percentile(min_dist_rr,5)
|
| 109 |
+
# min_dist_ff = np.array([i[0] for i in smallest_two_ff])
|
| 110 |
+
# fifth_perc_ff = np.percentile(min_dist_ff,5)
|
| 111 |
+
# nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf])
|
| 112 |
+
# nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5)
|
| 113 |
+
# nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr])
|
| 114 |
+
# nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5)
|
| 115 |
+
# nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff])
|
| 116 |
+
# nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5)
|
| 117 |
+
|
| 118 |
+
# return np.array([fifth_perc_rf,fifth_perc_rr,fifth_perc_ff,nn_fifth_perc_rf,nn_fifth_perc_rr,nn_fifth_perc_ff]).reshape(1,6)
|
| 119 |
+
return min_dist_rf # , min_dist_rr
|
| 120 |
+
|
| 121 |
+
def sample_wrapper(method, config, num_samples=None, seed=0):
|
| 122 |
+
if method == "ddpm":
|
| 123 |
+
sample(
|
| 124 |
+
num_samples=num_samples,
|
| 125 |
+
batch_size=config['sample']['batch_size'],
|
| 126 |
+
disbalance=config['sample'].get('disbalance', None),
|
| 127 |
+
**config['diffusion_params'],
|
| 128 |
+
parent_dir=config['parent_dir'],
|
| 129 |
+
real_data_path=config['real_data_path'],
|
| 130 |
+
model_path=os.path.join(config['parent_dir'], 'model.pt'),
|
| 131 |
+
model_type=config['model_type'],
|
| 132 |
+
model_params=config['model_params'],
|
| 133 |
+
T_dict=config['train']['T'],
|
| 134 |
+
num_numerical_features=config['num_numerical_features'],
|
| 135 |
+
seed=seed,
|
| 136 |
+
change_val=False,
|
| 137 |
+
device=torch.device(config["device"])
|
| 138 |
+
)
|
| 139 |
+
elif method == "smote":
|
| 140 |
+
sample_smote(
|
| 141 |
+
parent_dir=config['parent_dir'],
|
| 142 |
+
real_data_path=config['real_data_path'],
|
| 143 |
+
**config['smote_params'],
|
| 144 |
+
seed=seed,
|
| 145 |
+
change_val=False
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
def resample_privacy(config_path, method, q):
|
| 149 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 150 |
+
config = lib.load_config(config_path)
|
| 151 |
+
if method == "ddpm":
|
| 152 |
+
shutil.copy2(os.path.join(config['parent_dir'], 'model.pt'), os.path.join(dir_, 'model.pt'))
|
| 153 |
+
config["parent_dir"] = str(dir_)
|
| 154 |
+
parent_dir = config["parent_dir"]
|
| 155 |
+
|
| 156 |
+
sample_wrapper(method, config, num_samples=config["sample"].get("num_samples", 0))
|
| 157 |
+
|
| 158 |
+
dists = privacy_metrics(config["real_data_path"], parent_dir)
|
| 159 |
+
old_privacy = np.median(dists)
|
| 160 |
+
|
| 161 |
+
q10 = np.quantile(dists, q=q)
|
| 162 |
+
print(f"Q: {q10}")
|
| 163 |
+
to_drop = np.where(dists < q10)
|
| 164 |
+
|
| 165 |
+
X_num, X_cat, y = lib.read_pure_data(parent_dir)
|
| 166 |
+
num_samples = len(y)
|
| 167 |
+
X_num = np.delete(X_num, to_drop, axis=0)
|
| 168 |
+
X_cat = np.delete(X_cat, to_drop, axis=0) if X_cat is not None else None
|
| 169 |
+
y = np.delete(y, to_drop, axis=0)
|
| 170 |
+
i = 1
|
| 171 |
+
|
| 172 |
+
while len(y) < num_samples and i <= 10:
|
| 173 |
+
print(f"{len(y)}/{num_samples}")
|
| 174 |
+
|
| 175 |
+
sample_wrapper(method, config, num_samples=config["sample"].get("batch_size", 0), seed=i)
|
| 176 |
+
|
| 177 |
+
i += 1
|
| 178 |
+
|
| 179 |
+
X_num_t, X_cat_t, y_t = lib.read_pure_data(parent_dir)
|
| 180 |
+
dists = privacy_metrics(config["real_data_path"], parent_dir)
|
| 181 |
+
to_drop = np.where(dists < q10)
|
| 182 |
+
X_num_t = np.delete(X_num_t, to_drop, axis=0)
|
| 183 |
+
X_cat_t = np.delete(X_cat_t, to_drop, axis=0) if X_cat is not None else None
|
| 184 |
+
y_t = np.delete(y_t, to_drop, axis=0)
|
| 185 |
+
|
| 186 |
+
X_num = np.concatenate([X_num, X_num_t], axis=0)[:num_samples]
|
| 187 |
+
X_cat = np.concatenate([X_cat, X_cat_t], axis=0)[:num_samples] if X_cat is not None else None
|
| 188 |
+
y = np.concatenate([y, y_t], axis=0)[:num_samples]
|
| 189 |
+
|
| 190 |
+
# np.save(os.path.join(parent_dir, 'X_num_train'), X_num)
|
| 191 |
+
# if X_cat is not None:
|
| 192 |
+
# np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat)
|
| 193 |
+
# np.save(os.path.join(parent_dir, 'y_train'), y)
|
| 194 |
+
|
| 195 |
+
np.save(os.path.join(parent_dir, 'X_num_train'), X_num)
|
| 196 |
+
if X_cat is not None:
|
| 197 |
+
np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat)
|
| 198 |
+
np.save(os.path.join(parent_dir, 'y_train'), y)
|
| 199 |
+
|
| 200 |
+
new_dists = privacy_metrics(config["real_data_path"], parent_dir)
|
| 201 |
+
|
| 202 |
+
res = eval_seeds(
|
| 203 |
+
config,
|
| 204 |
+
n_seeds=10,
|
| 205 |
+
eval_type="synthetic",
|
| 206 |
+
model_type="catboost",
|
| 207 |
+
n_datasets=1,
|
| 208 |
+
dump=False
|
| 209 |
+
)
|
| 210 |
+
print(f"Old: {old_privacy:.4f}, New: {np.median(new_dists):.4f}")
|
| 211 |
+
|
| 212 |
+
metric = "r2-mean" if "r2-mean" in res["test"] else "f1-mean"
|
| 213 |
+
return res["test"][metric], np.around(np.median(new_dists), 4)
|
| 214 |
+
|
| 215 |
+
def resample_privacy_qs(config_path, method):
|
| 216 |
+
config = lib.load_config(config_path)
|
| 217 |
+
scores = []
|
| 218 |
+
privacies = []
|
| 219 |
+
|
| 220 |
+
eval_res = lib.load_json(Path(config["parent_dir"]) / "eval_catboost.json")["synthetic"]["test"]
|
| 221 |
+
metric = "r2-mean" if "r2-mean" in eval_res else "f1-mean"
|
| 222 |
+
scores.append(eval_res[metric])
|
| 223 |
+
privacies.append(np.median(privacy_metrics(config["real_data_path"], config["parent_dir"])))
|
| 224 |
+
|
| 225 |
+
for q in [0.1, 0.2, 0.3, 0.4]:
|
| 226 |
+
score, privacy = resample_privacy(config_path, method, q)
|
| 227 |
+
scores.append(score)
|
| 228 |
+
privacies.append(privacy)
|
| 229 |
+
|
| 230 |
+
lib.dump_json(
|
| 231 |
+
{"scores": scores, "privacies": privacies},
|
| 232 |
+
Path(config["parent_dir"]) / "privacies.json"
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
def calc_privacy(config_path, method, seed=0):
|
| 236 |
+
config = lib.load_config(config_path)
|
| 237 |
+
sample_wrapper(method, config, num_samples=config["sample"]["num_samples"], seed=seed)
|
| 238 |
+
timer = zero.Timer()
|
| 239 |
+
timer.run()
|
| 240 |
+
dists = privacy_metrics(config["real_data_path"], config["parent_dir"])
|
| 241 |
+
privacy_val = np.median(dists)
|
| 242 |
+
lib.dump_json({"privacy": privacy_val}, os.path.join(config["parent_dir"], "privacy.json"))
|
| 243 |
+
print(f"Elapsed tine:{str(timer)}")
|
| 244 |
+
|
| 245 |
+
def main():
|
| 246 |
+
parser = argparse.ArgumentParser()
|
| 247 |
+
parser.add_argument('--config', metavar='FILE')
|
| 248 |
+
parser.add_argument('method', type=str)
|
| 249 |
+
args = parser.parse_args()
|
| 250 |
+
|
| 251 |
+
calc_privacy(
|
| 252 |
+
args.config,
|
| 253 |
+
args.method
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
if __name__ == "__main__":
|
| 257 |
+
main()
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/sample.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import zero
|
| 4 |
+
import os
|
| 5 |
+
from tab_ddpm.gaussian_multinomial_diffsuion import GaussianMultinomialDiffusion
|
| 6 |
+
from tab_ddpm.utils import FoundNANsError
|
| 7 |
+
from scripts.utils_train import get_model, make_dataset
|
| 8 |
+
from lib import round_columns
|
| 9 |
+
import lib
|
| 10 |
+
|
| 11 |
+
def to_good_ohe(ohe, X):
|
| 12 |
+
indices = np.cumsum([0] + ohe._n_features_outs)
|
| 13 |
+
Xres = []
|
| 14 |
+
for i in range(1, len(indices)):
|
| 15 |
+
x_ = np.max(X[:, indices[i - 1]:indices[i]], axis=1)
|
| 16 |
+
t = X[:, indices[i - 1]:indices[i]] - x_.reshape(-1, 1)
|
| 17 |
+
Xres.append(np.where(t >= 0, 1, 0))
|
| 18 |
+
return np.hstack(Xres)
|
| 19 |
+
|
| 20 |
+
def sample(
|
| 21 |
+
parent_dir,
|
| 22 |
+
real_data_path = 'data/higgs-small',
|
| 23 |
+
batch_size = 2000,
|
| 24 |
+
num_samples = 0,
|
| 25 |
+
model_type = 'mlp',
|
| 26 |
+
model_params = None,
|
| 27 |
+
model_path = None,
|
| 28 |
+
num_timesteps = 1000,
|
| 29 |
+
gaussian_loss_type = 'mse',
|
| 30 |
+
scheduler = 'cosine',
|
| 31 |
+
T_dict = None,
|
| 32 |
+
num_numerical_features = 0,
|
| 33 |
+
disbalance = None,
|
| 34 |
+
device = torch.device('cuda:1'),
|
| 35 |
+
seed = 0,
|
| 36 |
+
change_val = False
|
| 37 |
+
):
|
| 38 |
+
zero.improve_reproducibility(seed)
|
| 39 |
+
|
| 40 |
+
T = lib.Transformations(**T_dict)
|
| 41 |
+
D = make_dataset(
|
| 42 |
+
real_data_path,
|
| 43 |
+
T,
|
| 44 |
+
num_classes=model_params['num_classes'],
|
| 45 |
+
is_y_cond=model_params['is_y_cond'],
|
| 46 |
+
change_val=change_val
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
K = np.array(D.get_category_sizes('train'))
|
| 50 |
+
if len(K) == 0 or T_dict['cat_encoding'] == 'one-hot':
|
| 51 |
+
K = np.array([0])
|
| 52 |
+
|
| 53 |
+
num_numerical_features_ = D.X_num['train'].shape[1] if D.X_num is not None else 0
|
| 54 |
+
d_in = np.sum(K) + num_numerical_features_
|
| 55 |
+
model_params['d_in'] = int(d_in)
|
| 56 |
+
model = get_model(
|
| 57 |
+
model_type,
|
| 58 |
+
model_params,
|
| 59 |
+
num_numerical_features_,
|
| 60 |
+
category_sizes=D.get_category_sizes('train')
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
model.load_state_dict(
|
| 64 |
+
torch.load(model_path, map_location="cpu")
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
diffusion = GaussianMultinomialDiffusion(
|
| 68 |
+
K,
|
| 69 |
+
num_numerical_features=num_numerical_features_,
|
| 70 |
+
denoise_fn=model, num_timesteps=num_timesteps,
|
| 71 |
+
gaussian_loss_type=gaussian_loss_type, scheduler=scheduler, device=device
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
diffusion.to(device)
|
| 75 |
+
diffusion.eval()
|
| 76 |
+
|
| 77 |
+
_, empirical_class_dist = torch.unique(torch.from_numpy(D.y['train']), return_counts=True)
|
| 78 |
+
# empirical_class_dist = empirical_class_dist.float() + torch.tensor([-5000., 10000.]).float()
|
| 79 |
+
if disbalance == 'fix':
|
| 80 |
+
empirical_class_dist[0], empirical_class_dist[1] = empirical_class_dist[1], empirical_class_dist[0]
|
| 81 |
+
x_gen, y_gen = diffusion.sample_all(num_samples, batch_size, empirical_class_dist.float(), ddim=False)
|
| 82 |
+
|
| 83 |
+
elif disbalance == 'fill':
|
| 84 |
+
ix_major = empirical_class_dist.argmax().item()
|
| 85 |
+
val_major = empirical_class_dist[ix_major].item()
|
| 86 |
+
x_gen, y_gen = [], []
|
| 87 |
+
for i in range(empirical_class_dist.shape[0]):
|
| 88 |
+
if i == ix_major:
|
| 89 |
+
continue
|
| 90 |
+
distrib = torch.zeros_like(empirical_class_dist)
|
| 91 |
+
distrib[i] = 1
|
| 92 |
+
num_samples = val_major - empirical_class_dist[i].item()
|
| 93 |
+
x_temp, y_temp = diffusion.sample_all(num_samples, batch_size, distrib.float(), ddim=False)
|
| 94 |
+
x_gen.append(x_temp)
|
| 95 |
+
y_gen.append(y_temp)
|
| 96 |
+
|
| 97 |
+
x_gen = torch.cat(x_gen, dim=0)
|
| 98 |
+
y_gen = torch.cat(y_gen, dim=0)
|
| 99 |
+
|
| 100 |
+
else:
|
| 101 |
+
x_gen, y_gen = diffusion.sample_all(num_samples, batch_size, empirical_class_dist.float(), ddim=False)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
# try:
|
| 105 |
+
# except FoundNANsError as ex:
|
| 106 |
+
# print("Found NaNs during sampling!")
|
| 107 |
+
# loader = lib.prepare_fast_dataloader(D, 'train', 8)
|
| 108 |
+
# x_gen = next(loader)[0]
|
| 109 |
+
# y_gen = torch.multinomial(
|
| 110 |
+
# empirical_class_dist.float(),
|
| 111 |
+
# num_samples=8,
|
| 112 |
+
# replacement=True
|
| 113 |
+
# )
|
| 114 |
+
X_gen, y_gen = x_gen.numpy(), y_gen.numpy()
|
| 115 |
+
|
| 116 |
+
###
|
| 117 |
+
# X_num_unnorm = X_gen[:, :num_numerical_features]
|
| 118 |
+
# lo = np.percentile(X_num_unnorm, 2.5, axis=0)
|
| 119 |
+
# hi = np.percentile(X_num_unnorm, 97.5, axis=0)
|
| 120 |
+
# idx = (lo < X_num_unnorm) & (hi > X_num_unnorm)
|
| 121 |
+
# X_gen = X_gen[np.all(idx, axis=1)]
|
| 122 |
+
# y_gen = y_gen[np.all(idx, axis=1)]
|
| 123 |
+
###
|
| 124 |
+
|
| 125 |
+
num_numerical_features = num_numerical_features + int(D.is_regression and not model_params["is_y_cond"])
|
| 126 |
+
|
| 127 |
+
X_num_ = X_gen
|
| 128 |
+
if num_numerical_features < X_gen.shape[1]:
|
| 129 |
+
np.save(os.path.join(parent_dir, 'X_cat_unnorm'), X_gen[:, num_numerical_features:])
|
| 130 |
+
# _, _, cat_encoder = lib.cat_encode({'train': X_cat_real}, T_dict['cat_encoding'], y_real, T_dict['seed'], True)
|
| 131 |
+
if T_dict['cat_encoding'] == 'one-hot':
|
| 132 |
+
X_gen[:, num_numerical_features:] = to_good_ohe(D.cat_transform.steps[0][1], X_num_[:, num_numerical_features:])
|
| 133 |
+
X_cat = D.cat_transform.inverse_transform(X_gen[:, num_numerical_features:])
|
| 134 |
+
|
| 135 |
+
if num_numerical_features_ != 0:
|
| 136 |
+
# _, normalize = lib.normalize({'train' : X_num_real}, T_dict['normalization'], T_dict['seed'], True)
|
| 137 |
+
np.save(os.path.join(parent_dir, 'X_num_unnorm'), X_gen[:, :num_numerical_features])
|
| 138 |
+
X_num_ = D.num_transform.inverse_transform(X_gen[:, :num_numerical_features])
|
| 139 |
+
X_num = X_num_[:, :num_numerical_features]
|
| 140 |
+
|
| 141 |
+
X_num_real = np.load(os.path.join(real_data_path, "X_num_train.npy"), allow_pickle=True)
|
| 142 |
+
disc_cols = []
|
| 143 |
+
for col in range(X_num_real.shape[1]):
|
| 144 |
+
uniq_vals = np.unique(X_num_real[:, col])
|
| 145 |
+
if len(uniq_vals) <= 32 and ((uniq_vals - np.round(uniq_vals)) == 0).all():
|
| 146 |
+
disc_cols.append(col)
|
| 147 |
+
print("Discrete cols:", disc_cols)
|
| 148 |
+
# 仅当 regression 且 y 在 X_num 中(非 is_y_cond)时才提取 y;否则 y_gen 已由 sample_all 返回
|
| 149 |
+
if model_params['num_classes'] == 0 and not model_params.get('is_y_cond', True):
|
| 150 |
+
y_gen = X_num[:, 0]
|
| 151 |
+
X_num = X_num[:, 1:]
|
| 152 |
+
if len(disc_cols):
|
| 153 |
+
X_num = round_columns(X_num_real, X_num, disc_cols)
|
| 154 |
+
|
| 155 |
+
if num_numerical_features != 0:
|
| 156 |
+
print("Num shape: ", X_num.shape)
|
| 157 |
+
np.save(os.path.join(parent_dir, 'X_num_train'), X_num)
|
| 158 |
+
if num_numerical_features < X_gen.shape[1]:
|
| 159 |
+
np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat)
|
| 160 |
+
np.save(os.path.join(parent_dir, 'y_train'), y_gen)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/train.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import deepcopy
|
| 2 |
+
import torch
|
| 3 |
+
import os
|
| 4 |
+
import numpy as np
|
| 5 |
+
import zero
|
| 6 |
+
from tab_ddpm import GaussianMultinomialDiffusion
|
| 7 |
+
from scripts.utils_train import get_model, make_dataset, update_ema
|
| 8 |
+
import lib
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
class Trainer:
|
| 12 |
+
def __init__(self, diffusion, train_iter, lr, weight_decay, steps, device=torch.device('cuda:1')):
|
| 13 |
+
self.diffusion = diffusion
|
| 14 |
+
self.ema_model = deepcopy(self.diffusion._denoise_fn)
|
| 15 |
+
for param in self.ema_model.parameters():
|
| 16 |
+
param.detach_()
|
| 17 |
+
|
| 18 |
+
self.train_iter = train_iter
|
| 19 |
+
self.steps = steps
|
| 20 |
+
self.init_lr = lr
|
| 21 |
+
self.optimizer = torch.optim.AdamW(self.diffusion.parameters(), lr=lr, weight_decay=weight_decay)
|
| 22 |
+
self.device = device
|
| 23 |
+
self.loss_history = pd.DataFrame(columns=['step', 'mloss', 'gloss', 'loss'])
|
| 24 |
+
self.log_every = 100
|
| 25 |
+
self.print_every = 500
|
| 26 |
+
self.ema_every = 1000
|
| 27 |
+
|
| 28 |
+
def _anneal_lr(self, step):
|
| 29 |
+
frac_done = step / self.steps
|
| 30 |
+
lr = self.init_lr * (1 - frac_done)
|
| 31 |
+
for param_group in self.optimizer.param_groups:
|
| 32 |
+
param_group["lr"] = lr
|
| 33 |
+
|
| 34 |
+
def _run_step(self, x, out_dict):
|
| 35 |
+
x = x.to(self.device)
|
| 36 |
+
for k in out_dict:
|
| 37 |
+
out_dict[k] = out_dict[k].long().to(self.device)
|
| 38 |
+
self.optimizer.zero_grad()
|
| 39 |
+
loss_multi, loss_gauss = self.diffusion.mixed_loss(x, out_dict)
|
| 40 |
+
loss = loss_multi + loss_gauss
|
| 41 |
+
loss.backward()
|
| 42 |
+
self.optimizer.step()
|
| 43 |
+
|
| 44 |
+
return loss_multi, loss_gauss
|
| 45 |
+
|
| 46 |
+
def run_loop(self):
|
| 47 |
+
step = 0
|
| 48 |
+
curr_loss_multi = 0.0
|
| 49 |
+
curr_loss_gauss = 0.0
|
| 50 |
+
|
| 51 |
+
curr_count = 0
|
| 52 |
+
while step < self.steps:
|
| 53 |
+
x, out_dict = next(self.train_iter)
|
| 54 |
+
out_dict = {'y': out_dict}
|
| 55 |
+
batch_loss_multi, batch_loss_gauss = self._run_step(x, out_dict)
|
| 56 |
+
|
| 57 |
+
self._anneal_lr(step)
|
| 58 |
+
|
| 59 |
+
curr_count += len(x)
|
| 60 |
+
curr_loss_multi += batch_loss_multi.item() * len(x)
|
| 61 |
+
curr_loss_gauss += batch_loss_gauss.item() * len(x)
|
| 62 |
+
|
| 63 |
+
if (step + 1) % self.log_every == 0:
|
| 64 |
+
mloss = np.around(curr_loss_multi / curr_count, 4)
|
| 65 |
+
gloss = np.around(curr_loss_gauss / curr_count, 4)
|
| 66 |
+
if (step + 1) % self.print_every == 0:
|
| 67 |
+
print(f'Step {(step + 1)}/{self.steps} MLoss: {mloss} GLoss: {gloss} Sum: {mloss + gloss}')
|
| 68 |
+
self.loss_history.loc[len(self.loss_history)] =[step + 1, mloss, gloss, mloss + gloss]
|
| 69 |
+
curr_count = 0
|
| 70 |
+
curr_loss_gauss = 0.0
|
| 71 |
+
curr_loss_multi = 0.0
|
| 72 |
+
|
| 73 |
+
update_ema(self.ema_model.parameters(), self.diffusion._denoise_fn.parameters())
|
| 74 |
+
|
| 75 |
+
step += 1
|
| 76 |
+
|
| 77 |
+
def train(
|
| 78 |
+
parent_dir,
|
| 79 |
+
real_data_path = 'data/higgs-small',
|
| 80 |
+
steps = 1000,
|
| 81 |
+
lr = 0.002,
|
| 82 |
+
weight_decay = 1e-4,
|
| 83 |
+
batch_size = 1024,
|
| 84 |
+
model_type = 'mlp',
|
| 85 |
+
model_params = None,
|
| 86 |
+
num_timesteps = 1000,
|
| 87 |
+
gaussian_loss_type = 'mse',
|
| 88 |
+
scheduler = 'cosine',
|
| 89 |
+
T_dict = None,
|
| 90 |
+
num_numerical_features = 0,
|
| 91 |
+
device = torch.device('cuda:1'),
|
| 92 |
+
seed = 0,
|
| 93 |
+
change_val = False
|
| 94 |
+
):
|
| 95 |
+
real_data_path = os.path.normpath(real_data_path)
|
| 96 |
+
parent_dir = os.path.normpath(parent_dir)
|
| 97 |
+
|
| 98 |
+
zero.improve_reproducibility(seed)
|
| 99 |
+
|
| 100 |
+
T = lib.Transformations(**T_dict)
|
| 101 |
+
|
| 102 |
+
dataset = make_dataset(
|
| 103 |
+
real_data_path,
|
| 104 |
+
T,
|
| 105 |
+
num_classes=model_params['num_classes'],
|
| 106 |
+
is_y_cond=model_params['is_y_cond'],
|
| 107 |
+
change_val=change_val
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
K = np.array(dataset.get_category_sizes('train'))
|
| 111 |
+
if len(K) == 0 or T_dict['cat_encoding'] == 'one-hot':
|
| 112 |
+
K = np.array([0])
|
| 113 |
+
print(K)
|
| 114 |
+
|
| 115 |
+
num_numerical_features = dataset.X_num['train'].shape[1] if dataset.X_num is not None else 0
|
| 116 |
+
d_in = np.sum(K) + num_numerical_features
|
| 117 |
+
model_params['d_in'] = d_in
|
| 118 |
+
print(d_in)
|
| 119 |
+
|
| 120 |
+
print(model_params)
|
| 121 |
+
model = get_model(
|
| 122 |
+
model_type,
|
| 123 |
+
model_params,
|
| 124 |
+
num_numerical_features,
|
| 125 |
+
category_sizes=dataset.get_category_sizes('train')
|
| 126 |
+
)
|
| 127 |
+
model.to(device)
|
| 128 |
+
|
| 129 |
+
# train_loader = lib.prepare_beton_loader(dataset, split='train', batch_size=batch_size)
|
| 130 |
+
train_loader = lib.prepare_fast_dataloader(dataset, split='train', batch_size=batch_size)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
diffusion = GaussianMultinomialDiffusion(
|
| 135 |
+
num_classes=K,
|
| 136 |
+
num_numerical_features=num_numerical_features,
|
| 137 |
+
denoise_fn=model,
|
| 138 |
+
gaussian_loss_type=gaussian_loss_type,
|
| 139 |
+
num_timesteps=num_timesteps,
|
| 140 |
+
scheduler=scheduler,
|
| 141 |
+
device=device
|
| 142 |
+
)
|
| 143 |
+
diffusion.to(device)
|
| 144 |
+
diffusion.train()
|
| 145 |
+
|
| 146 |
+
trainer = Trainer(
|
| 147 |
+
diffusion,
|
| 148 |
+
train_loader,
|
| 149 |
+
lr=lr,
|
| 150 |
+
weight_decay=weight_decay,
|
| 151 |
+
steps=steps,
|
| 152 |
+
device=device
|
| 153 |
+
)
|
| 154 |
+
trainer.run_loop()
|
| 155 |
+
|
| 156 |
+
trainer.loss_history.to_csv(os.path.join(parent_dir, 'loss.csv'), index=False)
|
| 157 |
+
torch.save(diffusion._denoise_fn.state_dict(), os.path.join(parent_dir, 'model.pt'))
|
| 158 |
+
torch.save(trainer.ema_model.state_dict(), os.path.join(parent_dir, 'model_ema.pt'))
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_evaluation_model.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import optuna
|
| 2 |
+
import lib
|
| 3 |
+
import argparse
|
| 4 |
+
from eval_catboost import train_catboost
|
| 5 |
+
from eval_mlp import train_mlp
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
parser = argparse.ArgumentParser()
|
| 9 |
+
parser.add_argument('ds_name', type=str)
|
| 10 |
+
parser.add_argument('model', type=str)
|
| 11 |
+
parser.add_argument('tune_type', type=str)
|
| 12 |
+
parser.add_argument('device', type=str)
|
| 13 |
+
|
| 14 |
+
args = parser.parse_args()
|
| 15 |
+
data_path = Path(f"data/{args.ds_name}")
|
| 16 |
+
best_params = None
|
| 17 |
+
|
| 18 |
+
assert args.tune_type in ("cv", "val")
|
| 19 |
+
|
| 20 |
+
def _suggest(trial: optuna.trial.Trial, distribution: str, label: str, *args):
|
| 21 |
+
return getattr(trial, f'suggest_{distribution}')(label, *args)
|
| 22 |
+
|
| 23 |
+
def _suggest_optional(trial: optuna.trial.Trial, distribution: str, label: str, *args):
|
| 24 |
+
if trial.suggest_categorical(f"optional_{label}", [True, False]):
|
| 25 |
+
return _suggest(trial, distribution, label, *args)
|
| 26 |
+
else:
|
| 27 |
+
return 0.0
|
| 28 |
+
|
| 29 |
+
def _suggest_mlp_layers(trial: optuna.trial.Trial, mlp_d_layers: list[int]):
|
| 30 |
+
|
| 31 |
+
min_n_layers, max_n_layers = mlp_d_layers[0], mlp_d_layers[1]
|
| 32 |
+
d_min, d_max = mlp_d_layers[2], mlp_d_layers[3]
|
| 33 |
+
|
| 34 |
+
def suggest_dim(name):
|
| 35 |
+
t = trial.suggest_int(name, d_min, d_max)
|
| 36 |
+
return 2 ** t
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers)
|
| 40 |
+
d_first = [suggest_dim('d_first')] if n_layers else []
|
| 41 |
+
d_middle = (
|
| 42 |
+
[suggest_dim('d_middle')] * (n_layers - 2)
|
| 43 |
+
if n_layers > 2
|
| 44 |
+
else []
|
| 45 |
+
)
|
| 46 |
+
d_last = [suggest_dim('d_last')] if n_layers > 1 else []
|
| 47 |
+
d_layers = d_first + d_middle + d_last
|
| 48 |
+
|
| 49 |
+
return d_layers
|
| 50 |
+
|
| 51 |
+
def suggest_mlp_params(trial):
|
| 52 |
+
params = {}
|
| 53 |
+
params["lr"] = trial.suggest_loguniform("lr", 5e-5, 0.005)
|
| 54 |
+
params["dropout"] = _suggest_optional(trial, "uniform", "dropout", 0.0, 0.5)
|
| 55 |
+
params["weight_decay"] = _suggest_optional(trial, "loguniform", "weight_decay", 1e-6, 1e-2)
|
| 56 |
+
params["d_layers"] = _suggest_mlp_layers(trial, [1, 8, 6, 10])
|
| 57 |
+
|
| 58 |
+
return params
|
| 59 |
+
|
| 60 |
+
def suggest_catboost_params(trial):
|
| 61 |
+
params = {}
|
| 62 |
+
params["learning_rate"] = trial.suggest_loguniform("learning_rate", 0.001, 1.0)
|
| 63 |
+
params["depth"] = trial.suggest_int("depth", 3, 10)
|
| 64 |
+
params["l2_leaf_reg"] = trial.suggest_uniform("l2_leaf_reg", 0.1, 10.0)
|
| 65 |
+
params["bagging_temperature"] = trial.suggest_uniform("bagging_temperature", 0.0, 1.0)
|
| 66 |
+
params["leaf_estimation_iterations"] = trial.suggest_int("leaf_estimation_iterations", 1, 10)
|
| 67 |
+
|
| 68 |
+
params = params | {
|
| 69 |
+
"iterations": 2000,
|
| 70 |
+
"early_stopping_rounds": 50,
|
| 71 |
+
"od_pval": 0.001,
|
| 72 |
+
"task_type": "CPU", # "GPU", may affect performance
|
| 73 |
+
"thread_count": 4,
|
| 74 |
+
# "devices": "0", # for GPU
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
return params
|
| 78 |
+
|
| 79 |
+
def objective(trial):
|
| 80 |
+
if args.model == "mlp":
|
| 81 |
+
params = suggest_mlp_params(trial)
|
| 82 |
+
train_func = train_mlp
|
| 83 |
+
T_dict = {
|
| 84 |
+
"seed": 0,
|
| 85 |
+
"normalization": "quantile",
|
| 86 |
+
"num_nan_policy": None,
|
| 87 |
+
"cat_nan_policy": None,
|
| 88 |
+
"cat_min_frequency": None,
|
| 89 |
+
"cat_encoding": "one-hot",
|
| 90 |
+
"y_policy": "default"
|
| 91 |
+
}
|
| 92 |
+
else:
|
| 93 |
+
params = suggest_catboost_params(trial)
|
| 94 |
+
train_func = train_catboost
|
| 95 |
+
T_dict = {
|
| 96 |
+
"seed": 0,
|
| 97 |
+
"normalization": None,
|
| 98 |
+
"num_nan_policy": None,
|
| 99 |
+
"cat_nan_policy": None,
|
| 100 |
+
"cat_min_frequency": None,
|
| 101 |
+
"cat_encoding": None,
|
| 102 |
+
"y_policy": "default"
|
| 103 |
+
}
|
| 104 |
+
trial.set_user_attr("params", params)
|
| 105 |
+
if args.tune_type == "cv":
|
| 106 |
+
score = 0.0
|
| 107 |
+
for fold in range(5):
|
| 108 |
+
metrics_report = train_func(
|
| 109 |
+
parent_dir=None,
|
| 110 |
+
real_data_path=data_path / f"kfolds/{fold}",
|
| 111 |
+
eval_type="real",
|
| 112 |
+
T_dict=T_dict,
|
| 113 |
+
params=params,
|
| 114 |
+
change_val=False,
|
| 115 |
+
device=args.device
|
| 116 |
+
)
|
| 117 |
+
score += metrics_report.get_val_score()
|
| 118 |
+
score /= 5
|
| 119 |
+
|
| 120 |
+
elif args.tune_type == "val":
|
| 121 |
+
metrics_report = train_func(
|
| 122 |
+
parent_dir=None,
|
| 123 |
+
real_data_path=data_path,
|
| 124 |
+
eval_type="real",
|
| 125 |
+
T_dict=T_dict,
|
| 126 |
+
params=params,
|
| 127 |
+
change_val=False,
|
| 128 |
+
device=args.device
|
| 129 |
+
)
|
| 130 |
+
score = metrics_report.get_val_score()
|
| 131 |
+
|
| 132 |
+
return score
|
| 133 |
+
|
| 134 |
+
study = optuna.create_study(
|
| 135 |
+
direction='maximize',
|
| 136 |
+
sampler=optuna.samplers.TPESampler(seed=0),
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
study.optimize(objective, n_trials=100, show_progress_bar=True)
|
| 140 |
+
|
| 141 |
+
bets_params = study.best_trial.user_attrs['params']
|
| 142 |
+
|
| 143 |
+
best_params_path = f"tuned_models/{args.model}/{args.ds_name}_{args.tune_type}.json"
|
| 144 |
+
|
| 145 |
+
lib.dump_json(bets_params, best_params_path)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__init__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .gaussian_multinomial_diffsuion import * # noqa
|
| 2 |
+
from .modules import * # noqa
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/gaussian_multinomial_diffsuion.py
ADDED
|
@@ -0,0 +1,993 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Based on https://github.com/openai/guided-diffusion/blob/main/guided_diffusion
|
| 3 |
+
and https://github.com/ehoogeboom/multinomial_diffusion
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
import torch
|
| 8 |
+
import math
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from .utils import *
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
Based in part on: https://github.com/lucidrains/denoising-diffusion-pytorch/blob/5989f4c77eafcdc6be0fb4739f0f277a6dd7f7d8/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py#L281
|
| 15 |
+
"""
|
| 16 |
+
eps = 1e-8
|
| 17 |
+
|
| 18 |
+
def get_named_beta_schedule(schedule_name, num_diffusion_timesteps):
|
| 19 |
+
"""
|
| 20 |
+
Get a pre-defined beta schedule for the given name.
|
| 21 |
+
The beta schedule library consists of beta schedules which remain similar
|
| 22 |
+
in the limit of num_diffusion_timesteps.
|
| 23 |
+
Beta schedules may be added, but should not be removed or changed once
|
| 24 |
+
they are committed to maintain backwards compatibility.
|
| 25 |
+
"""
|
| 26 |
+
if schedule_name == "linear":
|
| 27 |
+
# Linear schedule from Ho et al, extended to work for any number of
|
| 28 |
+
# diffusion steps.
|
| 29 |
+
scale = 1000 / num_diffusion_timesteps
|
| 30 |
+
beta_start = scale * 0.0001
|
| 31 |
+
beta_end = scale * 0.02
|
| 32 |
+
return np.linspace(
|
| 33 |
+
beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64
|
| 34 |
+
)
|
| 35 |
+
elif schedule_name == "cosine":
|
| 36 |
+
return betas_for_alpha_bar(
|
| 37 |
+
num_diffusion_timesteps,
|
| 38 |
+
lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,
|
| 39 |
+
)
|
| 40 |
+
else:
|
| 41 |
+
raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
|
| 45 |
+
"""
|
| 46 |
+
Create a beta schedule that discretizes the given alpha_t_bar function,
|
| 47 |
+
which defines the cumulative product of (1-beta) over time from t = [0,1].
|
| 48 |
+
:param num_diffusion_timesteps: the number of betas to produce.
|
| 49 |
+
:param alpha_bar: a lambda that takes an argument t from 0 to 1 and
|
| 50 |
+
produces the cumulative product of (1-beta) up to that
|
| 51 |
+
part of the diffusion process.
|
| 52 |
+
:param max_beta: the maximum beta to use; use values lower than 1 to
|
| 53 |
+
prevent singularities.
|
| 54 |
+
"""
|
| 55 |
+
betas = []
|
| 56 |
+
for i in range(num_diffusion_timesteps):
|
| 57 |
+
t1 = i / num_diffusion_timesteps
|
| 58 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
| 59 |
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
| 60 |
+
return np.array(betas)
|
| 61 |
+
|
| 62 |
+
class GaussianMultinomialDiffusion(torch.nn.Module):
|
| 63 |
+
def __init__(
|
| 64 |
+
self,
|
| 65 |
+
num_classes: np.array,
|
| 66 |
+
num_numerical_features: int,
|
| 67 |
+
denoise_fn,
|
| 68 |
+
num_timesteps=1000,
|
| 69 |
+
gaussian_loss_type='mse',
|
| 70 |
+
gaussian_parametrization='eps',
|
| 71 |
+
multinomial_loss_type='vb_stochastic',
|
| 72 |
+
parametrization='x0',
|
| 73 |
+
scheduler='cosine',
|
| 74 |
+
device=torch.device('cpu')
|
| 75 |
+
):
|
| 76 |
+
|
| 77 |
+
super(GaussianMultinomialDiffusion, self).__init__()
|
| 78 |
+
assert multinomial_loss_type in ('vb_stochastic', 'vb_all')
|
| 79 |
+
assert parametrization in ('x0', 'direct')
|
| 80 |
+
|
| 81 |
+
if multinomial_loss_type == 'vb_all':
|
| 82 |
+
print('Computing the loss using the bound on _all_ timesteps.'
|
| 83 |
+
' This is expensive both in terms of memory and computation.')
|
| 84 |
+
|
| 85 |
+
self.num_numerical_features = num_numerical_features
|
| 86 |
+
self.num_classes = num_classes # it as a vector [K1, K2, ..., Km]
|
| 87 |
+
self.num_classes_expanded = torch.from_numpy(
|
| 88 |
+
np.concatenate([num_classes[i].repeat(num_classes[i]) for i in range(len(num_classes))])
|
| 89 |
+
).to(device)
|
| 90 |
+
|
| 91 |
+
self.slices_for_classes = [np.arange(self.num_classes[0])]
|
| 92 |
+
offsets = np.cumsum(self.num_classes)
|
| 93 |
+
for i in range(1, len(offsets)):
|
| 94 |
+
self.slices_for_classes.append(np.arange(offsets[i - 1], offsets[i]))
|
| 95 |
+
self.offsets = torch.from_numpy(np.append([0], offsets)).to(device)
|
| 96 |
+
|
| 97 |
+
self._denoise_fn = denoise_fn
|
| 98 |
+
self.gaussian_loss_type = gaussian_loss_type
|
| 99 |
+
self.gaussian_parametrization = gaussian_parametrization
|
| 100 |
+
self.multinomial_loss_type = multinomial_loss_type
|
| 101 |
+
self.num_timesteps = num_timesteps
|
| 102 |
+
self.parametrization = parametrization
|
| 103 |
+
self.scheduler = scheduler
|
| 104 |
+
|
| 105 |
+
alphas = 1. - get_named_beta_schedule(scheduler, num_timesteps)
|
| 106 |
+
alphas = torch.tensor(alphas.astype('float64'))
|
| 107 |
+
betas = 1. - alphas
|
| 108 |
+
|
| 109 |
+
log_alpha = np.log(alphas)
|
| 110 |
+
log_cumprod_alpha = np.cumsum(log_alpha)
|
| 111 |
+
|
| 112 |
+
log_1_min_alpha = log_1_min_a(log_alpha)
|
| 113 |
+
log_1_min_cumprod_alpha = log_1_min_a(log_cumprod_alpha)
|
| 114 |
+
|
| 115 |
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
| 116 |
+
alphas_cumprod_prev = torch.tensor(np.append(1.0, alphas_cumprod[:-1]))
|
| 117 |
+
alphas_cumprod_next = torch.tensor(np.append(alphas_cumprod[1:], 0.0))
|
| 118 |
+
sqrt_alphas_cumprod = np.sqrt(alphas_cumprod)
|
| 119 |
+
sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - alphas_cumprod)
|
| 120 |
+
sqrt_recip_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod)
|
| 121 |
+
sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod - 1)
|
| 122 |
+
|
| 123 |
+
# Gaussian diffusion
|
| 124 |
+
|
| 125 |
+
self.posterior_variance = (
|
| 126 |
+
betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod)
|
| 127 |
+
)
|
| 128 |
+
self.posterior_log_variance_clipped = torch.from_numpy(
|
| 129 |
+
np.log(np.append(self.posterior_variance[1], self.posterior_variance[1:]))
|
| 130 |
+
).float().to(device)
|
| 131 |
+
self.posterior_mean_coef1 = (
|
| 132 |
+
betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod)
|
| 133 |
+
).float().to(device)
|
| 134 |
+
self.posterior_mean_coef2 = (
|
| 135 |
+
(1.0 - alphas_cumprod_prev)
|
| 136 |
+
* np.sqrt(alphas.numpy())
|
| 137 |
+
/ (1.0 - alphas_cumprod)
|
| 138 |
+
).float().to(device)
|
| 139 |
+
|
| 140 |
+
assert log_add_exp(log_alpha, log_1_min_alpha).abs().sum().item() < 1.e-5
|
| 141 |
+
assert log_add_exp(log_cumprod_alpha, log_1_min_cumprod_alpha).abs().sum().item() < 1e-5
|
| 142 |
+
assert (np.cumsum(log_alpha) - log_cumprod_alpha).abs().sum().item() < 1.e-5
|
| 143 |
+
|
| 144 |
+
# Convert to float32 and register buffers.
|
| 145 |
+
self.register_buffer('alphas', alphas.float().to(device))
|
| 146 |
+
self.register_buffer('log_alpha', log_alpha.float().to(device))
|
| 147 |
+
self.register_buffer('log_1_min_alpha', log_1_min_alpha.float().to(device))
|
| 148 |
+
self.register_buffer('log_1_min_cumprod_alpha', log_1_min_cumprod_alpha.float().to(device))
|
| 149 |
+
self.register_buffer('log_cumprod_alpha', log_cumprod_alpha.float().to(device))
|
| 150 |
+
self.register_buffer('alphas_cumprod', alphas_cumprod.float().to(device))
|
| 151 |
+
self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev.float().to(device))
|
| 152 |
+
self.register_buffer('alphas_cumprod_next', alphas_cumprod_next.float().to(device))
|
| 153 |
+
self.register_buffer('sqrt_alphas_cumprod', sqrt_alphas_cumprod.float().to(device))
|
| 154 |
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', sqrt_one_minus_alphas_cumprod.float().to(device))
|
| 155 |
+
self.register_buffer('sqrt_recip_alphas_cumprod', sqrt_recip_alphas_cumprod.float().to(device))
|
| 156 |
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', sqrt_recipm1_alphas_cumprod.float().to(device))
|
| 157 |
+
|
| 158 |
+
self.register_buffer('Lt_history', torch.zeros(num_timesteps))
|
| 159 |
+
self.register_buffer('Lt_count', torch.zeros(num_timesteps))
|
| 160 |
+
|
| 161 |
+
# Gaussian part
|
| 162 |
+
def gaussian_q_mean_variance(self, x_start, t):
|
| 163 |
+
mean = (
|
| 164 |
+
extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
| 165 |
+
)
|
| 166 |
+
variance = extract(1.0 - self.alphas_cumprod, t, x_start.shape)
|
| 167 |
+
log_variance = extract(
|
| 168 |
+
self.log_1_min_cumprod_alpha, t, x_start.shape
|
| 169 |
+
)
|
| 170 |
+
return mean, variance, log_variance
|
| 171 |
+
|
| 172 |
+
def gaussian_q_sample(self, x_start, t, noise=None):
|
| 173 |
+
if noise is None:
|
| 174 |
+
noise = torch.randn_like(x_start)
|
| 175 |
+
assert noise.shape == x_start.shape
|
| 176 |
+
return (
|
| 177 |
+
extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start
|
| 178 |
+
+ extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape)
|
| 179 |
+
* noise
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
def gaussian_q_posterior_mean_variance(self, x_start, x_t, t):
|
| 183 |
+
assert x_start.shape == x_t.shape
|
| 184 |
+
posterior_mean = (
|
| 185 |
+
extract(self.posterior_mean_coef1, t, x_t.shape) * x_start
|
| 186 |
+
+ extract(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
| 187 |
+
)
|
| 188 |
+
posterior_variance = extract(self.posterior_variance, t, x_t.shape)
|
| 189 |
+
posterior_log_variance_clipped = extract(
|
| 190 |
+
self.posterior_log_variance_clipped, t, x_t.shape
|
| 191 |
+
)
|
| 192 |
+
assert (
|
| 193 |
+
posterior_mean.shape[0]
|
| 194 |
+
== posterior_variance.shape[0]
|
| 195 |
+
== posterior_log_variance_clipped.shape[0]
|
| 196 |
+
== x_start.shape[0]
|
| 197 |
+
)
|
| 198 |
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
| 199 |
+
|
| 200 |
+
def gaussian_p_mean_variance(
|
| 201 |
+
self, model_output, x, t, clip_denoised=False, denoised_fn=None, model_kwargs=None
|
| 202 |
+
):
|
| 203 |
+
if model_kwargs is None:
|
| 204 |
+
model_kwargs = {}
|
| 205 |
+
|
| 206 |
+
B, C = x.shape[:2]
|
| 207 |
+
assert t.shape == (B,)
|
| 208 |
+
|
| 209 |
+
model_variance = torch.cat([self.posterior_variance[1].unsqueeze(0).to(x.device), (1. - self.alphas)[1:]], dim=0)
|
| 210 |
+
# model_variance = self.posterior_variance.to(x.device)
|
| 211 |
+
model_log_variance = torch.log(model_variance)
|
| 212 |
+
|
| 213 |
+
model_variance = extract(model_variance, t, x.shape)
|
| 214 |
+
model_log_variance = extract(model_log_variance, t, x.shape)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
if self.gaussian_parametrization == 'eps':
|
| 218 |
+
pred_xstart = self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)
|
| 219 |
+
elif self.gaussian_parametrization == 'x0':
|
| 220 |
+
pred_xstart = model_output
|
| 221 |
+
else:
|
| 222 |
+
raise NotImplementedError
|
| 223 |
+
|
| 224 |
+
model_mean, _, _ = self.gaussian_q_posterior_mean_variance(
|
| 225 |
+
x_start=pred_xstart, x_t=x, t=t
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
assert (
|
| 229 |
+
model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape
|
| 230 |
+
), f'{model_mean.shape}, {model_log_variance.shape}, {pred_xstart.shape}, {x.shape}'
|
| 231 |
+
|
| 232 |
+
return {
|
| 233 |
+
"mean": model_mean,
|
| 234 |
+
"variance": model_variance,
|
| 235 |
+
"log_variance": model_log_variance,
|
| 236 |
+
"pred_xstart": pred_xstart,
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
def _vb_terms_bpd(
|
| 240 |
+
self, model_output, x_start, x_t, t, clip_denoised=False, model_kwargs=None
|
| 241 |
+
):
|
| 242 |
+
true_mean, _, true_log_variance_clipped = self.gaussian_q_posterior_mean_variance(
|
| 243 |
+
x_start=x_start, x_t=x_t, t=t
|
| 244 |
+
)
|
| 245 |
+
out = self.gaussian_p_mean_variance(
|
| 246 |
+
model_output, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs
|
| 247 |
+
)
|
| 248 |
+
kl = normal_kl(
|
| 249 |
+
true_mean, true_log_variance_clipped, out["mean"], out["log_variance"]
|
| 250 |
+
)
|
| 251 |
+
kl = mean_flat(kl) / np.log(2.0)
|
| 252 |
+
|
| 253 |
+
decoder_nll = -discretized_gaussian_log_likelihood(
|
| 254 |
+
x_start, means=out["mean"], log_scales=0.5 * out["log_variance"]
|
| 255 |
+
)
|
| 256 |
+
assert decoder_nll.shape == x_start.shape
|
| 257 |
+
decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
|
| 258 |
+
|
| 259 |
+
# At the first timestep return the decoder NLL,
|
| 260 |
+
# otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
|
| 261 |
+
output = torch.where((t == 0), decoder_nll, kl)
|
| 262 |
+
return {"output": output, "pred_xstart": out["pred_xstart"], "out_mean": out["mean"], "true_mean": true_mean}
|
| 263 |
+
|
| 264 |
+
def _prior_gaussian(self, x_start):
|
| 265 |
+
"""
|
| 266 |
+
Get the prior KL term for the variational lower-bound, measured in
|
| 267 |
+
bits-per-dim.
|
| 268 |
+
|
| 269 |
+
This term can't be optimized, as it only depends on the encoder.
|
| 270 |
+
|
| 271 |
+
:param x_start: the [N x C x ...] tensor of inputs.
|
| 272 |
+
:return: a batch of [N] KL values (in bits), one per batch element.
|
| 273 |
+
"""
|
| 274 |
+
batch_size = x_start.shape[0]
|
| 275 |
+
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
|
| 276 |
+
qt_mean, _, qt_log_variance = self.gaussian_q_mean_variance(x_start, t)
|
| 277 |
+
kl_prior = normal_kl(
|
| 278 |
+
mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0
|
| 279 |
+
)
|
| 280 |
+
return mean_flat(kl_prior) / np.log(2.0)
|
| 281 |
+
|
| 282 |
+
def _gaussian_loss(self, model_out, x_start, x_t, t, noise, model_kwargs=None):
|
| 283 |
+
if model_kwargs is None:
|
| 284 |
+
model_kwargs = {}
|
| 285 |
+
|
| 286 |
+
terms = {}
|
| 287 |
+
if self.gaussian_loss_type == 'mse':
|
| 288 |
+
terms["loss"] = mean_flat((noise - model_out) ** 2)
|
| 289 |
+
elif self.gaussian_loss_type == 'kl':
|
| 290 |
+
terms["loss"] = self._vb_terms_bpd(
|
| 291 |
+
model_output=model_out,
|
| 292 |
+
x_start=x_start,
|
| 293 |
+
x_t=x_t,
|
| 294 |
+
t=t,
|
| 295 |
+
clip_denoised=False,
|
| 296 |
+
model_kwargs=model_kwargs,
|
| 297 |
+
)["output"]
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
return terms['loss']
|
| 301 |
+
|
| 302 |
+
def _predict_xstart_from_eps(self, x_t, t, eps):
|
| 303 |
+
assert x_t.shape == eps.shape
|
| 304 |
+
return (
|
| 305 |
+
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
|
| 306 |
+
- extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
| 310 |
+
return (
|
| 311 |
+
extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t
|
| 312 |
+
- pred_xstart
|
| 313 |
+
) / extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
| 314 |
+
|
| 315 |
+
def gaussian_p_sample(
|
| 316 |
+
self,
|
| 317 |
+
model_out,
|
| 318 |
+
x,
|
| 319 |
+
t,
|
| 320 |
+
clip_denoised=False,
|
| 321 |
+
denoised_fn=None,
|
| 322 |
+
model_kwargs=None,
|
| 323 |
+
):
|
| 324 |
+
out = self.gaussian_p_mean_variance(
|
| 325 |
+
model_out,
|
| 326 |
+
x,
|
| 327 |
+
t,
|
| 328 |
+
clip_denoised=clip_denoised,
|
| 329 |
+
denoised_fn=denoised_fn,
|
| 330 |
+
model_kwargs=model_kwargs,
|
| 331 |
+
)
|
| 332 |
+
noise = torch.randn_like(x)
|
| 333 |
+
nonzero_mask = (
|
| 334 |
+
(t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
|
| 335 |
+
) # no noise when t == 0
|
| 336 |
+
|
| 337 |
+
sample = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * noise
|
| 338 |
+
return {"sample": sample, "pred_xstart": out["pred_xstart"]}
|
| 339 |
+
|
| 340 |
+
# Multinomial part
|
| 341 |
+
|
| 342 |
+
def multinomial_kl(self, log_prob1, log_prob2):
|
| 343 |
+
kl = (log_prob1.exp() * (log_prob1 - log_prob2)).sum(dim=1)
|
| 344 |
+
return kl
|
| 345 |
+
|
| 346 |
+
def q_pred_one_timestep(self, log_x_t, t):
|
| 347 |
+
log_alpha_t = extract(self.log_alpha, t, log_x_t.shape)
|
| 348 |
+
log_1_min_alpha_t = extract(self.log_1_min_alpha, t, log_x_t.shape)
|
| 349 |
+
|
| 350 |
+
# alpha_t * E[xt] + (1 - alpha_t) 1 / K
|
| 351 |
+
log_probs = log_add_exp(
|
| 352 |
+
log_x_t + log_alpha_t,
|
| 353 |
+
log_1_min_alpha_t - torch.log(self.num_classes_expanded)
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
return log_probs
|
| 357 |
+
|
| 358 |
+
def q_pred(self, log_x_start, t):
|
| 359 |
+
log_cumprod_alpha_t = extract(self.log_cumprod_alpha, t, log_x_start.shape)
|
| 360 |
+
log_1_min_cumprod_alpha = extract(self.log_1_min_cumprod_alpha, t, log_x_start.shape)
|
| 361 |
+
|
| 362 |
+
log_probs = log_add_exp(
|
| 363 |
+
log_x_start + log_cumprod_alpha_t,
|
| 364 |
+
log_1_min_cumprod_alpha - torch.log(self.num_classes_expanded)
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
return log_probs
|
| 368 |
+
|
| 369 |
+
def predict_start(self, model_out, log_x_t, t, out_dict):
|
| 370 |
+
|
| 371 |
+
# model_out = self._denoise_fn(x_t, t.to(x_t.device), **out_dict)
|
| 372 |
+
|
| 373 |
+
assert model_out.size(0) == log_x_t.size(0)
|
| 374 |
+
assert model_out.size(1) == self.num_classes.sum(), f'{model_out.size()}'
|
| 375 |
+
|
| 376 |
+
log_pred = torch.empty_like(model_out)
|
| 377 |
+
for ix in self.slices_for_classes:
|
| 378 |
+
log_pred[:, ix] = F.log_softmax(model_out[:, ix], dim=1)
|
| 379 |
+
return log_pred
|
| 380 |
+
|
| 381 |
+
def q_posterior(self, log_x_start, log_x_t, t):
|
| 382 |
+
# q(xt-1 | xt, x0) = q(xt | xt-1, x0) * q(xt-1 | x0) / q(xt | x0)
|
| 383 |
+
# where q(xt | xt-1, x0) = q(xt | xt-1).
|
| 384 |
+
|
| 385 |
+
# EV_log_qxt_x0 = self.q_pred(log_x_start, t)
|
| 386 |
+
|
| 387 |
+
# print('sum exp', EV_log_qxt_x0.exp().sum(1).mean())
|
| 388 |
+
# assert False
|
| 389 |
+
|
| 390 |
+
# log_qxt_x0 = (log_x_t.exp() * EV_log_qxt_x0).sum(dim=1)
|
| 391 |
+
t_minus_1 = t - 1
|
| 392 |
+
# Remove negative values, will not be used anyway for final decoder
|
| 393 |
+
t_minus_1 = torch.where(t_minus_1 < 0, torch.zeros_like(t_minus_1), t_minus_1)
|
| 394 |
+
log_EV_qxtmin_x0 = self.q_pred(log_x_start, t_minus_1)
|
| 395 |
+
|
| 396 |
+
num_axes = (1,) * (len(log_x_start.size()) - 1)
|
| 397 |
+
t_broadcast = t.to(log_x_start.device).view(-1, *num_axes) * torch.ones_like(log_x_start)
|
| 398 |
+
log_EV_qxtmin_x0 = torch.where(t_broadcast == 0, log_x_start, log_EV_qxtmin_x0.to(torch.float32))
|
| 399 |
+
|
| 400 |
+
# unnormed_logprobs = log_EV_qxtmin_x0 +
|
| 401 |
+
# log q_pred_one_timestep(x_t, t)
|
| 402 |
+
# Note: _NOT_ x_tmin1, which is how the formula is typically used!!!
|
| 403 |
+
# Not very easy to see why this is true. But it is :)
|
| 404 |
+
unnormed_logprobs = log_EV_qxtmin_x0 + self.q_pred_one_timestep(log_x_t, t)
|
| 405 |
+
|
| 406 |
+
log_EV_xtmin_given_xt_given_xstart = \
|
| 407 |
+
unnormed_logprobs \
|
| 408 |
+
- sliced_logsumexp(unnormed_logprobs, self.offsets)
|
| 409 |
+
|
| 410 |
+
return log_EV_xtmin_given_xt_given_xstart
|
| 411 |
+
|
| 412 |
+
def p_pred(self, model_out, log_x, t, out_dict):
|
| 413 |
+
if self.parametrization == 'x0':
|
| 414 |
+
log_x_recon = self.predict_start(model_out, log_x, t=t, out_dict=out_dict)
|
| 415 |
+
log_model_pred = self.q_posterior(
|
| 416 |
+
log_x_start=log_x_recon, log_x_t=log_x, t=t)
|
| 417 |
+
elif self.parametrization == 'direct':
|
| 418 |
+
log_model_pred = self.predict_start(model_out, log_x, t=t, out_dict=out_dict)
|
| 419 |
+
else:
|
| 420 |
+
raise ValueError
|
| 421 |
+
return log_model_pred
|
| 422 |
+
|
| 423 |
+
@torch.no_grad()
|
| 424 |
+
def p_sample(self, model_out, log_x, t, out_dict):
|
| 425 |
+
model_log_prob = self.p_pred(model_out, log_x=log_x, t=t, out_dict=out_dict)
|
| 426 |
+
out = self.log_sample_categorical(model_log_prob)
|
| 427 |
+
return out
|
| 428 |
+
|
| 429 |
+
@torch.no_grad()
|
| 430 |
+
def p_sample_loop(self, shape, out_dict):
|
| 431 |
+
device = self.log_alpha.device
|
| 432 |
+
|
| 433 |
+
b = shape[0]
|
| 434 |
+
# start with random normal image.
|
| 435 |
+
img = torch.randn(shape, device=device)
|
| 436 |
+
|
| 437 |
+
for i in reversed(range(1, self.num_timesteps)):
|
| 438 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), out_dict)
|
| 439 |
+
return img
|
| 440 |
+
|
| 441 |
+
@torch.no_grad()
|
| 442 |
+
def _sample(self, image_size, out_dict, batch_size = 16):
|
| 443 |
+
return self.p_sample_loop((batch_size, 3, image_size, image_size), out_dict)
|
| 444 |
+
|
| 445 |
+
@torch.no_grad()
|
| 446 |
+
def interpolate(self, x1, x2, t = None, lam = 0.5):
|
| 447 |
+
b, *_, device = *x1.shape, x1.device
|
| 448 |
+
t = default(t, self.num_timesteps - 1)
|
| 449 |
+
|
| 450 |
+
assert x1.shape == x2.shape
|
| 451 |
+
|
| 452 |
+
t_batched = torch.stack([torch.tensor(t, device=device)] * b)
|
| 453 |
+
xt1, xt2 = map(lambda x: self.q_sample(x, t=t_batched), (x1, x2))
|
| 454 |
+
|
| 455 |
+
img = (1 - lam) * xt1 + lam * xt2
|
| 456 |
+
for i in reversed(range(0, t)):
|
| 457 |
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long))
|
| 458 |
+
|
| 459 |
+
return img
|
| 460 |
+
|
| 461 |
+
def log_sample_categorical(self, logits):
|
| 462 |
+
full_sample = []
|
| 463 |
+
for i in range(len(self.num_classes)):
|
| 464 |
+
one_class_logits = logits[:, self.slices_for_classes[i]]
|
| 465 |
+
uniform = torch.rand_like(one_class_logits)
|
| 466 |
+
gumbel_noise = -torch.log(-torch.log(uniform + 1e-30) + 1e-30)
|
| 467 |
+
sample = (gumbel_noise + one_class_logits).argmax(dim=1)
|
| 468 |
+
full_sample.append(sample.unsqueeze(1))
|
| 469 |
+
full_sample = torch.cat(full_sample, dim=1)
|
| 470 |
+
log_sample = index_to_log_onehot(full_sample, self.num_classes)
|
| 471 |
+
return log_sample
|
| 472 |
+
|
| 473 |
+
def q_sample(self, log_x_start, t):
|
| 474 |
+
log_EV_qxt_x0 = self.q_pred(log_x_start, t)
|
| 475 |
+
|
| 476 |
+
log_sample = self.log_sample_categorical(log_EV_qxt_x0)
|
| 477 |
+
|
| 478 |
+
return log_sample
|
| 479 |
+
|
| 480 |
+
def nll(self, log_x_start, out_dict):
|
| 481 |
+
b = log_x_start.size(0)
|
| 482 |
+
device = log_x_start.device
|
| 483 |
+
loss = 0
|
| 484 |
+
for t in range(0, self.num_timesteps):
|
| 485 |
+
t_array = (torch.ones(b, device=device) * t).long()
|
| 486 |
+
|
| 487 |
+
kl = self.compute_Lt(
|
| 488 |
+
log_x_start=log_x_start,
|
| 489 |
+
log_x_t=self.q_sample(log_x_start=log_x_start, t=t_array),
|
| 490 |
+
t=t_array,
|
| 491 |
+
out_dict=out_dict)
|
| 492 |
+
|
| 493 |
+
loss += kl
|
| 494 |
+
|
| 495 |
+
loss += self.kl_prior(log_x_start)
|
| 496 |
+
|
| 497 |
+
return loss
|
| 498 |
+
|
| 499 |
+
def kl_prior(self, log_x_start):
|
| 500 |
+
b = log_x_start.size(0)
|
| 501 |
+
device = log_x_start.device
|
| 502 |
+
ones = torch.ones(b, device=device).long()
|
| 503 |
+
|
| 504 |
+
log_qxT_prob = self.q_pred(log_x_start, t=(self.num_timesteps - 1) * ones)
|
| 505 |
+
log_half_prob = -torch.log(self.num_classes_expanded * torch.ones_like(log_qxT_prob))
|
| 506 |
+
|
| 507 |
+
kl_prior = self.multinomial_kl(log_qxT_prob, log_half_prob)
|
| 508 |
+
return sum_except_batch(kl_prior)
|
| 509 |
+
|
| 510 |
+
def compute_Lt(self, model_out, log_x_start, log_x_t, t, out_dict, detach_mean=False):
|
| 511 |
+
log_true_prob = self.q_posterior(
|
| 512 |
+
log_x_start=log_x_start, log_x_t=log_x_t, t=t)
|
| 513 |
+
log_model_prob = self.p_pred(model_out, log_x=log_x_t, t=t, out_dict=out_dict)
|
| 514 |
+
|
| 515 |
+
if detach_mean:
|
| 516 |
+
log_model_prob = log_model_prob.detach()
|
| 517 |
+
|
| 518 |
+
kl = self.multinomial_kl(log_true_prob, log_model_prob)
|
| 519 |
+
kl = sum_except_batch(kl)
|
| 520 |
+
|
| 521 |
+
decoder_nll = -log_categorical(log_x_start, log_model_prob)
|
| 522 |
+
decoder_nll = sum_except_batch(decoder_nll)
|
| 523 |
+
|
| 524 |
+
mask = (t == torch.zeros_like(t)).float()
|
| 525 |
+
loss = mask * decoder_nll + (1. - mask) * kl
|
| 526 |
+
|
| 527 |
+
return loss
|
| 528 |
+
|
| 529 |
+
def sample_time(self, b, device, method='uniform'):
|
| 530 |
+
if method == 'importance':
|
| 531 |
+
if not (self.Lt_count > 10).all():
|
| 532 |
+
return self.sample_time(b, device, method='uniform')
|
| 533 |
+
|
| 534 |
+
Lt_sqrt = torch.sqrt(self.Lt_history + 1e-10) + 0.0001
|
| 535 |
+
Lt_sqrt[0] = Lt_sqrt[1] # Overwrite decoder term with L1.
|
| 536 |
+
pt_all = (Lt_sqrt / Lt_sqrt.sum()).to(device)
|
| 537 |
+
|
| 538 |
+
t = torch.multinomial(pt_all, num_samples=b, replacement=True).to(device)
|
| 539 |
+
|
| 540 |
+
pt = pt_all.gather(dim=0, index=t)
|
| 541 |
+
|
| 542 |
+
return t, pt
|
| 543 |
+
|
| 544 |
+
elif method == 'uniform':
|
| 545 |
+
t = torch.randint(0, self.num_timesteps, (b,), device=device).long()
|
| 546 |
+
|
| 547 |
+
pt = torch.ones_like(t).float() / self.num_timesteps
|
| 548 |
+
return t, pt
|
| 549 |
+
else:
|
| 550 |
+
raise ValueError
|
| 551 |
+
|
| 552 |
+
def _multinomial_loss(self, model_out, log_x_start, log_x_t, t, pt, out_dict):
|
| 553 |
+
|
| 554 |
+
if self.multinomial_loss_type == 'vb_stochastic':
|
| 555 |
+
kl = self.compute_Lt(
|
| 556 |
+
model_out, log_x_start, log_x_t, t, out_dict
|
| 557 |
+
)
|
| 558 |
+
kl_prior = self.kl_prior(log_x_start)
|
| 559 |
+
# Upweigh loss term of the kl
|
| 560 |
+
vb_loss = kl / pt + kl_prior
|
| 561 |
+
|
| 562 |
+
return vb_loss
|
| 563 |
+
|
| 564 |
+
elif self.multinomial_loss_type == 'vb_all':
|
| 565 |
+
# Expensive, dont do it ;).
|
| 566 |
+
# DEPRECATED
|
| 567 |
+
return -self.nll(log_x_start)
|
| 568 |
+
else:
|
| 569 |
+
raise ValueError()
|
| 570 |
+
|
| 571 |
+
def log_prob(self, x, out_dict):
|
| 572 |
+
b, device = x.size(0), x.device
|
| 573 |
+
if self.training:
|
| 574 |
+
return self._multinomial_loss(x, out_dict)
|
| 575 |
+
|
| 576 |
+
else:
|
| 577 |
+
log_x_start = index_to_log_onehot(x, self.num_classes)
|
| 578 |
+
|
| 579 |
+
t, pt = self.sample_time(b, device, 'importance')
|
| 580 |
+
|
| 581 |
+
kl = self.compute_Lt(
|
| 582 |
+
log_x_start, self.q_sample(log_x_start=log_x_start, t=t), t, out_dict)
|
| 583 |
+
|
| 584 |
+
kl_prior = self.kl_prior(log_x_start)
|
| 585 |
+
|
| 586 |
+
# Upweigh loss term of the kl
|
| 587 |
+
loss = kl / pt + kl_prior
|
| 588 |
+
|
| 589 |
+
return -loss
|
| 590 |
+
|
| 591 |
+
def mixed_loss(self, x, out_dict):
|
| 592 |
+
b = x.shape[0]
|
| 593 |
+
device = x.device
|
| 594 |
+
t, pt = self.sample_time(b, device, 'uniform')
|
| 595 |
+
|
| 596 |
+
x_num = x[:, :self.num_numerical_features]
|
| 597 |
+
x_cat = x[:, self.num_numerical_features:]
|
| 598 |
+
|
| 599 |
+
x_num_t = x_num
|
| 600 |
+
log_x_cat_t = x_cat
|
| 601 |
+
if x_num.shape[1] > 0:
|
| 602 |
+
noise = torch.randn_like(x_num)
|
| 603 |
+
x_num_t = self.gaussian_q_sample(x_num, t, noise=noise)
|
| 604 |
+
if x_cat.shape[1] > 0:
|
| 605 |
+
log_x_cat = index_to_log_onehot(x_cat.long(), self.num_classes)
|
| 606 |
+
log_x_cat_t = self.q_sample(log_x_start=log_x_cat, t=t)
|
| 607 |
+
|
| 608 |
+
x_in = torch.cat([x_num_t, log_x_cat_t], dim=1)
|
| 609 |
+
|
| 610 |
+
model_out = self._denoise_fn(
|
| 611 |
+
x_in,
|
| 612 |
+
t,
|
| 613 |
+
**out_dict
|
| 614 |
+
)
|
| 615 |
+
|
| 616 |
+
model_out_num = model_out[:, :self.num_numerical_features]
|
| 617 |
+
model_out_cat = model_out[:, self.num_numerical_features:]
|
| 618 |
+
|
| 619 |
+
loss_multi = torch.zeros((1,)).float()
|
| 620 |
+
loss_gauss = torch.zeros((1,)).float()
|
| 621 |
+
if x_cat.shape[1] > 0:
|
| 622 |
+
loss_multi = self._multinomial_loss(model_out_cat, log_x_cat, log_x_cat_t, t, pt, out_dict) / len(self.num_classes)
|
| 623 |
+
|
| 624 |
+
if x_num.shape[1] > 0:
|
| 625 |
+
loss_gauss = self._gaussian_loss(model_out_num, x_num, x_num_t, t, noise)
|
| 626 |
+
|
| 627 |
+
# loss_multi = torch.where(out_dict['y'] == 1, loss_multi, 2 * loss_multi)
|
| 628 |
+
# loss_gauss = torch.where(out_dict['y'] == 1, loss_gauss, 2 * loss_gauss)
|
| 629 |
+
|
| 630 |
+
return loss_multi.mean(), loss_gauss.mean()
|
| 631 |
+
|
| 632 |
+
@torch.no_grad()
|
| 633 |
+
def mixed_elbo(self, x0, out_dict):
|
| 634 |
+
b = x0.size(0)
|
| 635 |
+
device = x0.device
|
| 636 |
+
|
| 637 |
+
x_num = x0[:, :self.num_numerical_features]
|
| 638 |
+
x_cat = x0[:, self.num_numerical_features:]
|
| 639 |
+
has_cat = x_cat.shape[1] > 0
|
| 640 |
+
if has_cat:
|
| 641 |
+
log_x_cat = index_to_log_onehot(x_cat.long(), self.num_classes).to(device)
|
| 642 |
+
|
| 643 |
+
gaussian_loss = []
|
| 644 |
+
xstart_mse = []
|
| 645 |
+
mse = []
|
| 646 |
+
mu_mse = []
|
| 647 |
+
out_mean = []
|
| 648 |
+
true_mean = []
|
| 649 |
+
multinomial_loss = []
|
| 650 |
+
for t in range(self.num_timesteps):
|
| 651 |
+
t_array = (torch.ones(b, device=device) * t).long()
|
| 652 |
+
noise = torch.randn_like(x_num)
|
| 653 |
+
|
| 654 |
+
x_num_t = self.gaussian_q_sample(x_start=x_num, t=t_array, noise=noise)
|
| 655 |
+
if has_cat:
|
| 656 |
+
log_x_cat_t = self.q_sample(log_x_start=log_x_cat, t=t_array)
|
| 657 |
+
else:
|
| 658 |
+
log_x_cat_t = x_cat
|
| 659 |
+
|
| 660 |
+
model_out = self._denoise_fn(
|
| 661 |
+
torch.cat([x_num_t, log_x_cat_t], dim=1),
|
| 662 |
+
t_array,
|
| 663 |
+
**out_dict
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
model_out_num = model_out[:, :self.num_numerical_features]
|
| 667 |
+
model_out_cat = model_out[:, self.num_numerical_features:]
|
| 668 |
+
|
| 669 |
+
kl = torch.tensor([0.0])
|
| 670 |
+
if has_cat:
|
| 671 |
+
kl = self.compute_Lt(
|
| 672 |
+
model_out=model_out_cat,
|
| 673 |
+
log_x_start=log_x_cat,
|
| 674 |
+
log_x_t=log_x_cat_t,
|
| 675 |
+
t=t_array,
|
| 676 |
+
out_dict=out_dict
|
| 677 |
+
)
|
| 678 |
+
|
| 679 |
+
out = self._vb_terms_bpd(
|
| 680 |
+
model_out_num,
|
| 681 |
+
x_start=x_num,
|
| 682 |
+
x_t=x_num_t,
|
| 683 |
+
t=t_array,
|
| 684 |
+
clip_denoised=False
|
| 685 |
+
)
|
| 686 |
+
|
| 687 |
+
multinomial_loss.append(kl)
|
| 688 |
+
gaussian_loss.append(out["output"])
|
| 689 |
+
xstart_mse.append(mean_flat((out["pred_xstart"] - x_num) ** 2))
|
| 690 |
+
# mu_mse.append(mean_flat(out["mean_mse"]))
|
| 691 |
+
out_mean.append(mean_flat(out["out_mean"]))
|
| 692 |
+
true_mean.append(mean_flat(out["true_mean"]))
|
| 693 |
+
|
| 694 |
+
eps = self._predict_eps_from_xstart(x_num_t, t_array, out["pred_xstart"])
|
| 695 |
+
mse.append(mean_flat((eps - noise) ** 2))
|
| 696 |
+
|
| 697 |
+
gaussian_loss = torch.stack(gaussian_loss, dim=1)
|
| 698 |
+
multinomial_loss = torch.stack(multinomial_loss, dim=1)
|
| 699 |
+
xstart_mse = torch.stack(xstart_mse, dim=1)
|
| 700 |
+
mse = torch.stack(mse, dim=1)
|
| 701 |
+
# mu_mse = torch.stack(mu_mse, dim=1)
|
| 702 |
+
out_mean = torch.stack(out_mean, dim=1)
|
| 703 |
+
true_mean = torch.stack(true_mean, dim=1)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
prior_gauss = self._prior_gaussian(x_num)
|
| 708 |
+
|
| 709 |
+
prior_multin = torch.tensor([0.0])
|
| 710 |
+
if has_cat:
|
| 711 |
+
prior_multin = self.kl_prior(log_x_cat)
|
| 712 |
+
|
| 713 |
+
total_gauss = gaussian_loss.sum(dim=1) + prior_gauss
|
| 714 |
+
total_multin = multinomial_loss.sum(dim=1) + prior_multin
|
| 715 |
+
return {
|
| 716 |
+
"total_gaussian": total_gauss,
|
| 717 |
+
"total_multinomial": total_multin,
|
| 718 |
+
"losses_gaussian": gaussian_loss,
|
| 719 |
+
"losses_multinimial": multinomial_loss,
|
| 720 |
+
"xstart_mse": xstart_mse,
|
| 721 |
+
"mse": mse,
|
| 722 |
+
# "mu_mse": mu_mse
|
| 723 |
+
"out_mean": out_mean,
|
| 724 |
+
"true_mean": true_mean
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
@torch.no_grad()
|
| 728 |
+
def gaussian_ddim_step(
|
| 729 |
+
self,
|
| 730 |
+
model_out_num,
|
| 731 |
+
x,
|
| 732 |
+
t,
|
| 733 |
+
clip_denoised=False,
|
| 734 |
+
denoised_fn=None,
|
| 735 |
+
eta=0.0
|
| 736 |
+
):
|
| 737 |
+
out = self.gaussian_p_mean_variance(
|
| 738 |
+
model_out_num,
|
| 739 |
+
x,
|
| 740 |
+
t,
|
| 741 |
+
clip_denoised=clip_denoised,
|
| 742 |
+
denoised_fn=denoised_fn,
|
| 743 |
+
model_kwargs=None,
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
|
| 747 |
+
|
| 748 |
+
alpha_bar = extract(self.alphas_cumprod, t, x.shape)
|
| 749 |
+
alpha_bar_prev = extract(self.alphas_cumprod_prev, t, x.shape)
|
| 750 |
+
sigma = (
|
| 751 |
+
eta
|
| 752 |
+
* torch.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
|
| 753 |
+
* torch.sqrt(1 - alpha_bar / alpha_bar_prev)
|
| 754 |
+
)
|
| 755 |
+
|
| 756 |
+
noise = torch.randn_like(x)
|
| 757 |
+
mean_pred = (
|
| 758 |
+
out["pred_xstart"] * torch.sqrt(alpha_bar_prev)
|
| 759 |
+
+ torch.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps
|
| 760 |
+
)
|
| 761 |
+
nonzero_mask = (
|
| 762 |
+
(t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))
|
| 763 |
+
) # no noise when t == 0
|
| 764 |
+
sample = mean_pred + nonzero_mask * sigma * noise
|
| 765 |
+
|
| 766 |
+
return sample
|
| 767 |
+
|
| 768 |
+
@torch.no_grad()
|
| 769 |
+
def gaussian_ddim_sample(
|
| 770 |
+
self,
|
| 771 |
+
noise,
|
| 772 |
+
T,
|
| 773 |
+
out_dict,
|
| 774 |
+
eta=0.0
|
| 775 |
+
):
|
| 776 |
+
x = noise
|
| 777 |
+
b = x.shape[0]
|
| 778 |
+
device = x.device
|
| 779 |
+
for t in reversed(range(T)):
|
| 780 |
+
print(f'Sample timestep {t:4d}', end='\r')
|
| 781 |
+
t_array = (torch.ones(b, device=device) * t).long()
|
| 782 |
+
out_num = self._denoise_fn(x, t_array, **out_dict)
|
| 783 |
+
x = self.gaussian_ddim_step(
|
| 784 |
+
out_num,
|
| 785 |
+
x,
|
| 786 |
+
t_array
|
| 787 |
+
)
|
| 788 |
+
print()
|
| 789 |
+
return x
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
@torch.no_grad()
|
| 793 |
+
def gaussian_ddim_reverse_step(
|
| 794 |
+
self,
|
| 795 |
+
model_out_num,
|
| 796 |
+
x,
|
| 797 |
+
t,
|
| 798 |
+
clip_denoised=False,
|
| 799 |
+
eta=0.0
|
| 800 |
+
):
|
| 801 |
+
assert eta == 0.0, "Eta must be zero."
|
| 802 |
+
out = self.gaussian_p_mean_variance(
|
| 803 |
+
model_out_num,
|
| 804 |
+
x,
|
| 805 |
+
t,
|
| 806 |
+
clip_denoised=clip_denoised,
|
| 807 |
+
denoised_fn=None,
|
| 808 |
+
model_kwargs=None,
|
| 809 |
+
)
|
| 810 |
+
|
| 811 |
+
eps = (
|
| 812 |
+
extract(self.sqrt_recip_alphas_cumprod, t, x.shape) * x
|
| 813 |
+
- out["pred_xstart"]
|
| 814 |
+
) / extract(self.sqrt_recipm1_alphas_cumprod, t, x.shape)
|
| 815 |
+
alpha_bar_next = extract(self.alphas_cumprod_next, t, x.shape)
|
| 816 |
+
|
| 817 |
+
mean_pred = (
|
| 818 |
+
out["pred_xstart"] * torch.sqrt(alpha_bar_next)
|
| 819 |
+
+ torch.sqrt(1 - alpha_bar_next) * eps
|
| 820 |
+
)
|
| 821 |
+
|
| 822 |
+
return mean_pred
|
| 823 |
+
|
| 824 |
+
@torch.no_grad()
|
| 825 |
+
def gaussian_ddim_reverse_sample(
|
| 826 |
+
self,
|
| 827 |
+
x,
|
| 828 |
+
T,
|
| 829 |
+
out_dict,
|
| 830 |
+
):
|
| 831 |
+
b = x.shape[0]
|
| 832 |
+
device = x.device
|
| 833 |
+
for t in range(T):
|
| 834 |
+
print(f'Reverse timestep {t:4d}', end='\r')
|
| 835 |
+
t_array = (torch.ones(b, device=device) * t).long()
|
| 836 |
+
out_num = self._denoise_fn(x, t_array, **out_dict)
|
| 837 |
+
x = self.gaussian_ddim_reverse_step(
|
| 838 |
+
out_num,
|
| 839 |
+
x,
|
| 840 |
+
t_array,
|
| 841 |
+
eta=0.0
|
| 842 |
+
)
|
| 843 |
+
print()
|
| 844 |
+
|
| 845 |
+
return x
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
@torch.no_grad()
|
| 849 |
+
def multinomial_ddim_step(
|
| 850 |
+
self,
|
| 851 |
+
model_out_cat,
|
| 852 |
+
log_x_t,
|
| 853 |
+
t,
|
| 854 |
+
out_dict,
|
| 855 |
+
eta=0.0
|
| 856 |
+
):
|
| 857 |
+
# not ddim, essentially
|
| 858 |
+
log_x0 = self.predict_start(model_out_cat, log_x_t=log_x_t, t=t, out_dict=out_dict)
|
| 859 |
+
|
| 860 |
+
alpha_bar = extract(self.alphas_cumprod, t, log_x_t.shape)
|
| 861 |
+
alpha_bar_prev = extract(self.alphas_cumprod_prev, t, log_x_t.shape)
|
| 862 |
+
sigma = (
|
| 863 |
+
eta
|
| 864 |
+
* torch.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))
|
| 865 |
+
* torch.sqrt(1 - alpha_bar / alpha_bar_prev)
|
| 866 |
+
)
|
| 867 |
+
|
| 868 |
+
coef1 = sigma
|
| 869 |
+
coef2 = alpha_bar_prev - sigma * alpha_bar
|
| 870 |
+
coef3 = 1 - coef1 - coef2
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
log_ps = torch.stack([
|
| 874 |
+
torch.log(coef1) + log_x_t,
|
| 875 |
+
torch.log(coef2) + log_x0,
|
| 876 |
+
torch.log(coef3) - torch.log(self.num_classes_expanded)
|
| 877 |
+
], dim=2)
|
| 878 |
+
|
| 879 |
+
log_prob = torch.logsumexp(log_ps, dim=2)
|
| 880 |
+
|
| 881 |
+
out = self.log_sample_categorical(log_prob)
|
| 882 |
+
|
| 883 |
+
return out
|
| 884 |
+
|
| 885 |
+
@torch.no_grad()
|
| 886 |
+
def sample_ddim(self, num_samples, y_dist):
|
| 887 |
+
b = num_samples
|
| 888 |
+
device = self.log_alpha.device
|
| 889 |
+
z_norm = torch.randn((b, self.num_numerical_features), device=device)
|
| 890 |
+
|
| 891 |
+
has_cat = self.num_classes[0] != 0
|
| 892 |
+
log_z = torch.zeros((b, 0), device=device).float()
|
| 893 |
+
if has_cat:
|
| 894 |
+
uniform_logits = torch.zeros((b, len(self.num_classes_expanded)), device=device)
|
| 895 |
+
log_z = self.log_sample_categorical(uniform_logits)
|
| 896 |
+
|
| 897 |
+
y = torch.multinomial(
|
| 898 |
+
y_dist,
|
| 899 |
+
num_samples=b,
|
| 900 |
+
replacement=True
|
| 901 |
+
)
|
| 902 |
+
out_dict = {'y': y.long().to(device)}
|
| 903 |
+
for i in reversed(range(0, self.num_timesteps)):
|
| 904 |
+
print(f'Sample timestep {i:4d}', end='\r')
|
| 905 |
+
t = torch.full((b,), i, device=device, dtype=torch.long)
|
| 906 |
+
model_out = self._denoise_fn(
|
| 907 |
+
torch.cat([z_norm, log_z], dim=1).float(),
|
| 908 |
+
t,
|
| 909 |
+
**out_dict
|
| 910 |
+
)
|
| 911 |
+
model_out_num = model_out[:, :self.num_numerical_features]
|
| 912 |
+
model_out_cat = model_out[:, self.num_numerical_features:]
|
| 913 |
+
z_norm = self.gaussian_ddim_step(model_out_num, z_norm, t, clip_denoised=False)
|
| 914 |
+
if has_cat:
|
| 915 |
+
log_z = self.multinomial_ddim_step(model_out_cat, log_z, t, out_dict)
|
| 916 |
+
|
| 917 |
+
print()
|
| 918 |
+
z_ohe = torch.exp(log_z).round()
|
| 919 |
+
z_cat = log_z
|
| 920 |
+
if has_cat:
|
| 921 |
+
z_cat = ohe_to_categories(z_ohe, self.num_classes)
|
| 922 |
+
sample = torch.cat([z_norm, z_cat], dim=1).cpu()
|
| 923 |
+
return sample, out_dict
|
| 924 |
+
|
| 925 |
+
|
| 926 |
+
@torch.no_grad()
|
| 927 |
+
def sample(self, num_samples, y_dist):
|
| 928 |
+
b = num_samples
|
| 929 |
+
device = self.log_alpha.device
|
| 930 |
+
z_norm = torch.randn((b, self.num_numerical_features), device=device)
|
| 931 |
+
|
| 932 |
+
has_cat = self.num_classes[0] != 0
|
| 933 |
+
log_z = torch.zeros((b, 0), device=device).float()
|
| 934 |
+
if has_cat:
|
| 935 |
+
uniform_logits = torch.zeros((b, len(self.num_classes_expanded)), device=device)
|
| 936 |
+
log_z = self.log_sample_categorical(uniform_logits)
|
| 937 |
+
|
| 938 |
+
y = torch.multinomial(
|
| 939 |
+
y_dist,
|
| 940 |
+
num_samples=b,
|
| 941 |
+
replacement=True
|
| 942 |
+
)
|
| 943 |
+
out_dict = {'y': y.long().to(device)}
|
| 944 |
+
for i in reversed(range(0, self.num_timesteps)):
|
| 945 |
+
print(f'Sample timestep {i:4d}', end='\r')
|
| 946 |
+
t = torch.full((b,), i, device=device, dtype=torch.long)
|
| 947 |
+
model_out = self._denoise_fn(
|
| 948 |
+
torch.cat([z_norm, log_z], dim=1).float(),
|
| 949 |
+
t,
|
| 950 |
+
**out_dict
|
| 951 |
+
)
|
| 952 |
+
model_out_num = model_out[:, :self.num_numerical_features]
|
| 953 |
+
model_out_cat = model_out[:, self.num_numerical_features:]
|
| 954 |
+
z_norm = self.gaussian_p_sample(model_out_num, z_norm, t, clip_denoised=False)['sample']
|
| 955 |
+
if has_cat:
|
| 956 |
+
log_z = self.p_sample(model_out_cat, log_z, t, out_dict)
|
| 957 |
+
|
| 958 |
+
print()
|
| 959 |
+
z_ohe = torch.exp(log_z).round()
|
| 960 |
+
z_cat = log_z
|
| 961 |
+
if has_cat:
|
| 962 |
+
z_cat = ohe_to_categories(z_ohe, self.num_classes)
|
| 963 |
+
sample = torch.cat([z_norm, z_cat], dim=1).cpu()
|
| 964 |
+
return sample, out_dict
|
| 965 |
+
|
| 966 |
+
def sample_all(self, num_samples, batch_size, y_dist, ddim=False):
|
| 967 |
+
if ddim:
|
| 968 |
+
print('Sample using DDIM.')
|
| 969 |
+
sample_fn = self.sample_ddim
|
| 970 |
+
else:
|
| 971 |
+
sample_fn = self.sample
|
| 972 |
+
|
| 973 |
+
b = batch_size
|
| 974 |
+
|
| 975 |
+
all_y = []
|
| 976 |
+
all_samples = []
|
| 977 |
+
num_generated = 0
|
| 978 |
+
while num_generated < num_samples:
|
| 979 |
+
sample, out_dict = sample_fn(b, y_dist)
|
| 980 |
+
mask_nan = torch.any(sample.isnan(), dim=1)
|
| 981 |
+
sample = sample[~mask_nan]
|
| 982 |
+
out_dict['y'] = out_dict['y'][~mask_nan]
|
| 983 |
+
|
| 984 |
+
all_samples.append(sample)
|
| 985 |
+
all_y.append(out_dict['y'].cpu())
|
| 986 |
+
if sample.shape[0] != b:
|
| 987 |
+
raise FoundNANsError
|
| 988 |
+
num_generated += sample.shape[0]
|
| 989 |
+
|
| 990 |
+
x_gen = torch.cat(all_samples, dim=0)[:num_samples]
|
| 991 |
+
y_gen = torch.cat(all_y, dim=0)[:num_samples]
|
| 992 |
+
|
| 993 |
+
return x_gen, y_gen
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/modules.py
ADDED
|
@@ -0,0 +1,486 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Code was adapted from https://github.com/Yura52/rtdl
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
import torch.nn.functional as F
|
| 11 |
+
import torch.optim
|
| 12 |
+
from torch import Tensor
|
| 13 |
+
|
| 14 |
+
ModuleType = Union[str, Callable[..., nn.Module]]
|
| 15 |
+
|
| 16 |
+
class SiLU(nn.Module):
|
| 17 |
+
def forward(self, x):
|
| 18 |
+
return x * torch.sigmoid(x)
|
| 19 |
+
|
| 20 |
+
def timestep_embedding(timesteps, dim, max_period=10000):
|
| 21 |
+
"""
|
| 22 |
+
Create sinusoidal timestep embeddings.
|
| 23 |
+
|
| 24 |
+
:param timesteps: a 1-D Tensor of N indices, one per batch element.
|
| 25 |
+
These may be fractional.
|
| 26 |
+
:param dim: the dimension of the output.
|
| 27 |
+
:param max_period: controls the minimum frequency of the embeddings.
|
| 28 |
+
:return: an [N x dim] Tensor of positional embeddings.
|
| 29 |
+
"""
|
| 30 |
+
half = dim // 2
|
| 31 |
+
freqs = torch.exp(
|
| 32 |
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
| 33 |
+
).to(device=timesteps.device)
|
| 34 |
+
args = timesteps[:, None].float() * freqs[None]
|
| 35 |
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
| 36 |
+
if dim % 2:
|
| 37 |
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
| 38 |
+
return embedding
|
| 39 |
+
|
| 40 |
+
def _is_glu_activation(activation: ModuleType):
|
| 41 |
+
return (
|
| 42 |
+
isinstance(activation, str)
|
| 43 |
+
and activation.endswith('GLU')
|
| 44 |
+
or activation in [ReGLU, GEGLU]
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _all_or_none(values):
|
| 49 |
+
assert all(x is None for x in values) or all(x is not None for x in values)
|
| 50 |
+
|
| 51 |
+
def reglu(x: Tensor) -> Tensor:
|
| 52 |
+
"""The ReGLU activation function from [1].
|
| 53 |
+
References:
|
| 54 |
+
[1] Noam Shazeer, "GLU Variants Improve Transformer", 2020
|
| 55 |
+
"""
|
| 56 |
+
assert x.shape[-1] % 2 == 0
|
| 57 |
+
a, b = x.chunk(2, dim=-1)
|
| 58 |
+
return a * F.relu(b)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def geglu(x: Tensor) -> Tensor:
|
| 62 |
+
"""The GEGLU activation function from [1].
|
| 63 |
+
References:
|
| 64 |
+
[1] Noam Shazeer, "GLU Variants Improve Transformer", 2020
|
| 65 |
+
"""
|
| 66 |
+
assert x.shape[-1] % 2 == 0
|
| 67 |
+
a, b = x.chunk(2, dim=-1)
|
| 68 |
+
return a * F.gelu(b)
|
| 69 |
+
|
| 70 |
+
class ReGLU(nn.Module):
|
| 71 |
+
"""The ReGLU activation function from [shazeer2020glu].
|
| 72 |
+
|
| 73 |
+
Examples:
|
| 74 |
+
.. testcode::
|
| 75 |
+
|
| 76 |
+
module = ReGLU()
|
| 77 |
+
x = torch.randn(3, 4)
|
| 78 |
+
assert module(x).shape == (3, 2)
|
| 79 |
+
|
| 80 |
+
References:
|
| 81 |
+
* [shazeer2020glu] Noam Shazeer, "GLU Variants Improve Transformer", 2020
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 85 |
+
return reglu(x)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class GEGLU(nn.Module):
|
| 89 |
+
"""The GEGLU activation function from [shazeer2020glu].
|
| 90 |
+
|
| 91 |
+
Examples:
|
| 92 |
+
.. testcode::
|
| 93 |
+
|
| 94 |
+
module = GEGLU()
|
| 95 |
+
x = torch.randn(3, 4)
|
| 96 |
+
assert module(x).shape == (3, 2)
|
| 97 |
+
|
| 98 |
+
References:
|
| 99 |
+
* [shazeer2020glu] Noam Shazeer, "GLU Variants Improve Transformer", 2020
|
| 100 |
+
"""
|
| 101 |
+
|
| 102 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 103 |
+
return geglu(x)
|
| 104 |
+
|
| 105 |
+
def _make_nn_module(module_type: ModuleType, *args) -> nn.Module:
|
| 106 |
+
return (
|
| 107 |
+
(
|
| 108 |
+
ReGLU()
|
| 109 |
+
if module_type == 'ReGLU'
|
| 110 |
+
else GEGLU()
|
| 111 |
+
if module_type == 'GEGLU'
|
| 112 |
+
else getattr(nn, module_type)(*args)
|
| 113 |
+
)
|
| 114 |
+
if isinstance(module_type, str)
|
| 115 |
+
else module_type(*args)
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class MLP(nn.Module):
|
| 120 |
+
"""The MLP model used in [gorishniy2021revisiting].
|
| 121 |
+
|
| 122 |
+
The following scheme describes the architecture:
|
| 123 |
+
|
| 124 |
+
.. code-block:: text
|
| 125 |
+
|
| 126 |
+
MLP: (in) -> Block -> ... -> Block -> Linear -> (out)
|
| 127 |
+
Block: (in) -> Linear -> Activation -> Dropout -> (out)
|
| 128 |
+
|
| 129 |
+
Examples:
|
| 130 |
+
.. testcode::
|
| 131 |
+
|
| 132 |
+
x = torch.randn(4, 2)
|
| 133 |
+
module = MLP.make_baseline(x.shape[1], [3, 5], 0.1, 1)
|
| 134 |
+
assert module(x).shape == (len(x), 1)
|
| 135 |
+
|
| 136 |
+
References:
|
| 137 |
+
* [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
class Block(nn.Module):
|
| 141 |
+
"""The main building block of `MLP`."""
|
| 142 |
+
|
| 143 |
+
def __init__(
|
| 144 |
+
self,
|
| 145 |
+
*,
|
| 146 |
+
d_in: int,
|
| 147 |
+
d_out: int,
|
| 148 |
+
bias: bool,
|
| 149 |
+
activation: ModuleType,
|
| 150 |
+
dropout: float,
|
| 151 |
+
) -> None:
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.linear = nn.Linear(d_in, d_out, bias)
|
| 154 |
+
self.activation = _make_nn_module(activation)
|
| 155 |
+
self.dropout = nn.Dropout(dropout)
|
| 156 |
+
|
| 157 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 158 |
+
return self.dropout(self.activation(self.linear(x)))
|
| 159 |
+
|
| 160 |
+
def __init__(
|
| 161 |
+
self,
|
| 162 |
+
*,
|
| 163 |
+
d_in: int,
|
| 164 |
+
d_layers: List[int],
|
| 165 |
+
dropouts: Union[float, List[float]],
|
| 166 |
+
activation: Union[str, Callable[[], nn.Module]],
|
| 167 |
+
d_out: int,
|
| 168 |
+
) -> None:
|
| 169 |
+
"""
|
| 170 |
+
Note:
|
| 171 |
+
`make_baseline` is the recommended constructor.
|
| 172 |
+
"""
|
| 173 |
+
super().__init__()
|
| 174 |
+
if isinstance(dropouts, float):
|
| 175 |
+
dropouts = [dropouts] * len(d_layers)
|
| 176 |
+
assert len(d_layers) == len(dropouts)
|
| 177 |
+
assert activation not in ['ReGLU', 'GEGLU']
|
| 178 |
+
|
| 179 |
+
self.blocks = nn.ModuleList(
|
| 180 |
+
[
|
| 181 |
+
MLP.Block(
|
| 182 |
+
d_in=d_layers[i - 1] if i else d_in,
|
| 183 |
+
d_out=d,
|
| 184 |
+
bias=True,
|
| 185 |
+
activation=activation,
|
| 186 |
+
dropout=dropout,
|
| 187 |
+
)
|
| 188 |
+
for i, (d, dropout) in enumerate(zip(d_layers, dropouts))
|
| 189 |
+
]
|
| 190 |
+
)
|
| 191 |
+
self.head = nn.Linear(d_layers[-1] if d_layers else d_in, d_out)
|
| 192 |
+
|
| 193 |
+
@classmethod
|
| 194 |
+
def make_baseline(
|
| 195 |
+
cls: Type['MLP'],
|
| 196 |
+
d_in: int,
|
| 197 |
+
d_layers: List[int],
|
| 198 |
+
dropout: float,
|
| 199 |
+
d_out: int,
|
| 200 |
+
) -> 'MLP':
|
| 201 |
+
"""Create a "baseline" `MLP`.
|
| 202 |
+
|
| 203 |
+
This variation of MLP was used in [gorishniy2021revisiting]. Features:
|
| 204 |
+
|
| 205 |
+
* :code:`Activation` = :code:`ReLU`
|
| 206 |
+
* all linear layers except for the first one and the last one are of the same dimension
|
| 207 |
+
* the dropout rate is the same for all dropout layers
|
| 208 |
+
|
| 209 |
+
Args:
|
| 210 |
+
d_in: the input size
|
| 211 |
+
d_layers: the dimensions of the linear layers. If there are more than two
|
| 212 |
+
layers, then all of them except for the first and the last ones must
|
| 213 |
+
have the same dimension. Valid examples: :code:`[]`, :code:`[8]`,
|
| 214 |
+
:code:`[8, 16]`, :code:`[2, 2, 2, 2]`, :code:`[1, 2, 2, 4]`. Invalid
|
| 215 |
+
example: :code:`[1, 2, 3, 4]`.
|
| 216 |
+
dropout: the dropout rate for all hidden layers
|
| 217 |
+
d_out: the output size
|
| 218 |
+
Returns:
|
| 219 |
+
MLP
|
| 220 |
+
|
| 221 |
+
References:
|
| 222 |
+
* [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021
|
| 223 |
+
"""
|
| 224 |
+
assert isinstance(dropout, float)
|
| 225 |
+
if len(d_layers) > 2:
|
| 226 |
+
assert len(set(d_layers[1:-1])) == 1, (
|
| 227 |
+
'if d_layers contains more than two elements, then'
|
| 228 |
+
' all elements except for the first and the last ones must be equal.'
|
| 229 |
+
)
|
| 230 |
+
return MLP(
|
| 231 |
+
d_in=d_in,
|
| 232 |
+
d_layers=d_layers, # type: ignore
|
| 233 |
+
dropouts=dropout,
|
| 234 |
+
activation='ReLU',
|
| 235 |
+
d_out=d_out,
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 239 |
+
x = x.float()
|
| 240 |
+
for block in self.blocks:
|
| 241 |
+
x = block(x)
|
| 242 |
+
x = self.head(x)
|
| 243 |
+
return x
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
class ResNet(nn.Module):
|
| 247 |
+
"""The ResNet model used in [gorishniy2021revisiting].
|
| 248 |
+
The following scheme describes the architecture:
|
| 249 |
+
.. code-block:: text
|
| 250 |
+
ResNet: (in) -> Linear -> Block -> ... -> Block -> Head -> (out)
|
| 251 |
+
|-> Norm -> Linear -> Activation -> Dropout -> Linear -> Dropout ->|
|
| 252 |
+
| |
|
| 253 |
+
Block: (in) ------------------------------------------------------------> Add -> (out)
|
| 254 |
+
Head: (in) -> Norm -> Activation -> Linear -> (out)
|
| 255 |
+
Examples:
|
| 256 |
+
.. testcode::
|
| 257 |
+
x = torch.randn(4, 2)
|
| 258 |
+
module = ResNet.make_baseline(
|
| 259 |
+
d_in=x.shape[1],
|
| 260 |
+
n_blocks=2,
|
| 261 |
+
d_main=3,
|
| 262 |
+
d_hidden=4,
|
| 263 |
+
dropout_first=0.25,
|
| 264 |
+
dropout_second=0.0,
|
| 265 |
+
d_out=1
|
| 266 |
+
)
|
| 267 |
+
assert module(x).shape == (len(x), 1)
|
| 268 |
+
References:
|
| 269 |
+
* [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021
|
| 270 |
+
"""
|
| 271 |
+
|
| 272 |
+
class Block(nn.Module):
|
| 273 |
+
"""The main building block of `ResNet`."""
|
| 274 |
+
|
| 275 |
+
def __init__(
|
| 276 |
+
self,
|
| 277 |
+
*,
|
| 278 |
+
d_main: int,
|
| 279 |
+
d_hidden: int,
|
| 280 |
+
bias_first: bool,
|
| 281 |
+
bias_second: bool,
|
| 282 |
+
dropout_first: float,
|
| 283 |
+
dropout_second: float,
|
| 284 |
+
normalization: ModuleType,
|
| 285 |
+
activation: ModuleType,
|
| 286 |
+
skip_connection: bool,
|
| 287 |
+
) -> None:
|
| 288 |
+
super().__init__()
|
| 289 |
+
self.normalization = _make_nn_module(normalization, d_main)
|
| 290 |
+
self.linear_first = nn.Linear(d_main, d_hidden, bias_first)
|
| 291 |
+
self.activation = _make_nn_module(activation)
|
| 292 |
+
self.dropout_first = nn.Dropout(dropout_first)
|
| 293 |
+
self.linear_second = nn.Linear(d_hidden, d_main, bias_second)
|
| 294 |
+
self.dropout_second = nn.Dropout(dropout_second)
|
| 295 |
+
self.skip_connection = skip_connection
|
| 296 |
+
|
| 297 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 298 |
+
x_input = x
|
| 299 |
+
x = self.normalization(x)
|
| 300 |
+
x = self.linear_first(x)
|
| 301 |
+
x = self.activation(x)
|
| 302 |
+
x = self.dropout_first(x)
|
| 303 |
+
x = self.linear_second(x)
|
| 304 |
+
x = self.dropout_second(x)
|
| 305 |
+
if self.skip_connection:
|
| 306 |
+
x = x_input + x
|
| 307 |
+
return x
|
| 308 |
+
|
| 309 |
+
class Head(nn.Module):
|
| 310 |
+
"""The final module of `ResNet`."""
|
| 311 |
+
|
| 312 |
+
def __init__(
|
| 313 |
+
self,
|
| 314 |
+
*,
|
| 315 |
+
d_in: int,
|
| 316 |
+
d_out: int,
|
| 317 |
+
bias: bool,
|
| 318 |
+
normalization: ModuleType,
|
| 319 |
+
activation: ModuleType,
|
| 320 |
+
) -> None:
|
| 321 |
+
super().__init__()
|
| 322 |
+
self.normalization = _make_nn_module(normalization, d_in)
|
| 323 |
+
self.activation = _make_nn_module(activation)
|
| 324 |
+
self.linear = nn.Linear(d_in, d_out, bias)
|
| 325 |
+
|
| 326 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 327 |
+
if self.normalization is not None:
|
| 328 |
+
x = self.normalization(x)
|
| 329 |
+
x = self.activation(x)
|
| 330 |
+
x = self.linear(x)
|
| 331 |
+
return x
|
| 332 |
+
|
| 333 |
+
def __init__(
|
| 334 |
+
self,
|
| 335 |
+
*,
|
| 336 |
+
d_in: int,
|
| 337 |
+
n_blocks: int,
|
| 338 |
+
d_main: int,
|
| 339 |
+
d_hidden: int,
|
| 340 |
+
dropout_first: float,
|
| 341 |
+
dropout_second: float,
|
| 342 |
+
normalization: ModuleType,
|
| 343 |
+
activation: ModuleType,
|
| 344 |
+
d_out: int,
|
| 345 |
+
) -> None:
|
| 346 |
+
"""
|
| 347 |
+
Note:
|
| 348 |
+
`make_baseline` is the recommended constructor.
|
| 349 |
+
"""
|
| 350 |
+
super().__init__()
|
| 351 |
+
|
| 352 |
+
self.first_layer = nn.Linear(d_in, d_main)
|
| 353 |
+
if d_main is None:
|
| 354 |
+
d_main = d_in
|
| 355 |
+
self.blocks = nn.Sequential(
|
| 356 |
+
*[
|
| 357 |
+
ResNet.Block(
|
| 358 |
+
d_main=d_main,
|
| 359 |
+
d_hidden=d_hidden,
|
| 360 |
+
bias_first=True,
|
| 361 |
+
bias_second=True,
|
| 362 |
+
dropout_first=dropout_first,
|
| 363 |
+
dropout_second=dropout_second,
|
| 364 |
+
normalization=normalization,
|
| 365 |
+
activation=activation,
|
| 366 |
+
skip_connection=True,
|
| 367 |
+
)
|
| 368 |
+
for _ in range(n_blocks)
|
| 369 |
+
]
|
| 370 |
+
)
|
| 371 |
+
self.head = ResNet.Head(
|
| 372 |
+
d_in=d_main,
|
| 373 |
+
d_out=d_out,
|
| 374 |
+
bias=True,
|
| 375 |
+
normalization=normalization,
|
| 376 |
+
activation=activation,
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
@classmethod
|
| 380 |
+
def make_baseline(
|
| 381 |
+
cls: Type['ResNet'],
|
| 382 |
+
*,
|
| 383 |
+
d_in: int,
|
| 384 |
+
n_blocks: int,
|
| 385 |
+
d_main: int,
|
| 386 |
+
d_hidden: int,
|
| 387 |
+
dropout_first: float,
|
| 388 |
+
dropout_second: float,
|
| 389 |
+
d_out: int,
|
| 390 |
+
) -> 'ResNet':
|
| 391 |
+
"""Create a "baseline" `ResNet`.
|
| 392 |
+
This variation of ResNet was used in [gorishniy2021revisiting]. Features:
|
| 393 |
+
* :code:`Activation` = :code:`ReLU`
|
| 394 |
+
* :code:`Norm` = :code:`BatchNorm1d`
|
| 395 |
+
Args:
|
| 396 |
+
d_in: the input size
|
| 397 |
+
n_blocks: the number of Blocks
|
| 398 |
+
d_main: the input size (or, equivalently, the output size) of each Block
|
| 399 |
+
d_hidden: the output size of the first linear layer in each Block
|
| 400 |
+
dropout_first: the dropout rate of the first dropout layer in each Block.
|
| 401 |
+
dropout_second: the dropout rate of the second dropout layer in each Block.
|
| 402 |
+
References:
|
| 403 |
+
* [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021
|
| 404 |
+
"""
|
| 405 |
+
return cls(
|
| 406 |
+
d_in=d_in,
|
| 407 |
+
n_blocks=n_blocks,
|
| 408 |
+
d_main=d_main,
|
| 409 |
+
d_hidden=d_hidden,
|
| 410 |
+
dropout_first=dropout_first,
|
| 411 |
+
dropout_second=dropout_second,
|
| 412 |
+
normalization='BatchNorm1d',
|
| 413 |
+
activation='ReLU',
|
| 414 |
+
d_out=d_out,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 418 |
+
x = x.float()
|
| 419 |
+
x = self.first_layer(x)
|
| 420 |
+
x = self.blocks(x)
|
| 421 |
+
x = self.head(x)
|
| 422 |
+
return x
|
| 423 |
+
#### For diffusion
|
| 424 |
+
|
| 425 |
+
class MLPDiffusion(nn.Module):
|
| 426 |
+
def __init__(self, d_in, num_classes, is_y_cond, rtdl_params, dim_t = 128):
|
| 427 |
+
super().__init__()
|
| 428 |
+
self.dim_t = dim_t
|
| 429 |
+
self.num_classes = num_classes
|
| 430 |
+
self.is_y_cond = is_y_cond
|
| 431 |
+
|
| 432 |
+
# d0 = rtdl_params['d_layers'][0]
|
| 433 |
+
|
| 434 |
+
rtdl_params['d_in'] = dim_t
|
| 435 |
+
rtdl_params['d_out'] = d_in
|
| 436 |
+
|
| 437 |
+
self.mlp = MLP.make_baseline(**rtdl_params)
|
| 438 |
+
|
| 439 |
+
if self.num_classes > 0 and is_y_cond:
|
| 440 |
+
self.label_emb = nn.Embedding(self.num_classes, dim_t)
|
| 441 |
+
elif self.num_classes == 0 and is_y_cond:
|
| 442 |
+
self.label_emb = nn.Linear(1, dim_t)
|
| 443 |
+
|
| 444 |
+
self.proj = nn.Linear(d_in, dim_t)
|
| 445 |
+
self.time_embed = nn.Sequential(
|
| 446 |
+
nn.Linear(dim_t, dim_t),
|
| 447 |
+
nn.SiLU(),
|
| 448 |
+
nn.Linear(dim_t, dim_t)
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
def forward(self, x, timesteps, y=None):
|
| 452 |
+
emb = self.time_embed(timestep_embedding(timesteps, self.dim_t))
|
| 453 |
+
if self.is_y_cond and y is not None:
|
| 454 |
+
if self.num_classes > 0:
|
| 455 |
+
y = y.squeeze()
|
| 456 |
+
else:
|
| 457 |
+
y = y.resize(y.size(0), 1).float()
|
| 458 |
+
emb += F.silu(self.label_emb(y))
|
| 459 |
+
x = self.proj(x) + emb
|
| 460 |
+
return self.mlp(x)
|
| 461 |
+
|
| 462 |
+
class ResNetDiffusion(nn.Module):
|
| 463 |
+
def __init__(self, d_in, num_classes, rtdl_params, dim_t = 256):
|
| 464 |
+
super().__init__()
|
| 465 |
+
self.dim_t = dim_t
|
| 466 |
+
self.num_classes = num_classes
|
| 467 |
+
|
| 468 |
+
rtdl_params['d_in'] = d_in
|
| 469 |
+
rtdl_params['d_out'] = d_in
|
| 470 |
+
rtdl_params['emb_d'] = dim_t
|
| 471 |
+
self.resnet = ResNet.make_baseline(**rtdl_params)
|
| 472 |
+
|
| 473 |
+
if self.num_classes > 0:
|
| 474 |
+
self.label_emb = nn.Embedding(self.num_classes, dim_t)
|
| 475 |
+
|
| 476 |
+
self.time_embed = nn.Sequential(
|
| 477 |
+
nn.Linear(dim_t, dim_t),
|
| 478 |
+
nn.SiLU(),
|
| 479 |
+
nn.Linear(dim_t, dim_t)
|
| 480 |
+
)
|
| 481 |
+
|
| 482 |
+
def forward(self, x, timesteps, y=None):
|
| 483 |
+
emb = self.time_embed(timestep_embedding(timesteps, self.dim_t))
|
| 484 |
+
if y is not None and self.num_classes > 0:
|
| 485 |
+
emb += self.label_emb(y.squeeze())
|
| 486 |
+
return self.resnet(x, emb)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/utils.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import numpy as np
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from torch.profiler import record_function
|
| 5 |
+
from inspect import isfunction
|
| 6 |
+
|
| 7 |
+
def normal_kl(mean1, logvar1, mean2, logvar2):
|
| 8 |
+
"""
|
| 9 |
+
Compute the KL divergence between two gaussians.
|
| 10 |
+
|
| 11 |
+
Shapes are automatically broadcasted, so batches can be compared to
|
| 12 |
+
scalars, among other use cases.
|
| 13 |
+
"""
|
| 14 |
+
tensor = None
|
| 15 |
+
for obj in (mean1, logvar1, mean2, logvar2):
|
| 16 |
+
if isinstance(obj, torch.Tensor):
|
| 17 |
+
tensor = obj
|
| 18 |
+
break
|
| 19 |
+
assert tensor is not None, "at least one argument must be a Tensor"
|
| 20 |
+
|
| 21 |
+
# Force variances to be Tensors. Broadcasting helps convert scalars to
|
| 22 |
+
# Tensors, but it does not work for torch.exp().
|
| 23 |
+
logvar1, logvar2 = [
|
| 24 |
+
x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
|
| 25 |
+
for x in (logvar1, logvar2)
|
| 26 |
+
]
|
| 27 |
+
|
| 28 |
+
return 0.5 * (
|
| 29 |
+
-1.0
|
| 30 |
+
+ logvar2
|
| 31 |
+
- logvar1
|
| 32 |
+
+ torch.exp(logvar1 - logvar2)
|
| 33 |
+
+ ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
def approx_standard_normal_cdf(x):
|
| 37 |
+
"""
|
| 38 |
+
A fast approximation of the cumulative distribution function of the
|
| 39 |
+
standard normal.
|
| 40 |
+
"""
|
| 41 |
+
return 0.5 * (1.0 + torch.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * torch.pow(x, 3))))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def discretized_gaussian_log_likelihood(x, *, means, log_scales):
|
| 45 |
+
"""
|
| 46 |
+
Compute the log-likelihood of a Gaussian distribution discretizing to a
|
| 47 |
+
given image.
|
| 48 |
+
|
| 49 |
+
:param x: the target images. It is assumed that this was uint8 values,
|
| 50 |
+
rescaled to the range [-1, 1].
|
| 51 |
+
:param means: the Gaussian mean Tensor.
|
| 52 |
+
:param log_scales: the Gaussian log stddev Tensor.
|
| 53 |
+
:return: a tensor like x of log probabilities (in nats).
|
| 54 |
+
"""
|
| 55 |
+
assert x.shape == means.shape == log_scales.shape
|
| 56 |
+
centered_x = x - means
|
| 57 |
+
inv_stdv = torch.exp(-log_scales)
|
| 58 |
+
plus_in = inv_stdv * (centered_x + 1.0 / 255.0)
|
| 59 |
+
cdf_plus = approx_standard_normal_cdf(plus_in)
|
| 60 |
+
min_in = inv_stdv * (centered_x - 1.0 / 255.0)
|
| 61 |
+
cdf_min = approx_standard_normal_cdf(min_in)
|
| 62 |
+
log_cdf_plus = torch.log(cdf_plus.clamp(min=1e-12))
|
| 63 |
+
log_one_minus_cdf_min = torch.log((1.0 - cdf_min).clamp(min=1e-12))
|
| 64 |
+
cdf_delta = cdf_plus - cdf_min
|
| 65 |
+
log_probs = torch.where(
|
| 66 |
+
x < -0.999,
|
| 67 |
+
log_cdf_plus,
|
| 68 |
+
torch.where(x > 0.999, log_one_minus_cdf_min, torch.log(cdf_delta.clamp(min=1e-12))),
|
| 69 |
+
)
|
| 70 |
+
assert log_probs.shape == x.shape
|
| 71 |
+
return log_probs
|
| 72 |
+
|
| 73 |
+
def sum_except_batch(x, num_dims=1):
|
| 74 |
+
'''
|
| 75 |
+
Sums all dimensions except the first.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
x: Tensor, shape (batch_size, ...)
|
| 79 |
+
num_dims: int, number of batch dims (default=1)
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
x_sum: Tensor, shape (batch_size,)
|
| 83 |
+
'''
|
| 84 |
+
return x.reshape(*x.shape[:num_dims], -1).sum(-1)
|
| 85 |
+
|
| 86 |
+
def mean_flat(tensor):
|
| 87 |
+
"""
|
| 88 |
+
Take the mean over all non-batch dimensions.
|
| 89 |
+
"""
|
| 90 |
+
return tensor.mean(dim=list(range(1, len(tensor.shape))))
|
| 91 |
+
|
| 92 |
+
def ohe_to_categories(ohe, K):
|
| 93 |
+
K = torch.from_numpy(K)
|
| 94 |
+
indices = torch.cat([torch.zeros((1,)), K.cumsum(dim=0)], dim=0).int().tolist()
|
| 95 |
+
res = []
|
| 96 |
+
for i in range(len(indices) - 1):
|
| 97 |
+
res.append(ohe[:, indices[i]:indices[i+1]].argmax(dim=1))
|
| 98 |
+
return torch.stack(res, dim=1)
|
| 99 |
+
|
| 100 |
+
def log_1_min_a(a):
|
| 101 |
+
return torch.log(1 - a.exp() + 1e-40)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def log_add_exp(a, b):
|
| 105 |
+
maximum = torch.max(a, b)
|
| 106 |
+
return maximum + torch.log(torch.exp(a - maximum) + torch.exp(b - maximum))
|
| 107 |
+
|
| 108 |
+
def exists(x):
|
| 109 |
+
return x is not None
|
| 110 |
+
|
| 111 |
+
def extract(a, t, x_shape):
|
| 112 |
+
b, *_ = t.shape
|
| 113 |
+
t = t.to(a.device)
|
| 114 |
+
out = a.gather(-1, t)
|
| 115 |
+
while len(out.shape) < len(x_shape):
|
| 116 |
+
out = out[..., None]
|
| 117 |
+
return out.expand(x_shape)
|
| 118 |
+
|
| 119 |
+
def default(val, d):
|
| 120 |
+
if exists(val):
|
| 121 |
+
return val
|
| 122 |
+
return d() if isfunction(d) else d
|
| 123 |
+
|
| 124 |
+
def log_categorical(log_x_start, log_prob):
|
| 125 |
+
return (log_x_start.exp() * log_prob).sum(dim=1)
|
| 126 |
+
|
| 127 |
+
def index_to_log_onehot(x, num_classes):
|
| 128 |
+
onehots = []
|
| 129 |
+
for i in range(len(num_classes)):
|
| 130 |
+
onehots.append(F.one_hot(x[:, i], num_classes[i]))
|
| 131 |
+
|
| 132 |
+
x_onehot = torch.cat(onehots, dim=1)
|
| 133 |
+
log_onehot = torch.log(x_onehot.float().clamp(min=1e-30))
|
| 134 |
+
return log_onehot
|
| 135 |
+
|
| 136 |
+
def log_sum_exp_by_classes(x, slices):
|
| 137 |
+
device = x.device
|
| 138 |
+
res = torch.zeros_like(x)
|
| 139 |
+
for ixs in slices:
|
| 140 |
+
res[:, ixs] = torch.logsumexp(x[:, ixs], dim=1, keepdim=True)
|
| 141 |
+
|
| 142 |
+
assert x.size() == res.size()
|
| 143 |
+
|
| 144 |
+
return res
|
| 145 |
+
|
| 146 |
+
@torch.jit.script
|
| 147 |
+
def log_sub_exp(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
|
| 148 |
+
m = torch.maximum(a, b)
|
| 149 |
+
return torch.log(torch.exp(a - m) - torch.exp(b - m)) + m
|
| 150 |
+
|
| 151 |
+
@torch.jit.script
|
| 152 |
+
def sliced_logsumexp(x, slices):
|
| 153 |
+
lse = torch.logcumsumexp(
|
| 154 |
+
torch.nn.functional.pad(x, [1, 0, 0, 0], value=-float('inf')),
|
| 155 |
+
dim=-1)
|
| 156 |
+
|
| 157 |
+
slice_starts = slices[:-1]
|
| 158 |
+
slice_ends = slices[1:]
|
| 159 |
+
|
| 160 |
+
slice_lse = log_sub_exp(lse[:, slice_ends], lse[:, slice_starts])
|
| 161 |
+
slice_lse_repeated = torch.repeat_interleave(
|
| 162 |
+
slice_lse,
|
| 163 |
+
slice_ends - slice_starts,
|
| 164 |
+
dim=-1
|
| 165 |
+
)
|
| 166 |
+
return slice_lse_repeated
|
| 167 |
+
|
| 168 |
+
def log_onehot_to_index(log_x):
|
| 169 |
+
return log_x.argmax(1)
|
| 170 |
+
|
| 171 |
+
class FoundNANsError(BaseException):
|
| 172 |
+
"""Found NANs during sampling"""
|
| 173 |
+
def __init__(self, message='Found NANs during sampling.'):
|
| 174 |
+
super(FoundNANsError, self).__init__(message)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_sample_r0.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, sys, subprocess, json
|
| 2 |
+
import numpy as np
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
tabddpm_root = "/workspace/tabddpm/code"
|
| 6 |
+
runtime_root = "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime"
|
| 7 |
+
assert os.path.isdir(tabddpm_root), f"TabDDPM source not mounted: {tabddpm_root}"
|
| 8 |
+
|
| 9 |
+
if not os.path.exists(runtime_root):
|
| 10 |
+
def _ignore(_, names):
|
| 11 |
+
skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"}
|
| 12 |
+
return [n for n in names if n in skip or n.endswith(".pyc")]
|
| 13 |
+
import shutil
|
| 14 |
+
shutil.copytree(tabddpm_root, runtime_root, ignore=_ignore)
|
| 15 |
+
|
| 16 |
+
env = os.environ.copy()
|
| 17 |
+
env["PYTHONPATH"] = runtime_root + (os.pathsep + env.get("PYTHONPATH", ""))
|
| 18 |
+
|
| 19 |
+
# Reuse the compat wrapper (patches collections.Sequence for skorch)
|
| 20 |
+
wrapper = os.path.join(runtime_root, "_compat_run.py")
|
| 21 |
+
if not os.path.exists(wrapper):
|
| 22 |
+
with open(wrapper, "w") as f:
|
| 23 |
+
f.write(
|
| 24 |
+
"import collections, collections.abc\n"
|
| 25 |
+
"for _a in ('Sequence','MutableSequence','MutableMapping','Mapping',"
|
| 26 |
+
"'MutableSet','Set','Callable','Iterable','Iterator'):\n"
|
| 27 |
+
" if not hasattr(collections, _a): setattr(collections, _a, getattr(collections.abc, _a, None))\n"
|
| 28 |
+
"import sys, runpy\n"
|
| 29 |
+
"sys.argv = sys.argv[1:]\n"
|
| 30 |
+
"runpy.run_path(sys.argv[0], run_name='__main__')\n"
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
print(f"[TabDDPM] Sampling 7636 rows")
|
| 34 |
+
ret = subprocess.run(
|
| 35 |
+
[sys.executable, wrapper, "scripts/pipeline.py",
|
| 36 |
+
"--config", "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/config_sample_20260510_222509_r0.toml",
|
| 37 |
+
"--sample"],
|
| 38 |
+
cwd=runtime_root,
|
| 39 |
+
env=env
|
| 40 |
+
)
|
| 41 |
+
if ret.returncode != 0:
|
| 42 |
+
sys.exit(ret.returncode)
|
| 43 |
+
|
| 44 |
+
# 将 .npy 输出转为 CSV(npy 在 TabDDPM 的 parent_dir,即 npy_dir)
|
| 45 |
+
info_path = "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/data/info.json"
|
| 46 |
+
with open(info_path) as f:
|
| 47 |
+
info = json.load(f)
|
| 48 |
+
|
| 49 |
+
output_dir = "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/output"
|
| 50 |
+
col_names = info.get("column_names", [])
|
| 51 |
+
|
| 52 |
+
parts = []
|
| 53 |
+
x_num_path = os.path.join(output_dir, "X_num_train.npy")
|
| 54 |
+
x_cat_path = os.path.join(output_dir, "X_cat_train.npy")
|
| 55 |
+
y_path = os.path.join(output_dir, "y_train.npy")
|
| 56 |
+
|
| 57 |
+
if os.path.exists(x_num_path):
|
| 58 |
+
parts.append(np.load(x_num_path, allow_pickle=True))
|
| 59 |
+
if os.path.exists(x_cat_path):
|
| 60 |
+
parts.append(np.load(x_cat_path, allow_pickle=True).astype(float))
|
| 61 |
+
if os.path.exists(y_path):
|
| 62 |
+
y = np.load(y_path, allow_pickle=True)
|
| 63 |
+
parts.append(y.reshape(-1, 1) if y.ndim == 1 else y)
|
| 64 |
+
|
| 65 |
+
if parts:
|
| 66 |
+
combined = np.concatenate(parts, axis=1)
|
| 67 |
+
if col_names and len(col_names) == combined.shape[1]:
|
| 68 |
+
df = pd.DataFrame(combined, columns=col_names)
|
| 69 |
+
else:
|
| 70 |
+
df = pd.DataFrame(combined)
|
| 71 |
+
df.to_csv("/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/tabddpm-c6-7636-20260510_222509.csv", index=False)
|
| 72 |
+
print(f"[TabDDPM] Saved {len(df)} rows -> /work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/tabddpm-c6-7636-20260510_222509.csv")
|
| 73 |
+
else:
|
| 74 |
+
print("[TabDDPM] WARNING: No output .npy files found")
|
| 75 |
+
sys.exit(1)
|
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_train.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, sys, subprocess
|
| 2 |
+
|
| 3 |
+
tabddpm_root = "/workspace/tabddpm/code"
|
| 4 |
+
runtime_root = "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime"
|
| 5 |
+
assert os.path.isdir(tabddpm_root), f"TabDDPM source not mounted: {tabddpm_root}"
|
| 6 |
+
|
| 7 |
+
def _ignore(_, names):
|
| 8 |
+
skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"}
|
| 9 |
+
return [n for n in names if n in skip or n.endswith(".pyc")]
|
| 10 |
+
|
| 11 |
+
import shutil
|
| 12 |
+
shutil.rmtree(runtime_root, ignore_errors=True)
|
| 13 |
+
shutil.copytree(tabddpm_root, runtime_root, ignore=_ignore)
|
| 14 |
+
|
| 15 |
+
env = os.environ.copy()
|
| 16 |
+
env["PYTHONPATH"] = runtime_root + (os.pathsep + env.get("PYTHONPATH", ""))
|
| 17 |
+
|
| 18 |
+
# Write a wrapper that patches collections.Sequence (removed in Python 3.10+)
|
| 19 |
+
# before running pipeline.py - needed because skorch uses old API
|
| 20 |
+
wrapper = os.path.join(runtime_root, "_compat_run.py")
|
| 21 |
+
with open(wrapper, "w") as f:
|
| 22 |
+
f.write(
|
| 23 |
+
"import collections, collections.abc\n"
|
| 24 |
+
"for _a in ('Sequence','MutableSequence','MutableMapping','Mapping',"
|
| 25 |
+
"'MutableSet','Set','Callable','Iterable','Iterator'):\n"
|
| 26 |
+
" if not hasattr(collections, _a): setattr(collections, _a, getattr(collections.abc, _a, None))\n"
|
| 27 |
+
"import sys, runpy\n"
|
| 28 |
+
"sys.argv = sys.argv[1:]\n"
|
| 29 |
+
"runpy.run_path(sys.argv[0], run_name='__main__')\n"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
print(f"[TabDDPM] Training, config=/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/config.toml")
|
| 33 |
+
ret = subprocess.run(
|
| 34 |
+
[sys.executable, wrapper, "scripts/pipeline.py",
|
| 35 |
+
"--config", "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/config.toml",
|
| 36 |
+
"--train"],
|
| 37 |
+
cwd=runtime_root,
|
| 38 |
+
env=env
|
| 39 |
+
)
|
| 40 |
+
if ret.returncode != 0:
|
| 41 |
+
sys.exit(ret.returncode)
|
| 42 |
+
print("[TabDDPM] Training complete")
|