Add files using upload-large-folder tool
Browse filesFiles changed (50)
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/._dataAdded
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/.gitignoreAdded+22
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/.gitmodulesAdded+9
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CONFIG_DESCRIPTION.mdAdded+78
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/.gitignoreAdded+1
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/README.mdAdded+49
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.pyAdded+81
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.pyAdded+110
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.pyAdded+153
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/.gitignoreAdded+1
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/LICENSEAdded+201
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/License.txtAdded+15
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/README.mdAdded+50
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/pipeline_ctabgan.pyAdded+80
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/requirements.txtAdded+6
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/train_sample_ctabgan.pyAdded+108
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/tune_ctabgan.pyAdded+150
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/pipeline_tvae.pyAdded+80
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/train_sample_tvae.pyAdded+117
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/tune_tvae.pyAdded+153
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/LICENSE.mdAdded+21
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/README.mdAdded+99
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/_compat_run.pyAdded+6
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/agg_results.ipynbAdded+315
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__init__.pyAdded+12
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/data.pyAdded+719
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/deep.pyAdded+168
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/env.pyAdded+39
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/metrics.pyAdded+158
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/util.pyAdded+433
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/requirements.txtAdded+22
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm.shAdded+5
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm_docker.shAdded+5
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__init__.pyAdded
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_catboost.pyAdded+145
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_mlp.pyAdded+176
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds.pyAdded+121
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds_simple.pyAdded+130
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_simple.pyAdded+141
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/pipeline.pyAdded+112
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/resample_privacy.pyAdded+257
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/sample.pyAdded+160
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/train.pyAdded+158
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_evaluation_model.pyAdded+145
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__init__.pyAdded+2
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/gaussian_multinomial_diffsuion.pyAdded+993
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/modules.pyAdded+486
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/utils.pyAdded+174
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_sample_r0.pyAdded+75
- syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_train.pyAdded+42
12345678910111213141516171819202122.DS_Store__pycache__/catboost_info/**/**.pt**/**.ipynb!agg_results.ipynb**/**.npy**/**.gz**/**.sh**/**.obj**/**.png**/**.tar**/**.code-workspace**/**.csvexp/**/**/results_catboost.jsonexp/**/**/results_mlp.json
configs/data/junk/RF/exps/123456789[submodule "ctgan"] # path = CTGAN/CTGAN url = https://github.com/sdv-dev/CTGAN[submodule "ctabgan"] # path = CTAB-GAN url = https://github.com/Team-TUD/CTAB-GAN[submodule "ctabgan+"] # path = CTAB-GAN-Plus url = https://github.com/Team-TUD/CTAB-GAN-Plus123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778# Description of .toml config for TabDDPMFirst of all, `train.T` and `eval.T` denote preprocessing for training and for evaluation, respectively.
Here we list non-obvious parameters.
Main part:- `seed = 0` -- evaluation seed (and training, but for training it is fixed to 0)- `parent_dir = "exp/abalone/check"` -- exp folder- `real_data_path = "data/abalone/"`- `model_type = "mlp"` -- model type that approximates the reverse process- `num_numerical_features ` -- a number of numerical features in dataset- `device = "cuda:0"`
Model params:- `is_y_cond` -- false for regression, true for classification- `d_in` -- input dimension (not necessary, since scripts calculate it automatically)- `num_calsses` -- zero for regression, a number of classes for classification- `rtdl_params` -- MLP parameters
```tomlseed = 0parent_dir = "exp/abalone/check"real_data_path = "data/abalone/"model_type = "mlp"num_numerical_features = 7device = "cuda:0"
[model_params]is_y_cond = falsed_in = 11num_classes = 0
[model_params.rtdl_params]d_layers = [ 256, 256,]dropout = 0.0
[diffusion_params]num_timesteps = 1000gaussian_loss_type = "mse"scheduler = "cosine"
[train.main]steps = 1000lr = 0.001weight_decay = 1e-05batch_size = 4096
[train.T]seed = 0normalization = "quantile"num_nan_policy = "__none__"cat_nan_policy = "__none__"cat_min_frequency = "__none__"cat_encoding = "__none__"y_policy = "default"
[sample]num_samples = 20800batch_size = 10000seed = 0
[eval.type]eval_model = "catboost"eval_type = "synthetic"
[eval.T]seed = 0normalization = "__none__"num_nan_policy = "__none__"cat_nan_policy = "__none__"cat_min_frequency = "__none__"cat_encoding = "__none__"y_policy = "default"
```1**/**.csv12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849# CTAB-GAN+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.If you have any question, please contact `z.zhao-8@tudelft.nl` for more information.
## Prerequisite
The required package version```numpy==1.21.0torch==1.9.1pandas==1.2.4sklearn==0.24.1dython==0.6.4.post1scipy==1.4.1```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!
## Example`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.The evaluation code is also provided.
## Problem type
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:```problem_type= {None: None}```
## For large dataset
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```sides = [4, 8, 16, 24, 32]```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.
## Bibtex
To cite this paper, you could use this bibtex
```@article{zhao2022ctab, title={CTAB-GAN+: Enhancing Tabular Data Synthesis}, author={Zhao, Zilong and Kunar, Aditya and Birke, Robert and Chen, Lydia Y}, journal={arXiv preprint arXiv:2204.00401}, year={2022}}```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import tomliimport shutilimport osimport argparsefrom train_sample_ctabganp import train_ctabgan, sample_ctabganfrom scripts.eval_catboost import train_catboostimport zeroimport libfrom model.ctabgan import CTABGAN
def load_config(path) : with open(path, 'rb') as f: return tomli.load(f) def save_file(parent_dir, config_path): try: dst = os.path.join(parent_dir) os.makedirs(os.path.dirname(dst), exist_ok=True) shutil.copyfile(os.path.abspath(config_path), dst) except shutil.SameFileError: pass
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', metavar='FILE') parser.add_argument('--train', action='store_true', default=False) parser.add_argument('--sample', action='store_true', default=False) parser.add_argument('--eval', action='store_true', default=False) parser.add_argument('--change_val', action='store_true', default=False)
args = parser.parse_args() raw_config = lib.load_config(args.config) timer = zero.Timer() timer.run() save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config) ctabgan = None if args.train: ctabgan = train_ctabgan( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], train_params=raw_config['train_params'], change_val=args.change_val, device=raw_config['device'] ) if args.sample: sample_ctabgan( synthesizer=ctabgan, parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], num_samples=raw_config['sample']['num_samples'], train_params=raw_config['train_params'], change_val=args.change_val, seed=raw_config['sample']['seed'], device=raw_config['device'] )
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json')) if args.eval: if raw_config['eval']['type']['eval_model'] == 'catboost': train_catboost( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], eval_type=raw_config['eval']['type']['eval_type'], T_dict=raw_config['eval']['T'], seed=raw_config['seed'], change_val=args.change_val ) # elif raw_config['eval']['type']['eval_model'] == 'mlp': # train_mlp( # parent_dir=raw_config['parent_dir'], # real_data_path=raw_config['real_data_path'], # eval_type=raw_config['eval']['type']['eval_type'], # T_dict=raw_config['eval']['T'], # seed=raw_config['seed'], # change_val=args.change_val # )
print(f'Elapsed time: {str(timer)}')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110import libimport osimport numpy as npimport argparsefrom model.ctabgan import CTABGANfrom pathlib import Pathimport torchimport pickle
def train_ctabgan( parent_dir, real_data_path, train_params = {"batch_size": 512}, change_val=False, device = "cpu"): real_data_path = Path(real_data_path) parent_dir = Path(parent_dir) device = torch.device(device)
if change_val: X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) else: X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
X.columns = [str(_) for _ in X.columns]
ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name] train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
print(train_params) synthesizer = CTABGAN( df = X, test_ratio = 0.0, **ctabgan_params, **train_params, device=device ) synthesizer.fit()
# save_ctabgan(synthesizer, parent_dir) with open(parent_dir / "ctabgan.obj", "wb") as f: pickle.dump(synthesizer, f)
return synthesizer
def sample_ctabgan( synthesizer, parent_dir, real_data_path, num_samples, train_params = {"batch_size": 512}, change_val=False, device="cpu", seed=0): real_data_path = Path(real_data_path) parent_dir = Path(parent_dir) device = torch.device(device)
if change_val: X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) else: X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
X.columns = [str(_) for _ in X.columns]
ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name]
cat_features = ctabgan_params["categorical_columns"] # if synthesizer is None: # synthesizer = load_ctabgan(X, ctabgan_params, train_params, parent_dir) with open(parent_dir / "ctabgan.obj", 'rb') as f: synthesizer = pickle.load(f) synthesizer.synthesizer.generator = synthesizer.synthesizer.generator.to(device) gen_data = synthesizer.generate_samples(num_samples, seed)
y = gen_data['y'].values if len(np.unique(y)) == 1: y[0] = 0 y[1] = 1
X_cat = gen_data[cat_features].drop('y', axis=1, errors="ignore").values if len(cat_features) else None X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
if X_num_train is not None: np.save(parent_dir / 'X_num_train', X_num.astype(float)) if X_cat_train is not None: np.save(parent_dir / 'X_cat_train', X_cat.astype(str)) np.save(parent_dir / 'y_train', y.astype(float).astype(int)) # only clf !!!
def main(): parser = argparse.ArgumentParser() parser.add_argument('real_data_path', type=str) parser.add_argument('parent_dir', type=str) parser.add_argument('train_size', type=int) args = parser.parse_args()
ctabgan = train_ctabgan(args.parent_dir, args.real_data_path, change_val=True) sample_ctabgan(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153from multiprocessing.sharedctypes import RawValuefrom random import randomimport tempfileimport subprocessimport libimport osimport optunaimport argparsefrom pathlib import Pathfrom train_sample_ctabganp import train_ctabgan, sample_ctabganfrom scripts.eval_catboost import train_catboost
parser = argparse.ArgumentParser()parser.add_argument('data_path', type=str)parser.add_argument('train_size', type=int)parser.add_argument('eval_type', type=str)parser.add_argument('device', type=str)
args = parser.parse_args()real_data_path = args.data_patheval_type = args.eval_typetrain_size = args.train_sizedevice = args.deviceassert eval_type in ('merged', 'synthetic')
def objective(trial): lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
def suggest_dim(name): t = trial.suggest_int(name, d_min, d_max) return 2 ** t # construct model min_n_layers, max_n_layers, d_min, d_max = 1, 4, 6, 8 n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers) d_first = [suggest_dim('d_first')] if n_layers else [] d_middle = ( [suggest_dim('d_middle')] * (n_layers - 2) if n_layers > 2 else [] ) d_last = [suggest_dim('d_last')] if n_layers > 1 else [] d_layers = d_first + d_middle + d_last ####
steps = trial.suggest_categorical('steps', [1000, 5000, 10000]) # steps = trial.suggest_categorical('steps', [10]) batch_size = 2 ** trial.suggest_int('batch_size', 9, 11) random_dim = 2 ** trial.suggest_int('random_dim', 4, 7) num_channels = 2 ** trial.suggest_int('num_channels', 4, 6)
# steps = trial.suggest_categorical('steps', [1000])
num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3)))
train_params = { "lr": lr, "epochs": steps, "class_dim": d_layers, "batch_size": batch_size, "random_dim": random_dim, "num_channels": num_channels } trial.set_user_attr("train_params", train_params) trial.set_user_attr("num_samples", num_samples)
score = 0.0 with tempfile.TemporaryDirectory() as dir_: dir_ = Path(dir_) ctabgan = train_ctabgan( parent_dir=dir_, real_data_path=real_data_path, train_params=train_params, change_val=True, device=device )
for sample_seed in range(5): sample_ctabgan( ctabgan, parent_dir=dir_, real_data_path=real_data_path, num_samples=num_samples, train_params=train_params, change_val=True, seed=sample_seed, device=device )
T_dict = { "seed": 0, "normalization": None, "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": None, "y_policy": "default" } metrics = train_catboost( parent_dir=dir_, real_data_path=real_data_path, eval_type=eval_type, T_dict=T_dict, change_val=True, seed = 0 )
score += metrics.get_val_score() return score / 5
study = optuna.create_study( direction='maximize', sampler=optuna.samplers.TPESampler(seed=0),)
study.optimize(objective, n_trials=35, show_progress_bar=True)
os.makedirs(f"exp/{Path(real_data_path).name}/ctabgan-plus/", exist_ok=True)config = { "parent_dir": f"exp/{Path(real_data_path).name}/ctabgan-plus/", "real_data_path": real_data_path, "seed": 0, "device": args.device, "train_params": study.best_trial.user_attrs["train_params"], "sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]}, "eval": { "type": {"eval_model": "catboost", "eval_type": eval_type}, "T": { "seed": 0, "normalization": None, "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": None, "y_policy": "default" }, }}
train_ctabgan( parent_dir=f"exp/{Path(real_data_path).name}/ctabgan-plus/", real_data_path=real_data_path, train_params=study.best_trial.user_attrs["train_params"], change_val=False, device=device)
lib.dump_config(config, config["parent_dir"]+"config.toml")
subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}', '10', "ctabgan-plus", eval_type, "catboost", "5"], check=True)1**/**.csv123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.123456789101112131415Distributed learning systems Lab at TU Delft & Generatrix, hereby disclaims all copyright interest in the program "CTAB-GAN" (which synthesizes tabular data)
Copyright 2020-2022 Distributed learning systems Lab at TU Delft & Generatrix.
Licensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an "AS IS" BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.See the License for the specific language governing permissions andlimitations under the License.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# CTAB-GANThis 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.
## Prerequisite
The required package version```numpy==1.21.0torch==1.9.1pandas==1.2.4sklearn==0.24.1dython==0.6.4.post1scipy==1.4.1```
## Example`Experiment_Script_Adult.ipynb` is an example notebook for training CTAB-GAN with Adult dataset. The dataset is alread under `Real_Datasets` folder.The evaluation code is also provided.
## For large dataset
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```sides = [4, 8, 16, 24, 32]```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.
## Bibtex
To cite this paper, you could use this bibtex
```@InProceedings{zhao21, title = {CTAB-GAN: Effective Table Data Synthesizing}, author = {Zhao, Zilong and Kunar, Aditya and Birke, Robert and Chen, Lydia Y.}, booktitle = {Proceedings of The 13th Asian Conference on Machine Learning}, pages = {97--112}, year = {2021}, editor = {Balasubramanian, Vineeth N. and Tsang, Ivor}, volume = {157}, series = {Proceedings of Machine Learning Research}, month = {17--19 Nov}, publisher = {PMLR}, pdf = {https://proceedings.mlr.press/v157/zhao21a/zhao21a.pdf}, url = {https://proceedings.mlr.press/v157/zhao21a.html}}
```1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import tomliimport shutilimport osimport argparsefrom train_sample_ctabgan import train_ctabgan, sample_ctabganfrom scripts.eval_catboost import train_catboostimport zeroimport lib
def load_config(path) : with open(path, 'rb') as f: return tomli.load(f) def save_file(parent_dir, config_path): try: dst = os.path.join(parent_dir) os.makedirs(os.path.dirname(dst), exist_ok=True) shutil.copyfile(os.path.abspath(config_path), dst) except shutil.SameFileError: pass
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', metavar='FILE') parser.add_argument('--train', action='store_true', default=False) parser.add_argument('--sample', action='store_true', default=False) parser.add_argument('--eval', action='store_true', default=False) parser.add_argument('--change_val', action='store_true', default=False)
args = parser.parse_args() raw_config = lib.load_config(args.config) timer = zero.Timer() timer.run() save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config) ctabgan = None if args.train: ctabgan = train_ctabgan( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], train_params=raw_config['train_params'], change_val=args.change_val, device=raw_config['device'] ) if args.sample: sample_ctabgan( synthesizer=ctabgan, parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], num_samples=raw_config['sample']['num_samples'], train_params=raw_config['train_params'], change_val=args.change_val, seed=raw_config['sample']['seed'], device=raw_config['device'] )
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json')) if args.eval: if raw_config['eval']['type']['eval_model'] == 'catboost': train_catboost( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], eval_type=raw_config['eval']['type']['eval_type'], T_dict=raw_config['eval']['T'], seed=raw_config['seed'], change_val=args.change_val ) # elif raw_config['eval']['type']['eval_model'] == 'mlp': # train_mlp( # parent_dir=raw_config['parent_dir'], # real_data_path=raw_config['real_data_path'], # eval_type=raw_config['eval']['type']['eval_type'], # T_dict=raw_config['eval']['T'], # seed=raw_config['seed'], # change_val=args.change_val # )
print(f'Elapsed time: {str(timer)}')
if __name__ == '__main__': main()123456numpy==1.21.0torch==1.9.1pandas==1.2.4sklearn==0.24.1dython==0.6.4.post1scipy==1.4.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108import libimport osimport numpy as npimport argparsefrom pathlib import Pathfrom model.ctabgan import CTABGANimport torchimport pickle
def train_ctabgan( parent_dir, real_data_path, train_params = {"batch_size": 512}, change_val=False, device = "cpu"): real_data_path = Path(real_data_path) parent_dir = Path(parent_dir) device = torch.device(device)
if change_val: X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) else: X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
X.columns = [str(_) for _ in X.columns]
ctabgan_params = lib.load_json("CTAB-GAN/columns.json")[real_data_path.name] train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
print(train_params) synthesizer = CTABGAN( df = X, test_ratio = 0.0, **ctabgan_params, **train_params, device=device ) synthesizer.fit()
# save_ctabgan(synthesizer, parent_dir) with open(parent_dir / "ctabgan.obj", "wb") as f: pickle.dump(synthesizer, f)
return synthesizer
def sample_ctabgan( synthesizer, parent_dir, real_data_path, num_samples, train_params = {"batch_size": 512}, change_val=False, device="cpu", seed=0): real_data_path = Path(real_data_path) parent_dir = Path(parent_dir) device = torch.device(device)
if change_val: X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) else: X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
X.columns = [str(_) for _ in X.columns]
ctabgan_params = lib.load_json("CTAB-GAN/columns.json")[real_data_path.name]
cat_features = ctabgan_params["categorical_columns"] # if synthesizer is None: # synthesizer = load_ctabgan(X, ctabgan_params, train_params, parent_dir) with open(parent_dir / "ctabgan.obj", 'rb') as f: synthesizer = pickle.load(f) synthesizer.synthesizer.generator = synthesizer.synthesizer.generator.to(device) gen_data = synthesizer.generate_samples(num_samples, seed)
y = gen_data['y'].values if len(np.unique(y)) == 1: y[0] = 1
X_cat = gen_data[cat_features].drop('y', axis=1).values if len(cat_features) else None X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
if X_num_train is not None: np.save(parent_dir / 'X_num_train', X_num.astype(float)) if X_cat_train is not None: np.save(parent_dir / 'X_cat_train', X_cat.astype(str)) np.save(parent_dir / 'y_train', y.astype(float).astype(int)) # only clf !!!
def main(): parser = argparse.ArgumentParser() parser.add_argument('real_data_path', type=str) parser.add_argument('parent_dir', type=str) parser.add_argument('train_size', type=int) args = parser.parse_args()
ctabgan = train_ctabgan(args.parent_dir, args.real_data_path, change_val=True) sample_ctabgan(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150from multiprocessing.sharedctypes import RawValueimport tempfileimport subprocessimport libimport osimport optunaimport argparsefrom pathlib import Pathfrom train_sample_ctabgan import train_ctabgan, sample_ctabganfrom scripts.eval_catboost import train_catboost
parser = argparse.ArgumentParser()parser.add_argument('data_path', type=str)parser.add_argument('train_size', type=int)parser.add_argument('eval_type', type=str)parser.add_argument('device', type=str)
args = parser.parse_args()real_data_path = args.data_patheval_type = args.eval_typetrain_size = args.train_sizedevice = args.deviceassert eval_type in ('merged', 'synthetic')
def objective(trial): lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
def suggest_dim(name): t = trial.suggest_int(name, d_min, d_max) return 2 ** t # construct model min_n_layers, max_n_layers, d_min, d_max = 1, 4, 6, 8 n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers) d_first = [suggest_dim('d_first')] if n_layers else [] d_middle = ( [suggest_dim('d_middle')] * (n_layers - 2) if n_layers > 2 else [] ) d_last = [suggest_dim('d_last')] if n_layers > 1 else [] d_layers = d_first + d_middle + d_last ####
steps = trial.suggest_categorical('steps', [1000, 5000, 10000]) # steps = trial.suggest_categorical('steps', [10]) batch_size = 2 ** trial.suggest_int('batch_size', 9, 11) random_dim = 2 ** trial.suggest_int('random_dim', 4, 7) num_channels = 2 ** trial.suggest_int('num_channels', 4, 6)
num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3)))
train_params = { "lr": lr, "epochs": steps, "class_dim": d_layers, "batch_size": batch_size, "random_dim": random_dim, "num_channels": num_channels } trial.set_user_attr("train_params", train_params) trial.set_user_attr("num_samples", num_samples)
score = 0.0 with tempfile.TemporaryDirectory() as dir_: dir_ = Path(dir_) ctabgan = train_ctabgan( parent_dir=dir_, real_data_path=real_data_path, train_params=train_params, change_val=True, device=device )
for sample_seed in range(5): sample_ctabgan( ctabgan, parent_dir=dir_, real_data_path=real_data_path, num_samples=num_samples, train_params=train_params, change_val=True, seed=sample_seed, device=device )
T_dict = { "seed": 0, "normalization": None, "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": None, "y_policy": "default" } metrics = train_catboost( parent_dir=dir_, real_data_path=real_data_path, eval_type=eval_type, T_dict=T_dict, change_val=True, seed = 0 )
score += metrics.get_val_score() return score / 5
study = optuna.create_study( direction='maximize', sampler=optuna.samplers.TPESampler(seed=0),)
study.optimize(objective, n_trials=35, show_progress_bar=True)
os.makedirs(f"exp/{Path(real_data_path).name}/ctabgan/", exist_ok=True)config = { "parent_dir": f"exp/{Path(real_data_path).name}/ctabgan/", "real_data_path": real_data_path, "seed": 0, "device": args.device, "train_params": study.best_trial.user_attrs["train_params"], "sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]}, "eval": { "type": {"eval_model": "catboost", "eval_type": eval_type}, "T": { "seed": 0, "normalization": None, "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": None, "y_policy": "default" }, }}
train_ctabgan( parent_dir=f"exp/{Path(real_data_path).name}/ctabgan/", real_data_path=real_data_path, train_params=study.best_trial.user_attrs["train_params"], change_val=False, device=device)
lib.dump_config(config, config["parent_dir"]+"config.toml")
subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}', '10', "ctabgan", eval_type, "catboost", "5"], check=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import tomliimport shutilimport osimport argparsefrom train_sample_tvae import train_tvae, sample_tvaefrom scripts.eval_catboost import train_catboostimport zeroimport lib
def load_config(path) : with open(path, 'rb') as f: return tomli.load(f) def save_file(parent_dir, config_path): try: dst = os.path.join(parent_dir) os.makedirs(os.path.dirname(dst), exist_ok=True) shutil.copyfile(os.path.abspath(config_path), dst) except shutil.SameFileError: pass
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', metavar='FILE') parser.add_argument('--train', action='store_true', default=False) parser.add_argument('--sample', action='store_true', default=False) parser.add_argument('--eval', action='store_true', default=False) parser.add_argument('--change_val', action='store_true', default=False)
args = parser.parse_args() raw_config = lib.load_config(args.config) timer = zero.Timer() timer.run() save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config) ctabgan = None if args.train: ctabgan = train_tvae( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], train_params=raw_config['train_params'], change_val=args.change_val, device=raw_config['device'] ) if args.sample: sample_tvae( synthesizer=ctabgan, parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], num_samples=raw_config['sample']['num_samples'], train_params=raw_config['train_params'], change_val=args.change_val, seed=raw_config['sample']['seed'], device=raw_config['device'] )
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json')) if args.eval: if raw_config['eval']['type']['eval_model'] == 'catboost': train_catboost( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], eval_type=raw_config['eval']['type']['eval_type'], T_dict=raw_config['eval']['T'], seed=raw_config['seed'], change_val=args.change_val ) # elif raw_config['eval']['type']['eval_model'] == 'mlp': # train_mlp( # parent_dir=raw_config['parent_dir'], # real_data_path=raw_config['real_data_path'], # eval_type=raw_config['eval']['type']['eval_type'], # T_dict=raw_config['eval']['T'], # seed=raw_config['seed'], # change_val=args.change_val # )
print(f'Elapsed time: {str(timer)}')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import libimport osimport numpy as npimport argparsefrom CTGAN.ctgan import TVAESynthesizerfrom pathlib import Pathimport torchimport pickleimport warningsfrom sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings("ignore", category=ConvergenceWarning)
def train_tvae( parent_dir, real_data_path, train_params = {"batch_size": 512}, change_val=False, device = "cpu"): real_data_path = Path(real_data_path) parent_dir = Path(parent_dir) device = torch.device(device)
if change_val: X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) else: X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
X.columns = [str(_) for _ in X.columns] 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 [] if lib.load_json(real_data_path / "info.json")["task_type"] != "regression": cat_features += ["y"]
train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
print(train_params) synthesizer = TVAESynthesizer( **train_params, device=device ) synthesizer.fit(X, cat_features)
# save_ctabgan(synthesizer, parent_dir) with open(parent_dir / "tvae.obj", "wb") as f: pickle.dump(synthesizer, f)
return synthesizer
def sample_tvae( synthesizer, parent_dir, real_data_path, num_samples, train_params = {"batch_size": 512}, change_val=False, device="cpu", seed=0): real_data_path = Path(real_data_path) parent_dir = Path(parent_dir) device = torch.device(device)
if change_val: X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) else: X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
X.columns = [str(_) for _ in X.columns]
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 [] if lib.load_json(real_data_path / "info.json")["task_type"] != "regression": cat_features += ["y"]
with open(parent_dir / "tvae.obj", 'rb') as f: synthesizer = pickle.load(f) synthesizer.decoder = synthesizer.decoder.to(device)
gen_data = synthesizer.sample(num_samples, seed)
y = gen_data['y'].values if len(np.unique(y)) == 1: y[0] = 0 y[1] = 1
X_cat = gen_data[cat_features].drop('y', axis=1, errors="ignore").values if len(cat_features) else None X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
if X_num_train is not None: np.save(parent_dir / 'X_num_train', X_num.astype(float)) if X_cat_train is not None: np.save(parent_dir / 'X_cat_train', X_cat.astype(str)) y = y.astype(float) if lib.load_json(real_data_path / "info.json")["task_type"] != "regression": y = y.astype(int) np.save(parent_dir / 'y_train', y) # only clf !!!
def main(): parser = argparse.ArgumentParser() parser.add_argument('real_data_path', type=str) parser.add_argument('parent_dir', type=str) parser.add_argument('train_size', type=int) args = parser.parse_args()
ctabgan = train_tvae(args.parent_dir, args.real_data_path, change_val=True) sample_tvae(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153from multiprocessing.sharedctypes import RawValueimport tempfileimport subprocessimport libimport osimport optunaimport argparsefrom pathlib import Pathfrom train_sample_tvae import train_tvae, sample_tvaefrom scripts.eval_catboost import train_catboost
parser = argparse.ArgumentParser()parser.add_argument('data_path', type=str)parser.add_argument('train_size', type=int)parser.add_argument('eval_type', type=str)parser.add_argument('device', type=str)
args = parser.parse_args()real_data_path = args.data_patheval_type = args.eval_typetrain_size = args.train_sizedevice = args.deviceassert eval_type in ('merged', 'synthetic')
def objective(trial): lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
def suggest_dim(name): t = trial.suggest_int(name, d_min, d_max) return 2 ** t # construct model min_n_layers, max_n_layers, d_min, d_max = 1, 3, 6, 9 n_layers = 2 * trial.suggest_int('n_layers', min_n_layers, max_n_layers) d_first = [suggest_dim('d_first')] if n_layers else [] d_middle = ( [suggest_dim('d_middle')] * (n_layers - 2) if n_layers > 2 else [] ) d_last = [suggest_dim('d_last')] if n_layers > 1 else [] d_layers = d_first + d_middle + d_last ####
steps = trial.suggest_categorical('steps', [5000, 20000, 30000]) # steps = trial.suggest_categorical('steps', [1000]) batch_size = trial.suggest_categorical('batch_size', [256, 4096])
num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3))) embedding_dim = 2 ** trial.suggest_int('embedding_dim', 6, 10) loss_factor = trial.suggest_loguniform('loss_factor', 0.001, 10)
train_params = { "lr": lr, "epochs": steps, "embedding_dim": embedding_dim, "batch_size": batch_size, "loss_factor": loss_factor, "compress_dims": d_layers, "decompress_dims": d_layers }
trial.set_user_attr("train_params", train_params) trial.set_user_attr("num_samples", num_samples)
score = 0.0 with tempfile.TemporaryDirectory() as dir_: dir_ = Path(dir_) ctabgan = train_tvae( parent_dir=dir_, real_data_path=real_data_path, train_params=train_params, change_val=True, device=device )
for sample_seed in range(5): sample_tvae( ctabgan, parent_dir=dir_, real_data_path=real_data_path, num_samples=num_samples, train_params=train_params, change_val=True, seed=sample_seed, device=device )
T_dict = { "seed": 0, "normalization": None, "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": None, "y_policy": "default" } metrics = train_catboost( parent_dir=dir_, real_data_path=real_data_path, eval_type=eval_type, T_dict=T_dict, change_val=True, seed = 0 )
score += metrics.get_val_score() return score / 5
study = optuna.create_study( direction='maximize', sampler=optuna.samplers.TPESampler(seed=0),)
study.optimize(objective, n_trials=50, show_progress_bar=True)
os.makedirs(f"exp/{Path(real_data_path).name}/tvae/", exist_ok=True)config = { "parent_dir": f"exp/{Path(real_data_path).name}/tvae/", "real_data_path": real_data_path, "seed": 0, "device": args.device, "train_params": study.best_trial.user_attrs["train_params"], "sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]}, "eval": { "type": {"eval_model": "catboost", "eval_type": eval_type}, "T": { "seed": 0, "normalization": None, "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": None, "y_policy": "default" }, }}
train_tvae( parent_dir=f"exp/{Path(real_data_path).name}/tvae/", real_data_path=real_data_path, train_params=study.best_trial.user_attrs["train_params"], change_val=False, device=device)
lib.dump_config(config, config["parent_dir"]+"config.toml")
subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}', '10', "tvae", eval_type, "catboost", "5"], check=True)123456789101112131415161718192021MIT License
Copyright (c) 2022 Akim Kotelnikov
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# TabDDPM: Modelling Tabular Data with Diffusion ModelsThis is the official code for our paper "TabDDPM: Modelling Tabular Data with Diffusion Models" ([paper](https://arxiv.org/abs/2209.15421))
<!-- ## ResultsYou can view all the results and build your own tables with this [notebook](notebooks/Reports.ipynb). -->
## Setup the environment1. Install [conda](https://docs.conda.io/en/latest/miniconda.html) (just to manage the env).2. Run the following commands ```bash export REPO_DIR=/path/to/the/code cd $REPO_DIR
conda create -n tddpm python=3.9.7 conda activate tddpm
pip install torch==1.10.1+cu111 -f https://download.pytorch.org/whl/torch_stable.html pip install -r requirements.txt
# if the following commands do not succeed, update conda conda env config vars set PYTHONPATH=${PYTHONPATH}:${REPO_DIR} conda env config vars set PROJECT_DIR=${REPO_DIR}
conda deactivate conda activate tddpm ```
## Running the experiments
Here we describe the neccesary info for reproducing the experimental results. Use `agg_results.ipynb` to print results for all dataset and all methods.
### Datasets
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.
You could load the datasets with the following commands:
``` bashconda activate tddpmcd $PROJECT_DIRwget "https://www.dropbox.com/s/rpckvcs3vx7j605/data.tar?dl=0" -O data.tartar -xvf data.tar```
### File structure`tab-ddpm/` -- implementation of the proposed method `tuned_models/` -- tuned hyperparameters of evaluation model (CatBoost or MLP)
All main scripts are in `scripts/` folder:
- `scripts/pipeline.py` are used to train, sample and eval TabDDPM using a given config - `scripts/tune_ddpm.py` -- tune hyperparameters of TabDDPM- `scripts/eval_[catboost|mlp|simple].py` -- evaluate synthetic data using a tuned evaluation model or simple models- `scripts/eval_seeds.py` -- eval using multiple sampling and multuple eval seeds- `scripts/eval_seeds_simple.py` -- eval using multiple sampling and multuple eval seeds (for simple models)- `scripts/tune_evaluation_model.py` -- tune hyperparameters of eval model (CatBoost or MLP)- `scripts/resample_privacy.py` -- privacy calculation
Experiments folder (`exp/`):- All results and synthetic data are stored in `exp/[ds_name]/[exp_name]/` folder- `exp/[ds_name]/config.toml` is a base config for tuning TabDDPM- `exp/[ds_name]/eval_[catboost|mlp].json` stores results of evaluation (`scripts/eval_seeds.py`)
To understand the structure of `config.toml` file, read `CONFIG_DESCRIPTION.md`.
Baselines:- `smote/`- `CTGAN/` -- TVAE [official repo](https://github.com/sdv-dev/CTGAN)- `CTAB-GAN/` -- [official repo](https://github.com/Team-TUD/CTAB-GAN)- `CTAB-GAN-Plus/` -- [official repo](https://github.com/Team-TUD/CTAB-GAN-Plus)
### Examples
<ins>Run TabDDPM tuning.</ins>
Template and example (`--eval_seeds` is optional): ```bashpython scripts/tune_ddpm.py [ds_name] [train_size] synthetic [catboost|mlp] [exp_name] --eval_seedspython scripts/tune_ddpm.py churn2 6500 synthetic catboost ddpm_tune --eval_seeds```
<ins>Run TabDDPM pipeline.</ins>
Template and example (`--train`, `--sample`, `--eval` are optional): ```bashpython scripts/pipeline.py --config [path_to_your_config] --train --sample --evalpython scripts/pipeline.py --config exp/churn2/ddpm_cb_best/config.toml --train --sample```It takes approximately 7min to run the script above (NVIDIA GeForce RTX 2080 Ti).
<ins>Run evaluation over seeds</ins> Before running evaluation, you have to train the model with the given hyperparameters (the example above).
Template and example: ```bashpython scripts/eval_seeds.py --config [path_to_your_config] [n_eval_seeds] [ddpm|smote|ctabgan|ctabgan-plus|tvae] synthetic [catboost|mlp] [n_sample_seeds]python scripts/eval_seeds.py --config exp/churn2/ddpm_cb_best/config.toml 10 ddpm synthetic catboost 5```123456import collections, collections.abcfor _a in ('Sequence','MutableSequence','MutableMapping','Mapping','MutableSet','Set','Callable','Iterable','Iterator'): if not hasattr(collections, _a): setattr(collections, _a, getattr(collections.abc, _a, None))import sys, runpysys.argv = sys.argv[1:]runpy.run_path(sys.argv[0], run_name='__main__')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Aggregating results to DataFrame" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "import lib\n", "import numpy as np\n", "import pandas as pd\n", "\n", "DATASETS = [\n", " \"abalone\",\n", " \"adult\",\n", " \"buddy\",\n", " \"california\",\n", " \"cardio\",\n", " \"churn2\",\n", " \"default\",\n", " \"diabetes\",\n", " \"fb-comments\",\n", " \"gesture\",\n", " \"higgs-small\",\n", " \"house\",\n", " \"insurance\",\n", " \"king\",\n", " \"miniboone\",\n", " \"wilt\"\n", "]\n", "\n", "_REGRESSION = [\n", " \"abalone\",\n", " \"california\",\n", " \"fb-comments\",\n", " \"house\",\n", " \"insurance\",\n", " \"king\",\n", "]\n", "\n", "\n", "method2exp = {\n", " \"real\": \"exp/{}/ddpm_cb_best/\",\n", " \"tab-ddpm\": \"exp/{}/ddpm_cb_best/\",\n", " \"smote\": \"exp/{}/smote/\",\n", " \"ctabgan+\": \"exp/{}/ctabgan-plus/\",\n", " \"ctabgan\": \"exp/{}/ctabgan/\",\n", " \"tvae\": \"exp/{}/tvae/\"\n", "}\n", "\n", "eval_file = \"eval_catboost.json\"\n", "show_std = False\n", "df = pd.DataFrame(columns=[\"method\"] + [_[:3].upper() for _ in DATASETS])\n", "\n", "for algo in method2exp: \n", " algo_res = []\n", " for ds in DATASETS:\n", " if not os.path.exists(os.path.join(method2exp[algo].format(ds), eval_file)):\n", " algo_res.append(\"--\")\n", " continue\n", " metric = \"r2\" if ds in _REGRESSION else \"f1\"\n", " res_dict = lib.load_json(os.path.join(method2exp[algo].format(ds), eval_file))\n", "\n", " if algo == \"real\":\n", " res = f'{res_dict[\"real\"][\"test\"][metric + \"-mean\"]:.4f}' \n", " if show_std: res += f'+-{res_dict[\"real\"][\"test\"][metric + \"-std\"]:.4f}'\n", " else:\n", " res = f'{res_dict[\"synthetic\"][\"test\"][metric + \"-mean\"]:.4f}'\n", " if show_std: res += f'+-{res_dict[\"synthetic\"][\"test\"][metric + \"-std\"]:.4f}'\n", "\n", " algo_res.append(res)\n", " df.loc[len(df)] = [algo] + algo_res" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>method</th>\n", " <th>ABA</th>\n", " <th>ADU</th>\n", " <th>BUD</th>\n", " <th>CAL</th>\n", " <th>CAR</th>\n", " <th>CHU</th>\n", " <th>DEF</th>\n", " <th>DIA</th>\n", " <th>FB-</th>\n", " <th>GES</th>\n", " <th>HIG</th>\n", " <th>HOU</th>\n", " <th>INS</th>\n", " <th>KIN</th>\n", " <th>MIN</th>\n", " <th>WIL</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>real</td>\n", " <td>0.5562</td>\n", " <td>0.8152</td>\n", " <td>0.9063</td>\n", " <td>0.8568</td>\n", " <td>0.7379</td>\n", " <td>0.7403</td>\n", " <td>0.6880</td>\n", " <td>0.7849</td>\n", " <td>0.8371</td>\n", " <td>0.6365</td>\n", " <td>0.7238</td>\n", " <td>0.6616</td>\n", " <td>0.8137</td>\n", " <td>0.9070</td>\n", " <td>0.9342</td>\n", " <td>0.8982</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>tab-ddpm</td>\n", " <td>0.5499</td>\n", " <td>0.7951</td>\n", " <td>0.9057</td>\n", " <td>0.8362</td>\n", " <td>0.7374</td>\n", " <td>0.7548</td>\n", " <td>0.6910</td>\n", " <td>0.7398</td>\n", " <td>0.7128</td>\n", " <td>0.5967</td>\n", " <td>0.7218</td>\n", " <td>0.6766</td>\n", " <td>0.8092</td>\n", " <td>0.8331</td>\n", " <td>0.9362</td>\n", " <td>0.9045</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>smote</td>\n", " <td>0.5486</td>\n", " <td>0.7912</td>\n", " <td>0.8906</td>\n", " <td>0.8397</td>\n", " <td>0.7323</td>\n", " <td>0.7432</td>\n", " <td>0.6930</td>\n", " <td>0.6835</td>\n", " <td>0.8035</td>\n", " <td>0.6579</td>\n", " <td>0.7219</td>\n", " <td>0.6625</td>\n", " <td>0.8119</td>\n", " <td>0.8416</td>\n", " <td>0.9323</td>\n", " <td>0.9127</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>ctabgan+</td>\n", " <td>0.4672</td>\n", " <td>0.7724</td>\n", " <td>0.8844</td>\n", " <td>0.5247</td>\n", " <td>0.7327</td>\n", " <td>0.7024</td>\n", " <td>0.6865</td>\n", " <td>0.7339</td>\n", " <td>0.5088</td>\n", " <td>0.4055</td>\n", " <td>0.6639</td>\n", " <td>0.5040</td>\n", " <td>0.7966</td>\n", " <td>0.4438</td>\n", " <td>0.8920</td>\n", " <td>0.7983</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>ctabgan</td>\n", " <td>--</td>\n", " <td>0.7831</td>\n", " <td>0.8552</td>\n", " <td>--</td>\n", " <td>0.7171</td>\n", " <td>0.6875</td>\n", " <td>0.6437</td>\n", " <td>0.7310</td>\n", " <td>--</td>\n", " <td>0.3922</td>\n", " <td>0.5748</td>\n", " <td>--</td>\n", " <td>--</td>\n", " <td>--</td>\n", " <td>0.8892</td>\n", " <td>0.9060</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>tvae</td>\n", " <td>0.4328</td>\n", " <td>0.7810</td>\n", " <td>0.8638</td>\n", " <td>0.7518</td>\n", " <td>0.7174</td>\n", " <td>0.7317</td>\n", " <td>0.6564</td>\n", " <td>0.7136</td>\n", " <td>0.6853</td>\n", " <td>0.4340</td>\n", " <td>0.6378</td>\n", " <td>0.4926</td>\n", " <td>0.7842</td>\n", " <td>0.8238</td>\n", " <td>0.9125</td>\n", " <td>0.5006</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " method ABA ADU BUD CAL CAR CHU DEF DIA \\\n", "0 real 0.5562 0.8152 0.9063 0.8568 0.7379 0.7403 0.6880 0.7849 \n", "1 tab-ddpm 0.5499 0.7951 0.9057 0.8362 0.7374 0.7548 0.6910 0.7398 \n", "2 smote 0.5486 0.7912 0.8906 0.8397 0.7323 0.7432 0.6930 0.6835 \n", "3 ctabgan+ 0.4672 0.7724 0.8844 0.5247 0.7327 0.7024 0.6865 0.7339 \n", "4 ctabgan -- 0.7831 0.8552 -- 0.7171 0.6875 0.6437 0.7310 \n", "5 tvae 0.4328 0.7810 0.8638 0.7518 0.7174 0.7317 0.6564 0.7136 \n", "\n", " FB- GES HIG HOU INS KIN MIN WIL \n", "0 0.8371 0.6365 0.7238 0.6616 0.8137 0.9070 0.9342 0.8982 \n", "1 0.7128 0.5967 0.7218 0.6766 0.8092 0.8331 0.9362 0.9045 \n", "2 0.8035 0.6579 0.7219 0.6625 0.8119 0.8416 0.9323 0.9127 \n", "3 0.5088 0.4055 0.6639 0.5040 0.7966 0.4438 0.8920 0.7983 \n", "4 -- 0.3922 0.5748 -- -- -- 0.8892 0.9060 \n", "5 0.6853 0.4340 0.6378 0.4926 0.7842 0.8238 0.9125 0.5006 " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3.9.7 ('base')", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "a06af253165e97d0c1e75e8bf6d3252013856f30b8177e11b02d3fa36c37333d" } } }, "nbformat": 4, "nbformat_minor": 2}123456789101112import torchfrom icecream import install
torch.set_num_threads(1)install()
from . import env # noqafrom .data import * # noqafrom .deep import * # noqafrom .env import * # noqafrom .metrics import * # noqafrom .util import * # noqa123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719import hashlibfrom collections import Counterfrom copy import deepcopyfrom dataclasses import astuple, dataclass, replacefrom importlib.resources import pathfrom pathlib import Pathfrom typing import Any, Literal, Optional, Union, cast, Tuple, Dict, List
import numpy as npimport pandas as pdfrom sklearn.model_selection import train_test_splitfrom sklearn.pipeline import make_pipelineimport sklearn.preprocessingimport torchimport osfrom category_encoders import LeaveOneOutEncoderfrom sklearn.impute import SimpleImputerfrom sklearn.preprocessing import StandardScalerfrom scipy.spatial.distance import cdist
from . import env, utilfrom .metrics import calculate_metrics as calculate_metrics_from .util import TaskType, load_json
ArrayDict = Dict[str, np.ndarray]TensorDict = Dict[str, torch.Tensor]
CAT_MISSING_VALUE = '__nan__'CAT_RARE_VALUE = '__rare__'Normalization = Literal['standard', 'quantile', 'minmax']NumNanPolicy = Literal['drop-rows', 'mean']CatNanPolicy = Literal['most_frequent']CatEncoding = Literal['one-hot', 'counter']YPolicy = Literal['default']
class StandardScaler1d(StandardScaler): def partial_fit(self, X, *args, **kwargs): assert X.ndim == 1 return super().partial_fit(X[:, None], *args, **kwargs)
def transform(self, X, *args, **kwargs): assert X.ndim == 1 return super().transform(X[:, None], *args, **kwargs).squeeze(1)
def inverse_transform(self, X, *args, **kwargs): assert X.ndim == 1 return super().inverse_transform(X[:, None], *args, **kwargs).squeeze(1)
def get_category_sizes(X: Union[torch.Tensor, np.ndarray]) -> List[int]: """Return K[i] s.t. F.one_hot(x[:,i], K[i]) is valid. Requires K[i] > max(x[:,i]).""" XT = X.T.cpu().tolist() if isinstance(X, torch.Tensor) else X.T.tolist() return [int(np.max(x)) + 1 if len(x) > 0 else 0 for x in XT]
@dataclass(frozen=False)class Dataset: X_num: Optional[ArrayDict] X_cat: Optional[ArrayDict] y: ArrayDict y_info: Dict[str, Any] task_type: TaskType n_classes: Optional[int]
@classmethod def from_dir(cls, dir_: Union[Path, str]) -> 'Dataset': dir_ = Path(dir_) splits = [k for k in ['train', 'val', 'test'] if dir_.joinpath(f'y_{k}.npy').exists()]
def load(item) -> ArrayDict: return { x: cast(np.ndarray, np.load(dir_ / f'{item}_{x}.npy', allow_pickle=True)) # type: ignore[code] for x in splits }
if Path(dir_ / 'info.json').exists(): info = util.load_json(dir_ / 'info.json') else: info = None return Dataset( load('X_num') if dir_.joinpath('X_num_train.npy').exists() else None, load('X_cat') if dir_.joinpath('X_cat_train.npy').exists() else None, load('y'), {}, TaskType(info['task_type']), info.get('n_classes'), )
@property def is_binclass(self) -> bool: return self.task_type == TaskType.BINCLASS
@property def is_multiclass(self) -> bool: return self.task_type == TaskType.MULTICLASS
@property def is_regression(self) -> bool: return self.task_type == TaskType.REGRESSION
@property def n_num_features(self) -> int: return 0 if self.X_num is None else self.X_num['train'].shape[1]
@property def n_cat_features(self) -> int: return 0 if self.X_cat is None else self.X_cat['train'].shape[1]
@property def n_features(self) -> int: return self.n_num_features + self.n_cat_features
def size(self, part: Optional[str]) -> int: return sum(map(len, self.y.values())) if part is None else len(self.y[part])
@property def nn_output_dim(self) -> int: if self.is_multiclass: assert self.n_classes is not None return self.n_classes else: return 1
def get_category_sizes(self, part: str) -> List[int]: return [] if self.X_cat is None else get_category_sizes(self.X_cat[part])
def calculate_metrics( self, predictions: Dict[str, np.ndarray], prediction_type: Optional[str], ) -> Dict[str, Any]: metrics = { x: calculate_metrics_( self.y[x], predictions[x], self.task_type, prediction_type, self.y_info ) for x in predictions } if self.task_type == TaskType.REGRESSION: score_key = 'rmse' score_sign = -1 else: score_key = 'accuracy' score_sign = 1 for part_metrics in metrics.values(): part_metrics['score'] = score_sign * part_metrics[score_key] return metrics
def change_val(dataset: Dataset, val_size: float = 0.2): # should be done before transformations
y = np.concatenate([dataset.y['train'], dataset.y['val']], axis=0)
ixs = np.arange(y.shape[0]) if dataset.is_regression: train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777) else: train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
dataset.y['train'] = y[train_ixs] dataset.y['val'] = y[val_ixs]
if dataset.X_num is not None: X_num = np.concatenate([dataset.X_num['train'], dataset.X_num['val']], axis=0) dataset.X_num['train'] = X_num[train_ixs] dataset.X_num['val'] = X_num[val_ixs]
if dataset.X_cat is not None: X_cat = np.concatenate([dataset.X_cat['train'], dataset.X_cat['val']], axis=0) dataset.X_cat['train'] = X_cat[train_ixs] dataset.X_cat['val'] = X_cat[val_ixs]
return dataset
def num_process_nans(dataset: Dataset, policy: Optional[NumNanPolicy]) -> Dataset: assert dataset.X_num is not None nan_masks = {k: np.isnan(v) for k, v in dataset.X_num.items()} if not any(x.any() for x in nan_masks.values()): # type: ignore[code] assert policy is None return dataset
assert policy is not None if policy == 'drop-rows': valid_masks = {k: ~v.any(1) for k, v in nan_masks.items()} assert valid_masks[ 'test' ].all(), 'Cannot drop test rows, since this will affect the final metrics.' new_data = {} for data_name in ['X_num', 'X_cat', 'y']: data_dict = getattr(dataset, data_name) if data_dict is not None: new_data[data_name] = { k: v[valid_masks[k]] for k, v in data_dict.items() } dataset = replace(dataset, **new_data) elif policy == 'mean': new_values = np.nanmean(dataset.X_num['train'], axis=0) X_num = deepcopy(dataset.X_num) for k, v in X_num.items(): num_nan_indices = np.where(nan_masks[k]) v[num_nan_indices] = np.take(new_values, num_nan_indices[1]) dataset = replace(dataset, X_num=X_num) else: assert util.raise_unknown('policy', policy) return dataset
# Inspired by: https://github.com/yandex-research/rtdl/blob/a4c93a32b334ef55d2a0559a4407c8306ffeeaee/lib/data.py#L20def normalize( X: ArrayDict, normalization: Normalization, seed: Optional[int], return_normalizer : bool = False) -> ArrayDict: X_train = X['train'] if normalization == 'standard': normalizer = sklearn.preprocessing.StandardScaler() elif normalization == 'minmax': normalizer = sklearn.preprocessing.MinMaxScaler() elif normalization == 'quantile': normalizer = sklearn.preprocessing.QuantileTransformer( output_distribution='normal', n_quantiles=max(min(X['train'].shape[0] // 30, 1000), 10), subsample=int(1e9), random_state=seed, ) # noise = 1e-3 # if noise > 0: # assert seed is not None # stds = np.std(X_train, axis=0, keepdims=True) # noise_std = noise / np.maximum(stds, noise) # type: ignore[code] # X_train = X_train + noise_std * np.random.default_rng(seed).standard_normal( # X_train.shape # ) else: util.raise_unknown('normalization', normalization) normalizer.fit(X_train) if return_normalizer: return {k: normalizer.transform(v) for k, v in X.items()}, normalizer return {k: normalizer.transform(v) for k, v in X.items()}
def cat_process_nans(X: ArrayDict, policy: Optional[CatNanPolicy]) -> ArrayDict: assert X is not None nan_masks = {k: np.asarray(v == CAT_MISSING_VALUE) for k, v in X.items()} if any(np.asarray(x).any() for x in nan_masks.values()): # type: ignore[code] if policy is None: X_new = X elif policy == 'most_frequent': imputer = SimpleImputer(missing_values=CAT_MISSING_VALUE, strategy=policy) # type: ignore[code] imputer.fit(X['train']) X_new = {k: cast(np.ndarray, imputer.transform(v)) for k, v in X.items()} else: util.raise_unknown('categorical NaN policy', policy) else: assert policy is None X_new = X return X_new
def cat_drop_rare(X: ArrayDict, min_frequency: float) -> ArrayDict: assert 0.0 < min_frequency < 1.0 min_count = round(len(X['train']) * min_frequency) X_new = {x: [] for x in X} for column_idx in range(X['train'].shape[1]): counter = Counter(X['train'][:, column_idx].tolist()) popular_categories = {k for k, v in counter.items() if v >= min_count} for part in X_new: X_new[part].append( [ (x if x in popular_categories else CAT_RARE_VALUE) for x in X[part][:, column_idx].tolist() ] ) return {k: np.array(v).T for k, v in X_new.items()}
def cat_encode( X: ArrayDict, encoding: Optional[CatEncoding], y_train: Optional[np.ndarray], seed: Optional[int], return_encoder : bool = False) -> Tuple[ArrayDict, bool, Optional[Any]]: # (X, is_converted_to_numerical) if encoding != 'counter': y_train = None
# Step 1. Map strings to 0-based ranges
if encoding is None: unknown_value = np.iinfo('int64').max - 3 oe = sklearn.preprocessing.OrdinalEncoder( handle_unknown='use_encoded_value', # type: ignore[code] unknown_value=unknown_value, # type: ignore[code] dtype='int64', # type: ignore[code] ).fit(X['train']) encoder = make_pipeline(oe) encoder.fit(X['train']) X = {k: encoder.transform(v) for k, v in X.items()} max_values = X['train'].max(axis=0) for part in X.keys(): if part == 'train': continue for column_idx in range(X[part].shape[1]): X[part][X[part][:, column_idx] == unknown_value, column_idx] = ( max_values[column_idx] + 1 ) if return_encoder: return (X, False, encoder) return (X, False)
# Step 2. Encode.
elif encoding == 'one-hot': ohe = sklearn.preprocessing.OneHotEncoder( handle_unknown='ignore', sparse=False, dtype=np.float32 # type: ignore[code] ) encoder = make_pipeline(ohe)
# encoder.steps.append(('ohe', ohe)) encoder.fit(X['train']) X = {k: encoder.transform(v) for k, v in X.items()} elif encoding == 'counter': assert y_train is not None assert seed is not None loe = LeaveOneOutEncoder(sigma=0.1, random_state=seed, return_df=False) encoder.steps.append(('loe', loe)) encoder.fit(X['train'], y_train) X = {k: encoder.transform(v).astype('float32') for k, v in X.items()} # type: ignore[code] if not isinstance(X['train'], pd.DataFrame): X = {k: v.values for k, v in X.items()} # type: ignore[code] else: util.raise_unknown('encoding', encoding) if return_encoder: return X, True, encoder # type: ignore[code] return (X, True)
def build_target( y: ArrayDict, policy: Optional[YPolicy], task_type: TaskType) -> Tuple[ArrayDict, Dict[str, Any]]: info: Dict[str, Any] = {'policy': policy} if policy is None: pass elif policy == 'default': if task_type == TaskType.REGRESSION: mean, std = float(y['train'].mean()), float(y['train'].std()) y = {k: (v - mean) / std for k, v in y.items()} info['mean'] = mean info['std'] = std else: util.raise_unknown('policy', policy) return y, info
@dataclass(frozen=True)class Transformations: seed: int = 0 normalization: Optional[Normalization] = None num_nan_policy: Optional[NumNanPolicy] = None cat_nan_policy: Optional[CatNanPolicy] = None cat_min_frequency: Optional[float] = None cat_encoding: Optional[CatEncoding] = None y_policy: Optional[YPolicy] = 'default'
def transform_dataset( dataset: Dataset, transformations: Transformations, cache_dir: Optional[Path], return_transforms: bool = False) -> Dataset: # WARNING: the order of transformations matters. Moreover, the current # implementation is not ideal in that sense. if cache_dir is not None: transformations_md5 = hashlib.md5( str(transformations).encode('utf-8') ).hexdigest() transformations_str = '__'.join(map(str, astuple(transformations))) cache_path = ( cache_dir / f'cache__{transformations_str}__{transformations_md5}.pickle' ) if cache_path.exists(): cache_transformations, value = util.load_pickle(cache_path) if transformations == cache_transformations: print( f"Using cached features: {cache_dir.name + '/' + cache_path.name}" ) return value else: raise RuntimeError(f'Hash collision for {cache_path}') else: cache_path = None
if dataset.X_num is not None: dataset = num_process_nans(dataset, transformations.num_nan_policy)
num_transform = None cat_transform = None X_num = dataset.X_num
if X_num is not None and transformations.normalization is not None: X_num, num_transform = normalize( X_num, transformations.normalization, transformations.seed, return_normalizer=True ) num_transform = num_transform if dataset.X_cat is None: assert transformations.cat_nan_policy is None assert transformations.cat_min_frequency is None # assert transformations.cat_encoding is None X_cat = None else: X_cat = cat_process_nans(dataset.X_cat, transformations.cat_nan_policy) if transformations.cat_min_frequency is not None: X_cat = cat_drop_rare(X_cat, transformations.cat_min_frequency) X_cat, is_num, cat_transform = cat_encode( X_cat, transformations.cat_encoding, dataset.y['train'], transformations.seed, return_encoder=True ) if is_num: X_num = ( X_cat if X_num is None else {x: np.hstack([X_num[x], X_cat[x]]) for x in X_num} ) X_cat = None
y, y_info = build_target(dataset.y, transformations.y_policy, dataset.task_type)
dataset = replace(dataset, X_num=X_num, X_cat=X_cat, y=y, y_info=y_info) dataset.num_transform = num_transform dataset.cat_transform = cat_transform
if cache_path is not None: util.dump_pickle((transformations, dataset), cache_path) # if return_transforms: # return dataset, num_transform, cat_transform return dataset
def build_dataset( path: Union[str, Path], transformations: Transformations, cache: bool) -> Dataset: path = Path(path) dataset = Dataset.from_dir(path) return transform_dataset(dataset, transformations, path if cache else None)
def prepare_tensors( dataset: Dataset, device: Union[str, torch.device]) -> Tuple[Optional[TensorDict], Optional[TensorDict], TensorDict]: X_num, X_cat, Y = ( None if x is None else {k: torch.as_tensor(v) for k, v in x.items()} for x in [dataset.X_num, dataset.X_cat, dataset.y] ) if device.type != 'cpu': X_num, X_cat, Y = ( None if x is None else {k: v.to(device) for k, v in x.items()} for x in [X_num, X_cat, Y] ) assert X_num is not None assert Y is not None if not dataset.is_multiclass: Y = {k: v.float() for k, v in Y.items()} return X_num, X_cat, Y
################# DataLoader#################
class TabDataset(torch.utils.data.Dataset): def __init__( self, dataset : Dataset, split : Literal['train', 'val', 'test'] ): super().__init__() self.X_num = torch.from_numpy(dataset.X_num[split]) if dataset.X_num is not None else None self.X_cat = torch.from_numpy(dataset.X_cat[split]) if dataset.X_cat is not None else None self.y = torch.from_numpy(dataset.y[split])
assert self.y is not None assert self.X_num is not None or self.X_cat is not None
def __len__(self): return len(self.y)
def __getitem__(self, idx): out_dict = { 'y': self.y[idx].long() if self.y is not None else None, }
x = np.empty((0,)) if self.X_num is not None: x = self.X_num[idx] if self.X_cat is not None: x = torch.cat([x, self.X_cat[idx]], dim=0) return x.float(), out_dict
def prepare_dataloader( dataset : Dataset, split : str, batch_size: int,):
torch_dataset = TabDataset(dataset, split) loader = torch.utils.data.DataLoader( torch_dataset, batch_size=batch_size, shuffle=(split == 'train'), num_workers=1, ) while True: yield from loader
def prepare_torch_dataloader( dataset : Dataset, split : str, shuffle : bool, batch_size: int,) -> torch.utils.data.DataLoader:
torch_dataset = TabDataset(dataset, split) loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=1)
return loader
def dataset_from_csv(paths : Dict[str, str], cat_features, target, T): assert 'train' in paths y = {} X_num = {} X_cat = {} if len(cat_features) else None for split in paths.keys(): df = pd.read_csv(paths[split]) y[split] = df[target].to_numpy().astype(float) if X_cat is not None: X_cat[split] = df[cat_features].to_numpy().astype(str) X_num[split] = df.drop(cat_features + [target], axis=1).to_numpy().astype(float)
dataset = Dataset(X_num, X_cat, y, {}, None, len(np.unique(y['train']))) return transform_dataset(dataset, T, None)
class FastTensorDataLoader: """ A DataLoader-like object for a set of tensors that can be much faster than TensorDataset + DataLoader because dataloader grabs individual indices of the dataset and calls cat (slow). Source: https://discuss.pytorch.org/t/dataloader-much-slower-than-manual-batching/27014/6 """ def __init__(self, *tensors, batch_size=32, shuffle=False): """ Initialize a FastTensorDataLoader. :param *tensors: tensors to store. Must have the same length @ dim 0. :param batch_size: batch size to load. :param shuffle: if True, shuffle the data *in-place* whenever an iterator is created out of this object. :returns: A FastTensorDataLoader. """ assert all(t.shape[0] == tensors[0].shape[0] for t in tensors) self.tensors = tensors
self.dataset_len = self.tensors[0].shape[0] self.batch_size = batch_size self.shuffle = shuffle
# Calculate # batches n_batches, remainder = divmod(self.dataset_len, self.batch_size) if remainder > 0: n_batches += 1 self.n_batches = n_batches def __iter__(self): if self.shuffle: r = torch.randperm(self.dataset_len) self.tensors = [t[r] for t in self.tensors] self.i = 0 return self
def __next__(self): if self.i >= self.dataset_len: raise StopIteration batch = tuple(t[self.i:self.i+self.batch_size] for t in self.tensors) self.i += self.batch_size return batch
def __len__(self): return self.n_batches
def prepare_fast_dataloader( D : Dataset, split : str, batch_size: int): if D.X_cat is not None: if D.X_num is not None: X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float() else: X = torch.from_numpy(D.X_cat[split]).float() else: X = torch.from_numpy(D.X_num[split]).float() y = torch.from_numpy(D.y[split]) dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train')) while True: yield from dataloader
def prepare_fast_torch_dataloader( D : Dataset, split : str, batch_size: int): if D.X_cat is not None: X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float() else: X = torch.from_numpy(D.X_num[split]).float() y = torch.from_numpy(D.y[split]) dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train')) return dataloader
def round_columns(X_real, X_synth, columns): for col in columns: uniq = np.unique(X_real[:,col]) dist = cdist(X_synth[:, col][:, np.newaxis].astype(float), uniq[:, np.newaxis].astype(float)) X_synth[:, col] = uniq[dist.argmin(axis=1)] return X_synth
def concat_features(D : Dataset): if D.X_num is None: assert D.X_cat is not None X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_cat.items()} elif D.X_cat is None: assert D.X_num is not None X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_num.items()} else: X = { part: pd.concat( [ pd.DataFrame(D.X_num[part], columns=range(D.n_num_features)), pd.DataFrame( D.X_cat[part], columns=range(D.n_num_features, D.n_features), ), ], axis=1, ) for part in D.y.keys() }
return X
def concat_to_pd(X_num, X_cat, y): if X_num is None: return pd.concat([ pd.DataFrame(X_cat, columns=list(range(X_cat.shape[1]))), pd.DataFrame(y, columns=['y']) ], axis=1) if X_cat is not None: return pd.concat([ pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))), pd.DataFrame(X_cat, columns=list(range(X_num.shape[1], X_num.shape[1] + X_cat.shape[1]))), pd.DataFrame(y, columns=['y']) ], axis=1) return pd.concat([ pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))), pd.DataFrame(y, columns=['y']) ], axis=1)
def read_pure_data(path, split='train'): y = np.load(os.path.join(path, f'y_{split}.npy'), allow_pickle=True) X_num = None X_cat = None if os.path.exists(os.path.join(path, f'X_num_{split}.npy')): X_num = np.load(os.path.join(path, f'X_num_{split}.npy'), allow_pickle=True) if os.path.exists(os.path.join(path, f'X_cat_{split}.npy')): X_cat = np.load(os.path.join(path, f'X_cat_{split}.npy'), allow_pickle=True)
return X_num, X_cat, y
def read_changed_val(path, val_size=0.2): path = Path(path) X_num_train, X_cat_train, y_train = read_pure_data(path, 'train') X_num_val, X_cat_val, y_val = read_pure_data(path, 'val') is_regression = load_json(path / 'info.json')['task_type'] == 'regression'
y = np.concatenate([y_train, y_val], axis=0)
ixs = np.arange(y.shape[0]) if is_regression: train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777) else: train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y) y_train = y[train_ixs] y_val = y[val_ixs]
if X_num_train is not None: X_num = np.concatenate([X_num_train, X_num_val], axis=0) X_num_train = X_num[train_ixs] X_num_val = X_num[val_ixs]
if X_cat_train is not None: X_cat = np.concatenate([X_cat_train, X_cat_val], axis=0) X_cat_train = X_cat[train_ixs] X_cat_val = X_cat[val_ixs] return X_num_train, X_cat_train, y_train, X_num_val, X_cat_val, y_val
#############
def load_dataset_info(dataset_dir_name: str) -> Dict[str, Any]: path = Path("data/" + dataset_dir_name) info = util.load_json(path / 'info.json') info['size'] = info['train_size'] + info['val_size'] + info['test_size'] info['n_features'] = info['n_num_features'] + info['n_cat_features'] info['path'] = path return info123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168import statisticsfrom dataclasses import dataclassfrom typing import Any, Callable, Literal, cast
import rtdlimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.optim as optimimport zerofrom torch import Tensor
from .util import TaskType
def cos_sin(x: Tensor) -> Tensor: return torch.cat([torch.cos(x), torch.sin(x)], -1)
@dataclassclass PeriodicOptions: n: int # the output size is 2 * n sigma: float trainable: bool initialization: Literal['log-linear', 'normal']
class Periodic(nn.Module): def __init__(self, n_features: int, options: PeriodicOptions) -> None: super().__init__() if options.initialization == 'log-linear': coefficients = options.sigma ** (torch.arange(options.n) / options.n) coefficients = coefficients[None].repeat(n_features, 1) else: assert options.initialization == 'normal' coefficients = torch.normal(0.0, options.sigma, (n_features, options.n)) if options.trainable: self.coefficients = nn.Parameter(coefficients) # type: ignore[code] else: self.register_buffer('coefficients', coefficients)
def forward(self, x: Tensor) -> Tensor: assert x.ndim == 2 return cos_sin(2 * torch.pi * self.coefficients[None] * x[..., None])
def get_n_parameters(m: nn.Module): return sum(x.numel() for x in m.parameters() if x.requires_grad)
def get_loss_fn(task_type: TaskType) -> Callable[..., Tensor]: return ( F.binary_cross_entropy_with_logits if task_type == TaskType.BINCLASS else F.cross_entropy if task_type == TaskType.MULTICLASS else F.mse_loss )
def default_zero_weight_decay_condition(module_name, module, parameter_name, parameter): del module_name, parameter return parameter_name.endswith('bias') or isinstance( module, ( nn.BatchNorm1d, nn.LayerNorm, nn.InstanceNorm1d, rtdl.CLSToken, rtdl.NumericalFeatureTokenizer, rtdl.CategoricalFeatureTokenizer, Periodic, ), )
def split_parameters_by_weight_decay( model: nn.Module, zero_weight_decay_condition=default_zero_weight_decay_condition) -> list[dict[str, Any]]: parameters_info = {} for module_name, module in model.named_modules(): for parameter_name, parameter in module.named_parameters(): full_parameter_name = ( f'{module_name}.{parameter_name}' if module_name else parameter_name ) parameters_info.setdefault(full_parameter_name, ([], parameter))[0].append( zero_weight_decay_condition( module_name, module, parameter_name, parameter ) ) params_with_wd = {'params': []} params_without_wd = {'params': [], 'weight_decay': 0.0} for full_parameter_name, (results, parameter) in parameters_info.items(): (params_without_wd if any(results) else params_with_wd)['params'].append( parameter ) return [params_with_wd, params_without_wd]
def make_optimizer( config: dict[str, Any], parameter_groups,) -> optim.Optimizer: if config['optimizer'] == 'FT-Transformer-default': return optim.AdamW(parameter_groups, lr=1e-4, weight_decay=1e-5) return getattr(optim, config['optimizer'])( parameter_groups, **{x: config[x] for x in ['lr', 'weight_decay', 'momentum'] if x in config}, )
def get_lr(optimizer: optim.Optimizer) -> float: return next(iter(optimizer.param_groups))['lr']
def is_oom_exception(err: RuntimeError) -> bool: return any( x in str(err) for x in [ 'CUDA out of memory', 'CUBLAS_STATUS_ALLOC_FAILED', 'CUDA error: out of memory', ] )
def train_with_auto_virtual_batch( optimizer, loss_fn, step, batch, chunk_size: int,) -> tuple[Tensor, int]: batch_size = len(batch) random_state = zero.random.get_state() loss = None while chunk_size != 0: try: zero.random.set_state(random_state) optimizer.zero_grad() if batch_size <= chunk_size: loss = loss_fn(*step(batch)) loss.backward() else: loss = None for chunk in zero.iter_batches(batch, chunk_size): chunk_loss = loss_fn(*step(chunk)) chunk_loss = chunk_loss * (len(chunk) / batch_size) chunk_loss.backward() if loss is None: loss = chunk_loss.detach() else: loss += chunk_loss.detach() except RuntimeError as err: if not is_oom_exception(err): raise chunk_size //= 2 else: break if not chunk_size: raise RuntimeError('Not enough memory even for batch_size=1') optimizer.step() return cast(Tensor, loss), chunk_size
def process_epoch_losses(losses: list[Tensor]) -> tuple[list[float], float]: losses_ = torch.stack(losses).tolist() return losses_, statistics.mean(losses_)123456789101112131415161718192021222324252627282930313233343536373839"""Have not used in TabDDPM project."""
import datetimeimport osimport shutilimport typing as tyfrom pathlib import Path
PROJ = Path('tab-ddpm/').absolute().resolve()EXP = PROJ / 'exp'DATA = PROJ / 'data'
def get_path(path: ty.Union[str, Path]) -> Path: if isinstance(path, str): path = Path(path) if not path.is_absolute(): path = PROJ / path return path.resolve()
def get_relative_path(path: ty.Union[str, Path]) -> Path: return get_path(path).relative_to(PROJ)
def duplicate_path( src: ty.Union[str, Path], alternative_project_dir: ty.Union[str, Path]) -> None: src = get_path(src) alternative_project_dir = get_path(alternative_project_dir) dst = alternative_project_dir / src.relative_to(PROJ) dst.parent.mkdir(parents=True, exist_ok=True) if dst.exists(): dst = dst.with_name( dst.name + '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S') ) (shutil.copytree if src.is_dir() else shutil.copyfile)(src, dst)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158import enumfrom typing import Any, Optional, Tuple, Dict, Union, castfrom functools import partial
import numpy as npimport scipy.specialimport sklearn.metrics as skm
from . import utilfrom .util import TaskType
class PredictionType(enum.Enum): LOGITS = 'logits' PROBS = 'probs'
class MetricsReport: def __init__(self, report: dict, task_type: TaskType): self._res = {k: {} for k in report.keys()} if task_type in (TaskType.BINCLASS, TaskType.MULTICLASS): self._metrics_names = ["acc", "f1"] for k in report.keys(): self._res[k]["acc"] = report[k]["accuracy"] self._res[k]["f1"] = report[k]["macro avg"]["f1-score"] if task_type == TaskType.BINCLASS: self._res[k]["roc_auc"] = report[k]["roc_auc"] self._metrics_names.append("roc_auc")
elif task_type == TaskType.REGRESSION: self._metrics_names = ["r2", "rmse"] for k in report.keys(): self._res[k]["r2"] = report[k]["r2"] self._res[k]["rmse"] = report[k]["rmse"] else: raise "Unknown TaskType!"
def get_splits_names(self) -> list[str]: return self._res.keys()
def get_metrics_names(self) -> list[str]: return self._metrics_names
def get_metric(self, split: str, metric: str) -> float: return self._res[split][metric]
def get_val_score(self) -> float: return self._res["val"]["r2"] if "r2" in self._res["val"] else self._res["val"]["f1"] def get_test_score(self) -> float: return self._res["test"]["r2"] if "r2" in self._res["test"] else self._res["test"]["f1"] def print_metrics(self) -> None: res = { "val": {k: np.around(self._res["val"][k], 4) for k in self._res["val"]}, "test": {k: np.around(self._res["test"][k], 4) for k in self._res["test"]} } print("*"*100) print("[val]") print(res["val"]) print("[test]") print(res["test"])
return res
class SeedsMetricsReport: def __init__(self): self._reports = []
def add_report(self, report: MetricsReport) -> None: self._reports.append(report) def get_mean_std(self) -> dict: res = {k: {} for k in ["train", "val", "test"]} for split in self._reports[0].get_splits_names(): for metric in self._reports[0].get_metrics_names(): res[split][metric] = [x.get_metric(split, metric) for x in self._reports]
agg_res = {k: {} for k in ["train", "val", "test"]} for split in self._reports[0].get_splits_names(): for metric in self._reports[0].get_metrics_names(): for k, f in [("count", len), ("mean", np.mean), ("std", np.std)]: agg_res[split][f"{metric}-{k}"] = f(res[split][metric]) self._res = res self._agg_res = agg_res
return agg_res
def print_result(self) -> dict: res = {split: {k: float(np.around(self._agg_res[split][k], 4)) for k in self._agg_res[split]} for split in ["val", "test"]} print("="*100) print("EVAL RESULTS:") print("[val]") print(res["val"]) print("[test]") print(res["test"]) print("="*100) return res
def calculate_rmse( y_true: np.ndarray, y_pred: np.ndarray, std: Optional[float]) -> float: rmse = skm.mean_squared_error(y_true, y_pred) ** 0.5 if std is not None: rmse *= std return rmse
def _get_labels_and_probs( y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType]) -> Tuple[np.ndarray, Optional[np.ndarray]]: assert task_type in (TaskType.BINCLASS, TaskType.MULTICLASS)
if prediction_type is None: return y_pred, None
if prediction_type == PredictionType.LOGITS: probs = ( scipy.special.expit(y_pred) if task_type == TaskType.BINCLASS else scipy.special.softmax(y_pred, axis=1) ) elif prediction_type == PredictionType.PROBS: probs = y_pred else: util.raise_unknown('prediction_type', prediction_type)
assert probs is not None labels = np.round(probs) if task_type == TaskType.BINCLASS else probs.argmax(axis=1) return labels.astype('int64'), probs
def calculate_metrics( y_true: np.ndarray, y_pred: np.ndarray, task_type: Union[str, TaskType], prediction_type: Optional[Union[str, PredictionType]], y_info: Dict[str, Any],) -> Dict[str, Any]: # Example: calculate_metrics(y_true, y_pred, 'binclass', 'logits', {}) task_type = TaskType(task_type) if prediction_type is not None: prediction_type = PredictionType(prediction_type)
if task_type == TaskType.REGRESSION: assert prediction_type is None assert 'std' in y_info rmse = calculate_rmse(y_true, y_pred, y_info['std']) r2 = skm.r2_score(y_true, y_pred) result = {'rmse': rmse, 'r2': r2} else: labels, probs = _get_labels_and_probs(y_pred, task_type, prediction_type) result = cast( Dict[str, Any], skm.classification_report(y_true, labels, output_dict=True) ) if task_type == TaskType.BINCLASS: result['roc_auc'] = skm.roc_auc_score(y_true, probs) return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433import argparseimport atexitimport enumimport jsonimport osimport pickleimport shutilimport sysimport timeimport uuidfrom copy import deepcopyfrom dataclasses import asdict, fields, is_dataclassfrom pathlib import Pathfrom pprint import pprintfrom typing import Any, Callable, List, Dict, Type, Optional, Tuple, TypeVar, Union, cast, get_args, get_origin
import __main__import numpy as npimport tomliimport tomli_wimport torchimport zero
from . import env
RawConfig = Dict[str, Any]Report = Dict[str, Any]T = TypeVar('T')
class Part(enum.Enum): TRAIN = 'train' VAL = 'val' TEST = 'test'
def __str__(self) -> str: return self.value
class TaskType(enum.Enum): BINCLASS = 'binclass' MULTICLASS = 'multiclass' REGRESSION = 'regression'
def __str__(self) -> str: return self.value
class Timer(zero.Timer): @classmethod def launch(cls) -> 'Timer': timer = cls() timer.run() return timer
def update_training_log(training_log, data, metrics): def _update(log_part, data_part): for k, v in data_part.items(): if isinstance(v, dict): _update(log_part.setdefault(k, {}), v) elif isinstance(v, list): log_part.setdefault(k, []).extend(v) else: log_part.setdefault(k, []).append(v)
_update(training_log, data) transposed_metrics = {} for part, part_metrics in metrics.items(): for metric_name, value in part_metrics.items(): transposed_metrics.setdefault(metric_name, {})[part] = value _update(training_log, transposed_metrics)
def raise_unknown(unknown_what: str, unknown_value: Any): raise ValueError(f'Unknown {unknown_what}: {unknown_value}')
def _replace(data, condition, value): def do(x): if isinstance(x, dict): return {k: do(v) for k, v in x.items()} elif isinstance(x, list): return [do(y) for y in x] else: return value if condition(x) else x
return do(data)
_CONFIG_NONE = '__none__'
def unpack_config(config: RawConfig) -> RawConfig: config = cast(RawConfig, _replace(config, lambda x: x == _CONFIG_NONE, None)) return config
def pack_config(config: RawConfig) -> RawConfig: config = cast(RawConfig, _replace(config, lambda x: x is None, _CONFIG_NONE)) return config
def load_config(path: Union[Path, str]) -> Any: with open(path, 'rb') as f: return unpack_config(tomli.load(f))
def dump_config(config: Any, path: Union[Path, str]) -> None: with open(path, 'wb') as f: tomli_w.dump(pack_config(config), f) # check that there are no bugs in all these "pack/unpack" things assert config == load_config(path)
def load_json(path: Union[Path, str], **kwargs) -> Any: return json.loads(Path(path).read_text(), **kwargs)
def dump_json(x: Any, path: Union[Path, str], **kwargs) -> None: kwargs.setdefault('indent', 4) Path(path).write_text(json.dumps(x, **kwargs) + '\n')
def load_pickle(path: Union[Path, str], **kwargs) -> Any: return pickle.loads(Path(path).read_bytes(), **kwargs)
def dump_pickle(x: Any, path: Union[Path, str], **kwargs) -> None: Path(path).write_bytes(pickle.dumps(x, **kwargs))
def load(path: Union[Path, str], **kwargs) -> Any: return globals()[f'load_{Path(path).suffix[1:]}'](Path(path), **kwargs)
def dump(x: Any, path: Union[Path, str], **kwargs) -> Any: return globals()[f'dump_{Path(path).suffix[1:]}'](x, Path(path), **kwargs)
def _get_output_item_path( path: Union[str, Path], filename: str, must_exist: bool) -> Path: path = env.get_path(path) if path.suffix == '.toml': path = path.with_suffix('') if path.is_dir(): path = path / filename else: assert path.name == filename assert path.parent.exists() if must_exist: assert path.exists() return path
def load_report(path: Path) -> Report: return load_json(_get_output_item_path(path, 'report.json', True))
def dump_report(report: dict, path: Path) -> None: dump_json(report, _get_output_item_path(path, 'report.json', False))
def load_predictions(path: Path) -> Dict[str, np.ndarray]: with np.load(_get_output_item_path(path, 'predictions.npz', True)) as predictions: return {x: predictions[x] for x in predictions}
def dump_predictions(predictions: Dict[str, np.ndarray], path: Path) -> None: np.savez(_get_output_item_path(path, 'predictions.npz', False), **predictions)
def dump_metrics(metrics: Dict[str, Any], path: Path) -> None: dump_json(metrics, _get_output_item_path(path, 'metrics.json', False))
def load_checkpoint(path: Path, *args, **kwargs) -> Dict[str, np.ndarray]: return torch.load( _get_output_item_path(path, 'checkpoint.pt', True), *args, **kwargs )
def get_device() -> torch.device: if torch.cuda.is_available(): assert os.environ.get('CUDA_VISIBLE_DEVICES') is not None return torch.device('cuda:0') else: return torch.device('cpu')
def _print_sep(c, size=100): print(c * size)
def start( config_cls: Type[T] = RawConfig, argv: Optional[List[str]] = None, patch_raw_config: Optional[Callable[[RawConfig], None]] = None,) -> Tuple[T, Path, Report]: # config # output dir # report parser = argparse.ArgumentParser() parser.add_argument('config', metavar='FILE') parser.add_argument('--force', action='store_true') parser.add_argument('--continue', action='store_true', dest='continue_') if argv is None: program = __main__.__file__ args = parser.parse_args() else: program = argv[0] try: args = parser.parse_args(argv[1:]) except Exception: print( 'Failed to parse `argv`.' ' Remember that the first item of `argv` must be the path (relative to' ' the project root) to the script/notebook.' ) raise args = parser.parse_args(argv)
snapshot_dir = os.environ.get('SNAPSHOT_PATH') if snapshot_dir and Path(snapshot_dir).joinpath('CHECKPOINTS_RESTORED').exists(): assert args.continue_
config_path = env.get_path(args.config) output_dir = config_path.with_suffix('') _print_sep('=') print(f'[output] {output_dir}') _print_sep('=')
assert config_path.exists() raw_config = load_config(config_path) if patch_raw_config is not None: patch_raw_config(raw_config) if is_dataclass(config_cls): config = from_dict(config_cls, raw_config) full_raw_config = asdict(config) else: assert config_cls is dict full_raw_config = config = raw_config full_raw_config = asdict(config)
if output_dir.exists(): if args.force: print('Removing the existing output and creating a new one...') shutil.rmtree(output_dir) output_dir.mkdir() elif not args.continue_: backup_output(output_dir) print('The output directory already exists. Done!\n') sys.exit() elif output_dir.joinpath('DONE').exists(): backup_output(output_dir) print('The "DONE" file already exists. Done!') sys.exit() else: print('Continuing with the existing output...') else: print('Creating the output...') output_dir.mkdir()
report = { 'program': str(env.get_relative_path(program)), 'environment': {}, 'config': full_raw_config, } if torch.cuda.is_available(): # type: ignore[code] report['environment'].update( { 'CUDA_VISIBLE_DEVICES': os.environ.get('CUDA_VISIBLE_DEVICES'), 'gpus': zero.hardware.get_gpus_info(), 'torch.version.cuda': torch.version.cuda, 'torch.backends.cudnn.version()': torch.backends.cudnn.version(), # type: ignore[code] 'torch.cuda.nccl.version()': torch.cuda.nccl.version(), # type: ignore[code] } ) dump_report(report, output_dir) dump_json(raw_config, output_dir / 'raw_config.json') _print_sep('-') pprint(full_raw_config, width=100) _print_sep('-') return cast(config_cls, config), output_dir, report
_LAST_SNAPSHOT_TIME = None
def backup_output(output_dir: Path) -> None: backup_dir = os.environ.get('TMP_OUTPUT_PATH') snapshot_dir = os.environ.get('SNAPSHOT_PATH') if backup_dir is None: assert snapshot_dir is None return assert snapshot_dir is not None
try: relative_output_dir = output_dir.relative_to(env.PROJ) except ValueError: return
for dir_ in [backup_dir, snapshot_dir]: new_output_dir = dir_ / relative_output_dir prev_backup_output_dir = new_output_dir.with_name(new_output_dir.name + '_prev') new_output_dir.parent.mkdir(exist_ok=True, parents=True) if new_output_dir.exists(): new_output_dir.rename(prev_backup_output_dir) shutil.copytree(output_dir, new_output_dir) # the case for evaluate.py which automatically creates configs if output_dir.with_suffix('.toml').exists(): shutil.copyfile( output_dir.with_suffix('.toml'), new_output_dir.with_suffix('.toml') ) if prev_backup_output_dir.exists(): shutil.rmtree(prev_backup_output_dir)
global _LAST_SNAPSHOT_TIME if _LAST_SNAPSHOT_TIME is None or time.time() - _LAST_SNAPSHOT_TIME > 10 * 60: import nirvana_dl.snapshot # type: ignore[code]
nirvana_dl.snapshot.dump_snapshot() _LAST_SNAPSHOT_TIME = time.time() print('The snapshot was saved!')
def _get_scores(metrics: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, float]]: return ( {k: v['score'] for k, v in metrics.items()} if 'score' in next(iter(metrics.values())) else None )
def format_scores(metrics: Dict[str, Dict[str, Any]]) -> str: return ' '.join( f"[{x}] {metrics[x]['score']:.3f}" for x in ['test', 'val', 'train'] if x in metrics )
def finish(output_dir: Path, report: dict) -> None: print() _print_sep('=')
metrics = report.get('metrics') if metrics is not None: scores = _get_scores(metrics) if scores is not None: dump_json(scores, output_dir / 'scores.json') print(format_scores(metrics)) _print_sep('-')
dump_report(report, output_dir) json_output_path = os.environ.get('JSON_OUTPUT_FILE') if json_output_path: try: key = str(output_dir.relative_to(env.PROJ)) except ValueError: pass else: json_output_path = Path(json_output_path) try: json_data = json.loads(json_output_path.read_text()) except (FileNotFoundError, json.decoder.JSONDecodeError): json_data = {} json_data[key] = load_json(output_dir / 'report.json') json_output_path.write_text(json.dumps(json_data, indent=4)) shutil.copyfile( json_output_path, os.path.join(os.environ['SNAPSHOT_PATH'], 'json_output.json'), )
output_dir.joinpath('DONE').touch() backup_output(output_dir) print(f'Done! | {report.get("time")} | {output_dir}') _print_sep('=') print()
def from_dict(datacls: Type[T], data: dict) -> T: assert is_dataclass(datacls) data = deepcopy(data) for field in fields(datacls): if field.name not in data: continue if is_dataclass(field.type): data[field.name] = from_dict(field.type, data[field.name]) elif ( get_origin(field.type) is Union and len(get_args(field.type)) == 2 and get_args(field.type)[1] is type(None) and is_dataclass(get_args(field.type)[0]) ): if data[field.name] is not None: data[field.name] = from_dict(get_args(field.type)[0], data[field.name]) return datacls(**data)
def replace_factor_with_value( config: RawConfig, key: str, reference_value: int, bounds: Tuple[float, float],) -> None: factor_key = key + '_factor' if factor_key not in config: assert key in config else: assert key not in config factor = config.pop(factor_key) assert bounds[0] <= factor <= bounds[1] config[key] = int(factor * reference_value)
def get_temporary_copy(path: Union[str, Path]) -> Path: path = env.get_path(path) assert not path.is_dir() and not path.is_symlink() tmp_path = path.with_name( path.stem + '___' + str(uuid.uuid4()).replace('-', '') + path.suffix ) shutil.copyfile(path, tmp_path) atexit.register(lambda: tmp_path.unlink()) return tmp_path
def get_python(): python = Path('python3.9') return str(python) if python.exists() else 'python'
def get_catboost_config(real_data_path, is_cv=False): ds_name = Path(real_data_path).name C = load_json(f'tuned_models/catboost/{ds_name}_cv.json') return C12345678910111213141516171819202122catboost==1.0.3category-encoders==2.3.0dython==0.5.1icecream==2.1.2libzero==0.0.8numpy==1.21.4optuna==2.10.1pandas==1.3.4pyarrow==6.0.0rtdl==0.0.9scikit-learn==1.0.2scipy==1.7.2skorch==0.11.0tomli-w==0.4.0tomli==1.2.2tqdm==4.62.3
# smoteimbalanced-learn==0.7.0
# tvaerdt==0.6.4 12345#!/usr/bin/env bashset -ecd /data/jialinzhang/synthetic_benchmark/tabddpm/codeexport PYTHONPATH="$PWD:$PYTHONPATH"python -m scripts.pipeline "$@"12345#!/usr/bin/env bashset -ecd /workspace/tabddpm/codeexport PYTHONPATH="$PWD:$PYTHONPATH"python -m scripts.pipeline "$@"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145from catboost import CatBoostClassifier, CatBoostRegressorfrom sklearn.metrics import classification_report, r2_scoreimport numpy as npimport osfrom sklearn.utils import shuffleimport zerofrom pathlib import Pathimport libfrom pprint import pprintfrom lib import concat_features, read_pure_data, get_catboost_config, read_changed_val
def train_catboost( parent_dir, real_data_path, eval_type, T_dict, seed = 0, params = None, change_val = True, device = None # dummy): zero.improve_reproducibility(seed) if eval_type != "real": synthetic_data_path = os.path.join(parent_dir) info = lib.load_json(os.path.join(real_data_path, 'info.json')) T = lib.Transformations(**T_dict) if change_val: 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)
X = None print('-'*100) if eval_type == 'merged': print('loading merged data...') if not change_val: X_num_real, X_cat_real, y_real = read_pure_data(real_data_path) X_num_fake, X_cat_fake, y_fake = read_pure_data(synthetic_data_path)
### # dists = privacy_metrics(real_data_path, synthetic_data_path) # bad_fakes = dists.argsort()[:int(0.25 * len(y_fake))] # X_num_fake = np.delete(X_num_fake, bad_fakes, axis=0) # X_cat_fake = np.delete(X_cat_fake, bad_fakes, axis=0) if X_cat_fake is not None else None # y_fake = np.delete(y_fake, bad_fakes, axis=0) ###
y = np.concatenate([y_real, y_fake], axis=0)
X_num = None if X_num_real is not None: X_num = np.concatenate([X_num_real, X_num_fake], axis=0)
X_cat = None if X_cat_real is not None: X_cat = np.concatenate([X_cat_real, X_cat_fake], axis=0)
elif eval_type == 'synthetic': print(f'loading synthetic data: {parent_dir}') X_num, X_cat, y = read_pure_data(synthetic_data_path)
elif eval_type == 'real': print('loading real data...') if not change_val: X_num, X_cat, y = read_pure_data(real_data_path) else: raise "Choose eval method"
if not change_val: X_num_val, X_cat_val, y_val = read_pure_data(real_data_path, 'val') X_num_test, X_cat_test, y_test = read_pure_data(real_data_path, 'test')
D = lib.Dataset( {'train': X_num, 'val': X_num_val, 'test': X_num_test} if X_num is not None else None, {'train': X_cat, 'val': X_cat_val, 'test': X_cat_test} if X_cat is not None else None, {'train': y, 'val': y_val, 'test': y_test}, {}, lib.TaskType(info['task_type']), info.get('n_classes') )
D = lib.transform_dataset(D, T, None) X = concat_features(D) print(f'Train size: {X["train"].shape}, Val size {X["val"].shape}')
if params is None: catboost_config = get_catboost_config(real_data_path, is_cv=True) else: catboost_config = params
if 'cat_features' not in catboost_config: catboost_config['cat_features'] = list(range(D.n_num_features, D.n_features))
for col in range(D.n_features): for split in X.keys(): if col in catboost_config['cat_features']: X[split][col] = X[split][col].astype(str) else: X[split][col] = X[split][col].astype(float) print(T_dict) pprint(catboost_config, width=100) print('-'*100) if D.is_regression: model = CatBoostRegressor( **catboost_config, eval_metric='RMSE', random_seed=seed ) predict = model.predict else: model = CatBoostClassifier( loss_function="MultiClass" if D.is_multiclass else "Logloss", **catboost_config, eval_metric='TotalF1', random_seed=seed, class_names=[str(i) for i in range(D.n_classes)] if D.is_multiclass else ["0", "1"] ) predict = ( model.predict_proba if D.is_multiclass else lambda x: model.predict_proba(x)[:, 1] )
model.fit( X['train'], D.y['train'], eval_set=(X['val'], D.y['val']), verbose=100 ) predictions = {k: predict(v) for k, v in X.items()} print(predictions['train'].shape)
report = {} report['eval_type'] = eval_type report['dataset'] = real_data_path report['metrics'] = D.calculate_metrics(predictions, None if D.is_regression else 'probs')
metrics_report = lib.MetricsReport(report['metrics'], D.task_type) metrics_report.print_metrics()
if parent_dir is not None: lib.dump_json(report, os.path.join(parent_dir, "results_catboost.json"))
return metrics_report
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176from sklearn.metrics import classification_report, r2_score, f1_scoreimport numpy as npimport osfrom sklearn.utils import shuffleimport zerofrom pathlib import Pathimport libfrom tab_ddpm.modules import MLPfrom skorch.regressor import NeuralNetRegressorfrom skorch.classifier import NeuralNetClassifierfrom skorch.dataset import Dataset as SkDatasetfrom skorch.callbacks import EarlyStopping, EpochScoringfrom skorch.helper import predefined_splitfrom torch.optim import AdamWfrom torch.nn import MSELoss, BCEWithLogitsLoss, CrossEntropyLoss
def train_mlp( parent_dir, real_data_path, eval_type, T_dict, params = None, change_val = False, seed = 0, device = "cuda:0"): zero.improve_reproducibility(seed) synthetic_data_path = os.path.join(parent_dir) if parent_dir is not None else None info = lib.load_json(os.path.join(real_data_path, 'info.json')) T = lib.Transformations(**T_dict) if change_val: 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)
X = None print('-'*100) if eval_type == 'merged': print('loading merged data...') if not change_val: X_num_real, X_cat_real, y_real = lib.read_pure_data(real_data_path) X_num_fake, X_cat_fake, y_fake = lib.read_pure_data(synthetic_data_path) y = np.concatenate([y_real, y_fake], axis=0)
X_num = None if X_num_real is not None: X_num = np.concatenate([X_num_real, X_num_fake], axis=0)
X_cat = None if X_cat_real is not None: X_cat = np.concatenate([X_cat_real, X_cat_fake], axis=0)
elif eval_type == 'synthetic': print('loading synthetic data...') X_num, X_cat, y = lib.read_pure_data(synthetic_data_path)
elif eval_type == 'real': print('loading real data...') if not change_val: X_num, X_cat, y = lib.read_pure_data(real_data_path) else: raise "Choose eval method"
if not change_val: X_num_val, X_cat_val, y_val = lib.read_pure_data(real_data_path, 'val') X_num_test, X_cat_test, y_test = lib.read_pure_data(real_data_path, 'test')
D = lib.Dataset( {'train': X_num, 'val': X_num_val, 'test': X_num_test} if X_num is not None else None, {'train': X_cat, 'val': X_cat_val, 'test': X_cat_test} if X_cat is not None else None, {'train': y, 'val': y_val, 'test': y_test}, {}, lib.TaskType(info['task_type']), info.get('n_classes') )
D = lib.transform_dataset(D, T, None) X = lib.concat_features(D)
X["train"], D.y["train"] = shuffle(X["train"], D.y["train"], random_state=seed) print(f'Train size: {X["train"].shape}, Val size {X["val"].shape}')
if params is None: params = lib.load_json(f"tuned_models/mlp/{Path(real_data_path).name}_cv.json")
mlp_params = {} if params is not None: mlp_params["d_layers"] = params["d_layers"] mlp_params["dropout"] = params["dropout"] # mlp_params["n_blocks"] = params["n_blocks"] # mlp_params["d_main"] = params["d_main"] # mlp_params["d_hidden"] = params["d_hidden"] # mlp_params["dropout_first"] = params["dropout_first"] # mlp_params["dropout_second"] = params["dropout_second"] mlp_params["d_in"] = X["train"].shape[1] mlp_params["d_out"] = D.nn_output_dim
model = MLP.make_baseline(**mlp_params)
if D.is_regression: y = {k: D.y[k].reshape(-1, 1).astype(np.float32) for k in D.y} elif D.is_binclass: y = {k: D.y[k].reshape(-1, 1).astype(np.float32) for k in D.y} else: y = {k: D.y[k].astype(np.int64) for k in D.y}
train_ds = SkDataset(X = X["train"].to_numpy(), y = y["train"]) val_ds = SkDataset(X = X["val"].to_numpy(), y = y["val"]) es = EarlyStopping(monitor="valid_loss", patience=16)
print('-'*100)
def f1(net, X, y): y_pred = net.predict(X) return f1_score(y, y_pred, average="macro")
def r2(net, X, y): y_pred = net.predict(X) return r2_score(y, y_pred)
if D.is_regression: net = NeuralNetRegressor( model, criterion=MSELoss, optimizer=AdamW, lr=params["lr"], optimizer__weight_decay=params["weight_decay"], batch_size=128 if len(D.y["train"]) < 10_000 else 256, max_epochs=1000, train_split=predefined_split(val_ds), iterator_train__shuffle=True, device=device, callbacks=[es, EpochScoring(r2, lower_is_better=False)], )
else: net = NeuralNetClassifier( model, criterion=BCEWithLogitsLoss if D.is_binclass else CrossEntropyLoss, optimizer=AdamW, lr=params["lr"], optimizer__weight_decay=params["weight_decay"], batch_size=128 if len(D.y["train"]) < 10_000 else 256, max_epochs=1000, train_split=predefined_split(val_ds), iterator_train__shuffle=True, device=device, callbacks=[es, EpochScoring(f1, lower_is_better=False)], )
net.fit( X=train_ds.X, y=train_ds.y )
print("LAST:", len(net.history))
predictions = {k: net.predict_proba(v.to_numpy())[:, 1] if D.is_binclass else net.predict_proba(v.to_numpy()) if D.is_multiclass else net.predict(v.to_numpy()) for k, v in X.items() }
report = {} report['eval_type'] = eval_type report['dataset'] = real_data_path report['metrics'] = D.calculate_metrics(predictions, None if D.is_regression else 'probs')
metrics_report = lib.MetricsReport(report['metrics'], D.task_type) metrics_report.print_metrics()
if parent_dir is not None: lib.dump_json(report, os.path.join(parent_dir, "results_mlp.json"))
return metrics_report
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import argparseimport subprocessimport tempfileimport libimport osimport shutilfrom pathlib import Pathfrom copy import deepcopyfrom scripts.eval_catboost import train_catboostfrom scripts.eval_mlp import train_mlpfrom scripts.eval_simple import train_simple
pipeline = { 'ddpm': 'scripts/pipeline.py', 'smote': 'smote/pipeline_smote.py', 'ctabgan': 'CTAB-GAN/pipeline_ctabgan.py', 'ctabgan-plus': 'CTAB-GAN-Plus/pipeline_ctabgan.py', 'tvae': 'CTGAN/pipeline_tvae.py'}
def eval_seeds( raw_config, n_seeds, eval_type, sampling_method="ddpm", model_type="catboost", n_datasets=1, dump=True, change_val=False):
metrics_seeds_report = lib.SeedsMetricsReport() parent_dir = Path(raw_config["parent_dir"])
if eval_type == 'real': n_datasets = 1
temp_config = deepcopy(raw_config) with tempfile.TemporaryDirectory() as dir_: dir_ = Path(dir_) temp_config["parent_dir"] = str(dir_) if sampling_method == "ddpm": shutil.copy2(parent_dir / "model.pt", temp_config["parent_dir"]) elif sampling_method in ["ctabgan", "ctabgan-plus"]: shutil.copy2(parent_dir / "ctabgan.obj", temp_config["parent_dir"]) elif sampling_method == "tvae": shutil.copy2(parent_dir / "tvae.obj", temp_config["parent_dir"])
for sample_seed in range(n_datasets): temp_config['sample']['seed'] = sample_seed lib.dump_config(temp_config, dir_ / "config.toml") if eval_type != 'real' and n_datasets > 1: subprocess.run(['python3.9', f'{pipeline[sampling_method]}', '--config', f'{str(dir_ / "config.toml")}', '--sample'], check=True)
T_dict = deepcopy(raw_config['eval']['T']) for seed in range(n_seeds): print(f'**Eval Iter: {sample_seed*n_seeds + (seed + 1)}/{n_seeds * n_datasets}**') if model_type == "catboost": T_dict["normalization"] = None T_dict["cat_encoding"] = None metric_report = train_catboost( parent_dir=temp_config['parent_dir'], real_data_path=temp_config['real_data_path'], eval_type=eval_type, T_dict=T_dict, seed=seed, change_val=change_val ) elif model_type == "mlp": T_dict["normalization"] = "quantile" T_dict["cat_encoding"] = "one-hot" metric_report = train_mlp( parent_dir=temp_config['parent_dir'], real_data_path=temp_config['real_data_path'], eval_type=eval_type, T_dict=T_dict, seed=seed, change_val=change_val )
metrics_seeds_report.add_report(metric_report)
metrics_seeds_report.get_mean_std() res = metrics_seeds_report.print_result() if os.path.exists(parent_dir/ f"eval_{model_type}.json"): eval_dict = lib.load_json(parent_dir / f"eval_{model_type}.json") eval_dict = eval_dict | {eval_type: res} else: eval_dict = {eval_type: res} if dump: lib.dump_json(eval_dict, parent_dir / f"eval_{model_type}.json")
raw_config['sample']['seed'] = 0 lib.dump_config(raw_config, parent_dir / 'config.toml') return res
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', metavar='FILE') parser.add_argument('n_seeds', type=int, default=10) parser.add_argument('sampling_method', type=str, default="ddpm") parser.add_argument('eval_type', type=str, default='synthetic') parser.add_argument('model_type', type=str, default='catboost') parser.add_argument('n_datasets', type=int, default=1) parser.add_argument('--no_dump', action='store_false', default=True)
args = parser.parse_args() raw_config = lib.load_config(args.config) eval_seeds( raw_config, n_seeds=args.n_seeds, sampling_method=args.sampling_method, eval_type=args.eval_type, model_type=args.model_type, n_datasets=args.n_datasets, dump=args.no_dump )
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130import argparseimport subprocessimport tempfileimport libimport osimport pandas as pdimport numpy as npfrom pathlib import Pathfrom eval_simple import train_simplefrom copy import deepcopyimport shutil
pipeline = { 'ddpm': 'scripts/pipeline.py', 'smote': 'smote/pipeline_smote.py', 'ctabgan': 'CTAB-GAN/pipeline_ctabgan.py', 'ctabgan-plus': 'CTAB-GAN-Plus/pipeline_ctabganp.py', 'tvae': 'CTGAN/pipeline_tvae.py'}
def eval_seeds( raw_config, n_seeds, eval_type, sampling_method="ddpm", model_type="simple", n_datasets=1, dump=True, change_val=False): parent_dir = Path(raw_config["parent_dir"]) models = ["tree", "lr", "rf", "mlp"] metrics_seeds_report = { k: lib.SeedsMetricsReport() for k in models }
if eval_type == 'real': n_datasets = 1
T_dict = deepcopy(raw_config['eval']['T']) T_dict["normalization"] = "minmax" T_dict["cat_encoding"] = None
temp_config = deepcopy(raw_config) with tempfile.TemporaryDirectory() as dir_: dir_ = Path(dir_) temp_config["parent_dir"] = str(dir_) if sampling_method == "ddpm": shutil.copy2(parent_dir / "model.pt", temp_config["parent_dir"]) elif sampling_method in ["ctabgan", "ctabgan-plus"]: shutil.copy2(parent_dir / "ctabgan.obj", temp_config["parent_dir"]) elif sampling_method == "tvae": shutil.copy2(parent_dir / "tvae.obj", temp_config["parent_dir"])
for sample_seed in range(n_datasets): temp_config['sample']['seed'] = sample_seed lib.dump_config(temp_config, dir_ / "config.toml") if eval_type != 'real': subprocess.run(['python3.9', f'{pipeline[sampling_method]}', '--config', f'{str(dir_ / "config.toml")}', '--sample'], check=True)
for seed in range(n_seeds): print(f'**Eval Iter: {sample_seed*n_seeds + (seed + 1)}/{n_seeds * n_datasets}**') for model in models: metric_report = train_simple( parent_dir=temp_config['parent_dir'], real_data_path=temp_config['real_data_path'], model_name=model, eval_type=eval_type, T_dict=T_dict, seed=seed, change_val=change_val )
metrics_seeds_report[model].add_report(metric_report) for k in models: metrics_seeds_report[k].get_mean_std() res = { k: metrics_seeds_report[k].print_result() for k in models }
m1, m2 = ("r2-mean", "rmse-mean") if "r2-mean" in res["tree"]["val"] else ("f1-mean", "acc-mean") res["avg"] = { "val": { m1: np.around(np.mean([res[k]["val"][m1] for k in models]), 4), m2: np.around(np.mean([res[k]["val"][m2] for k in models]), 4) }, "test": { m1: np.around(np.mean([res[k]["test"][m1] for k in models]), 4), m2: np.around(np.mean([res[k]["test"][m2] for k in models]), 4) }, }
if os.path.exists(parent_dir / f"eval_{model_type}.json"): eval_dict = lib.load_json(parent_dir / f"eval_{model_type}.json") eval_dict = eval_dict | {eval_type: res} else: eval_dict = {eval_type: res} if dump: lib.dump_json(eval_dict, parent_dir / f"eval_{model_type}.json")
raw_config['sample']['seed'] = 0 lib.dump_config(raw_config, parent_dir / 'config.toml') return res
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', metavar='FILE') parser.add_argument('n_seeds', type=int, default=10) parser.add_argument('sampling_method', type=str, default="ddpm") parser.add_argument('eval_type', type=str, default='synthetic') parser.add_argument('model_type', type=str, default='catboost') parser.add_argument('n_datasets', type=int, default=1) parser.add_argument('--no_dump', action='store_false', default=True)
args = parser.parse_args() raw_config = lib.load_config(args.config) eval_seeds( raw_config, n_seeds=args.n_seeds, sampling_method=args.sampling_method, eval_type=args.eval_type, model_type=args.model_type, n_datasets=args.n_datasets, dump=args.no_dump )
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141import numpy as npimport osfrom sklearn.utils import shuffleimport zerofrom pathlib import Pathimport libfrom lib import concat_features, read_pure_data, read_changed_valfrom sklearn.utils import shuffleimport libfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressorfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressorfrom sklearn.linear_model import LogisticRegression, Ridgefrom sklearn.neural_network import MLPClassifier, MLPRegressor
def train_simple( parent_dir, real_data_path, eval_type, T_dict, model_name = "tree", seed = 0, change_val = True, params = None, # dummy device = None # dummy): zero.improve_reproducibility(seed) if eval_type != "real": synthetic_data_path = os.path.join(parent_dir)
T_dict["normalization"] = "minmax" T_dict["cat_encoding"] = None T = lib.Transformations(**T_dict) info = lib.load_json(os.path.join(real_data_path, 'info.json')) if change_val: 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)
X = None print('-'*100) if eval_type == 'merged': print('loading merged data...') if not change_val: X_num_real, X_cat_real, y_real = read_pure_data(real_data_path) X_num_fake, X_cat_fake, y_fake = read_pure_data(synthetic_data_path)
### # dists = privacy_metrics(real_data_path, synthetic_data_path) # bad_fakes = dists.argsort()[:int(0.25 * len(y_fake))] # X_num_fake = np.delete(X_num_fake, bad_fakes, axis=0) # X_cat_fake = np.delete(X_cat_fake, bad_fakes, axis=0) if X_cat_fake is not None else None # y_fake = np.delete(y_fake, bad_fakes, axis=0) ###
y = np.concatenate([y_real, y_fake], axis=0)
X_num = None if X_num_real is not None: X_num = np.concatenate([X_num_real, X_num_fake], axis=0)
X_cat = None if X_cat_real is not None: X_cat = np.concatenate([X_cat_real, X_cat_fake], axis=0)
elif eval_type == 'synthetic': print(f'loading synthetic data: {parent_dir}') X_num, X_cat, y = read_pure_data(synthetic_data_path)
elif eval_type == 'real': print('loading real data...') if not change_val: X_num, X_cat, y = read_pure_data(real_data_path) else: raise "Choose eval method"
if not change_val: X_num_val, X_cat_val, y_val = read_pure_data(real_data_path, 'val') X_num_test, X_cat_test, y_test = read_pure_data(real_data_path, 'test') D = lib.Dataset( {'train': X_num, 'val': X_num_val, 'test': X_num_test} if X_num is not None else None, {'train': X_cat, 'val': X_cat_val, 'test': X_cat_test} if X_cat is not None else None, {'train': y, 'val': y_val, 'test': y_test}, {}, lib.TaskType(info['task_type']), info.get('n_classes') )
D = lib.transform_dataset(D, T, None) X = concat_features(D) # ixs = np.random.choice(len(D.y["train"]), min(info["train_size"], len(D.y["train"])), replace=False) # X["train"] = X["train"].iloc[ixs] # D.y["train"] = D.y["train"][ixs]
print(f'Train size: {X["train"].shape}, Val size {X["val"].shape}') print(T_dict) print('-'*100) if D.is_regression: models = { "tree": DecisionTreeRegressor(max_depth=28, random_state=seed), "rf": RandomForestRegressor(max_depth=28, random_state=seed), "lr": Ridge(max_iter=500, random_state=seed), "mlp": MLPRegressor(max_iter=100, random_state=seed) } else: models = { "tree": DecisionTreeClassifier(max_depth=28, random_state=seed), "rf": RandomForestClassifier(max_depth=28, random_state=seed), "lr": LogisticRegression(max_iter=500, n_jobs=2, random_state=seed), "mlp": MLPClassifier(max_iter=100, random_state=seed) } model = models[model_name]
predict = ( model.predict if D.is_regression else model.predict_proba if D.is_multiclass else lambda x: model.predict_proba(x)[:, 1] )
model.fit(X['train'], D.y['train'])
predictions = {k: predict(v) for k, v in X.items()}
report = {} report['eval_type'] = eval_type report['dataset'] = real_data_path report['metrics'] = D.calculate_metrics(predictions, None if D.is_regression else 'probs')
metrics_report = lib.MetricsReport(report['metrics'], D.task_type) print(model.__class__.__name__) metrics_report.print_metrics() # if parent_dir is not None: # lib.dump_json(report, os.path.join(parent_dir, "results_catboost.json"))
return metrics_report
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112import tomliimport shutilimport osimport argparsefrom scripts.train import trainfrom scripts.sample import samplefrom scripts.eval_catboost import train_catboostfrom scripts.eval_mlp import train_mlpfrom scripts.eval_simple import train_simpleimport pandas as pdimport matplotlib.pyplot as pltimport zeroimport libimport torch
def load_config(path) : with open(path, 'rb') as f: return tomli.load(f) def save_file(parent_dir, config_path): try: dst = os.path.join(parent_dir) os.makedirs(os.path.dirname(dst), exist_ok=True) shutil.copyfile(os.path.abspath(config_path), dst) except shutil.SameFileError: pass
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', metavar='FILE') parser.add_argument('--train', action='store_true', default=False) parser.add_argument('--sample', action='store_true', default=False) parser.add_argument('--eval', action='store_true', default=False) parser.add_argument('--change_val', action='store_true', default=False)
args = parser.parse_args() raw_config = lib.load_config(args.config) if 'device' in raw_config: device = torch.device(raw_config['device']) else: device = torch.device('cuda:1') timer = zero.Timer() timer.run() save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
if args.train: train( **raw_config['train']['main'], **raw_config['diffusion_params'], parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], model_type=raw_config['model_type'], model_params=raw_config['model_params'], T_dict=raw_config['train']['T'], num_numerical_features=raw_config['num_numerical_features'], device=device, change_val=args.change_val ) if args.sample: sample( num_samples=raw_config['sample']['num_samples'], batch_size=raw_config['sample']['batch_size'], disbalance=raw_config['sample'].get('disbalance', None), **raw_config['diffusion_params'], parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], model_path=os.path.join(raw_config['parent_dir'], 'model.pt'), model_type=raw_config['model_type'], model_params=raw_config['model_params'], T_dict=raw_config['train']['T'], num_numerical_features=raw_config['num_numerical_features'], device=device, seed=raw_config['sample'].get('seed', 0), change_val=args.change_val )
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json')) if args.eval: if raw_config['eval']['type']['eval_model'] == 'catboost': train_catboost( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], eval_type=raw_config['eval']['type']['eval_type'], T_dict=raw_config['eval']['T'], seed=raw_config['seed'], change_val=args.change_val ) elif raw_config['eval']['type']['eval_model'] == 'mlp': train_mlp( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], eval_type=raw_config['eval']['type']['eval_type'], T_dict=raw_config['eval']['T'], seed=raw_config['seed'], change_val=args.change_val, device=device ) elif raw_config['eval']['type']['eval_model'] == 'simple': train_simple( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], eval_type=raw_config['eval']['type']['eval_type'], T_dict=raw_config['eval']['T'], seed=raw_config['seed'], change_val=args.change_val )
print(f'Elapsed time: {str(timer)}')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257"""Adapted from https://github.com/Team-TUD/CTAB-GAN/tree/main/model/eval"""
import argparseimport libimport osimport shutilimport zerofrom sample import samplefrom smote.sample_smote import sample_smotefrom sklearn.preprocessing import MinMaxScaler, OneHotEncoderfrom sklearn.metrics import pairwise_distancesfrom pathlib import Pathimport tempfilefrom eval_seeds import eval_seedsimport numpy as npimport subprocessimport warningsimport torch
zero.improve_reproducibility(0)
warnings.filterwarnings("ignore", category=FutureWarning)
def privacy_metrics(real_path,fake_path, data_percent=15):
""" Returns privacy metrics Inputs: 1) real_path -> path to real data 2) fake_path -> path to corresponding synthetic data 3) data_percent -> percentage of data to be sampled from real and synthetic datasets for computing privacy metrics Outputs: 1) List containing the 5th percentile distance to closest record (DCR) between real and synthetic as well as within real and synthetic datasets along with 5th percentile of nearest neighbour distance ratio (NNDR) between real and synthetic as well as within real and synthetic datasets """ task_type = lib.load_json(real_path + "/info.json")["task_type"] X_num_real, X_cat_real, y_real = lib.read_pure_data(real_path, 'train') X_num_fake, X_cat_fake, y_fake = lib.read_pure_data(fake_path, 'train')
if task_type == 'regression': X_num_real = np.concatenate([X_num_real, y_real[:, np.newaxis]], axis=1) X_num_fake = np.concatenate([X_num_fake, y_fake[:, np.newaxis]], axis=1) else: if X_cat_fake is None: X_cat_real = y_real[:, np.newaxis].astype(int).astype(str) X_cat_fake = y_fake[:, np.newaxis].astype(int).astype(str) else: X_cat_real = np.concatenate([X_cat_real, y_real[:, np.newaxis].astype(int).astype(str)], axis=1) X_cat_fake = np.concatenate([X_cat_fake, y_fake[:, np.newaxis].astype(int).astype(str)], axis=1)
if len(y_real) > 50000: ixs = np.random.choice(len(y_real), 50000, replace=False) X_num_real = X_num_real[ixs] X_cat_real = X_cat_real[ixs] if X_cat_real is not None else None if len(y_fake) > 50000: ixs = np.random.choice(len(y_fake), 50000, replace=False) X_num_fake = X_num_fake[ixs] X_cat_fake = X_cat_fake[ixs] if X_cat_fake is not None else None
mm = MinMaxScaler().fit(X_num_real) X_real = mm.transform(X_num_real) X_fake = mm.transform(X_num_fake) if X_cat_real is not None: ohe = OneHotEncoder().fit(X_cat_real) X_cat_real = ohe.transform(X_cat_real) / np.sqrt(2) X_cat_fake = ohe.transform(X_cat_fake) / np.sqrt(2)
X_real = np.concatenate([X_real, X_cat_real.todense()], axis=1) X_fake = np.concatenate([X_fake, X_cat_fake.todense()], axis=1)
# X_real = np.unique(X_real, axis=0) # X_fake = np.unique(X_fake, axis=0)
# Computing pair-wise distances between real and synthetic dist_rf = pairwise_distances(X_fake, Y=X_real, metric='l2', n_jobs=-1) # Computing pair-wise distances within real # dist_rr = pairwise_distances(X_real, Y=None, metric='l2', n_jobs=-1) # Computing pair-wise distances within synthetic # dist_ff = pairwise_distances(X_fake, Y=None, metric='l2', n_jobs=-1)
# Removes distances of data points to themselves to avoid 0s within real and synthetic # rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1) # rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1) # Computing first and second smallest nearest neighbour distances between real and synthetic smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))] smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))] # Computing first and second smallest nearest neighbour distances within real # smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))] # smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))] # Computing first and second smallest nearest neighbour distances within synthetic # smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))] # smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))]
# Computing 5th percentiles for DCR and NNDR between and within real and synthetic datasets min_dist_rf = np.array([i[0] for i in smallest_two_rf]) fifth_perc_rf = np.percentile(min_dist_rf,5) # min_dist_rr = np.array([i[0] for i in smallest_two_rr]) # fifth_perc_rr = np.percentile(min_dist_rr,5) # min_dist_ff = np.array([i[0] for i in smallest_two_ff]) # fifth_perc_ff = np.percentile(min_dist_ff,5) # nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf]) # nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5) # nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr]) # nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5) # nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff]) # nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5) # 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) return min_dist_rf # , min_dist_rr
def sample_wrapper(method, config, num_samples=None, seed=0): if method == "ddpm": sample( num_samples=num_samples, batch_size=config['sample']['batch_size'], disbalance=config['sample'].get('disbalance', None), **config['diffusion_params'], parent_dir=config['parent_dir'], real_data_path=config['real_data_path'], model_path=os.path.join(config['parent_dir'], 'model.pt'), model_type=config['model_type'], model_params=config['model_params'], T_dict=config['train']['T'], num_numerical_features=config['num_numerical_features'], seed=seed, change_val=False, device=torch.device(config["device"]) ) elif method == "smote": sample_smote( parent_dir=config['parent_dir'], real_data_path=config['real_data_path'], **config['smote_params'], seed=seed, change_val=False )
def resample_privacy(config_path, method, q): with tempfile.TemporaryDirectory() as dir_: config = lib.load_config(config_path) if method == "ddpm": shutil.copy2(os.path.join(config['parent_dir'], 'model.pt'), os.path.join(dir_, 'model.pt')) config["parent_dir"] = str(dir_) parent_dir = config["parent_dir"]
sample_wrapper(method, config, num_samples=config["sample"].get("num_samples", 0))
dists = privacy_metrics(config["real_data_path"], parent_dir) old_privacy = np.median(dists)
q10 = np.quantile(dists, q=q) print(f"Q: {q10}") to_drop = np.where(dists < q10)
X_num, X_cat, y = lib.read_pure_data(parent_dir) num_samples = len(y) X_num = np.delete(X_num, to_drop, axis=0) X_cat = np.delete(X_cat, to_drop, axis=0) if X_cat is not None else None y = np.delete(y, to_drop, axis=0) i = 1
while len(y) < num_samples and i <= 10: print(f"{len(y)}/{num_samples}") sample_wrapper(method, config, num_samples=config["sample"].get("batch_size", 0), seed=i)
i += 1
X_num_t, X_cat_t, y_t = lib.read_pure_data(parent_dir) dists = privacy_metrics(config["real_data_path"], parent_dir) to_drop = np.where(dists < q10) X_num_t = np.delete(X_num_t, to_drop, axis=0) X_cat_t = np.delete(X_cat_t, to_drop, axis=0) if X_cat is not None else None y_t = np.delete(y_t, to_drop, axis=0)
X_num = np.concatenate([X_num, X_num_t], axis=0)[:num_samples] X_cat = np.concatenate([X_cat, X_cat_t], axis=0)[:num_samples] if X_cat is not None else None y = np.concatenate([y, y_t], axis=0)[:num_samples]
# np.save(os.path.join(parent_dir, 'X_num_train'), X_num) # if X_cat is not None: # np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat) # np.save(os.path.join(parent_dir, 'y_train'), y)
np.save(os.path.join(parent_dir, 'X_num_train'), X_num) if X_cat is not None: np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat) np.save(os.path.join(parent_dir, 'y_train'), y)
new_dists = privacy_metrics(config["real_data_path"], parent_dir)
res = eval_seeds( config, n_seeds=10, eval_type="synthetic", model_type="catboost", n_datasets=1, dump=False ) print(f"Old: {old_privacy:.4f}, New: {np.median(new_dists):.4f}")
metric = "r2-mean" if "r2-mean" in res["test"] else "f1-mean" return res["test"][metric], np.around(np.median(new_dists), 4)
def resample_privacy_qs(config_path, method): config = lib.load_config(config_path) scores = [] privacies = []
eval_res = lib.load_json(Path(config["parent_dir"]) / "eval_catboost.json")["synthetic"]["test"] metric = "r2-mean" if "r2-mean" in eval_res else "f1-mean" scores.append(eval_res[metric]) privacies.append(np.median(privacy_metrics(config["real_data_path"], config["parent_dir"])))
for q in [0.1, 0.2, 0.3, 0.4]: score, privacy = resample_privacy(config_path, method, q) scores.append(score) privacies.append(privacy) lib.dump_json( {"scores": scores, "privacies": privacies}, Path(config["parent_dir"]) / "privacies.json" )
def calc_privacy(config_path, method, seed=0): config = lib.load_config(config_path) sample_wrapper(method, config, num_samples=config["sample"]["num_samples"], seed=seed) timer = zero.Timer() timer.run() dists = privacy_metrics(config["real_data_path"], config["parent_dir"]) privacy_val = np.median(dists) lib.dump_json({"privacy": privacy_val}, os.path.join(config["parent_dir"], "privacy.json")) print(f"Elapsed tine:{str(timer)}")
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', metavar='FILE') parser.add_argument('method', type=str) args = parser.parse_args()
calc_privacy( args.config, args.method )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160import torchimport numpy as npimport zeroimport osfrom tab_ddpm.gaussian_multinomial_diffsuion import GaussianMultinomialDiffusionfrom tab_ddpm.utils import FoundNANsErrorfrom scripts.utils_train import get_model, make_datasetfrom lib import round_columnsimport lib
def to_good_ohe(ohe, X): indices = np.cumsum([0] + ohe._n_features_outs) Xres = [] for i in range(1, len(indices)): x_ = np.max(X[:, indices[i - 1]:indices[i]], axis=1) t = X[:, indices[i - 1]:indices[i]] - x_.reshape(-1, 1) Xres.append(np.where(t >= 0, 1, 0)) return np.hstack(Xres)
def sample( parent_dir, real_data_path = 'data/higgs-small', batch_size = 2000, num_samples = 0, model_type = 'mlp', model_params = None, model_path = None, num_timesteps = 1000, gaussian_loss_type = 'mse', scheduler = 'cosine', T_dict = None, num_numerical_features = 0, disbalance = None, device = torch.device('cuda:1'), seed = 0, change_val = False): zero.improve_reproducibility(seed)
T = lib.Transformations(**T_dict) D = make_dataset( real_data_path, T, num_classes=model_params['num_classes'], is_y_cond=model_params['is_y_cond'], change_val=change_val )
K = np.array(D.get_category_sizes('train')) if len(K) == 0 or T_dict['cat_encoding'] == 'one-hot': K = np.array([0])
num_numerical_features_ = D.X_num['train'].shape[1] if D.X_num is not None else 0 d_in = np.sum(K) + num_numerical_features_ model_params['d_in'] = int(d_in) model = get_model( model_type, model_params, num_numerical_features_, category_sizes=D.get_category_sizes('train') )
model.load_state_dict( torch.load(model_path, map_location="cpu") )
diffusion = GaussianMultinomialDiffusion( K, num_numerical_features=num_numerical_features_, denoise_fn=model, num_timesteps=num_timesteps, gaussian_loss_type=gaussian_loss_type, scheduler=scheduler, device=device )
diffusion.to(device) diffusion.eval() _, empirical_class_dist = torch.unique(torch.from_numpy(D.y['train']), return_counts=True) # empirical_class_dist = empirical_class_dist.float() + torch.tensor([-5000., 10000.]).float() if disbalance == 'fix': empirical_class_dist[0], empirical_class_dist[1] = empirical_class_dist[1], empirical_class_dist[0] x_gen, y_gen = diffusion.sample_all(num_samples, batch_size, empirical_class_dist.float(), ddim=False)
elif disbalance == 'fill': ix_major = empirical_class_dist.argmax().item() val_major = empirical_class_dist[ix_major].item() x_gen, y_gen = [], [] for i in range(empirical_class_dist.shape[0]): if i == ix_major: continue distrib = torch.zeros_like(empirical_class_dist) distrib[i] = 1 num_samples = val_major - empirical_class_dist[i].item() x_temp, y_temp = diffusion.sample_all(num_samples, batch_size, distrib.float(), ddim=False) x_gen.append(x_temp) y_gen.append(y_temp) x_gen = torch.cat(x_gen, dim=0) y_gen = torch.cat(y_gen, dim=0)
else: x_gen, y_gen = diffusion.sample_all(num_samples, batch_size, empirical_class_dist.float(), ddim=False)
# try: # except FoundNANsError as ex: # print("Found NaNs during sampling!") # loader = lib.prepare_fast_dataloader(D, 'train', 8) # x_gen = next(loader)[0] # y_gen = torch.multinomial( # empirical_class_dist.float(), # num_samples=8, # replacement=True # ) X_gen, y_gen = x_gen.numpy(), y_gen.numpy()
### # X_num_unnorm = X_gen[:, :num_numerical_features] # lo = np.percentile(X_num_unnorm, 2.5, axis=0) # hi = np.percentile(X_num_unnorm, 97.5, axis=0) # idx = (lo < X_num_unnorm) & (hi > X_num_unnorm) # X_gen = X_gen[np.all(idx, axis=1)] # y_gen = y_gen[np.all(idx, axis=1)] ###
num_numerical_features = num_numerical_features + int(D.is_regression and not model_params["is_y_cond"])
X_num_ = X_gen if num_numerical_features < X_gen.shape[1]: np.save(os.path.join(parent_dir, 'X_cat_unnorm'), X_gen[:, num_numerical_features:]) # _, _, cat_encoder = lib.cat_encode({'train': X_cat_real}, T_dict['cat_encoding'], y_real, T_dict['seed'], True) if T_dict['cat_encoding'] == 'one-hot': X_gen[:, num_numerical_features:] = to_good_ohe(D.cat_transform.steps[0][1], X_num_[:, num_numerical_features:]) X_cat = D.cat_transform.inverse_transform(X_gen[:, num_numerical_features:])
if num_numerical_features_ != 0: # _, normalize = lib.normalize({'train' : X_num_real}, T_dict['normalization'], T_dict['seed'], True) np.save(os.path.join(parent_dir, 'X_num_unnorm'), X_gen[:, :num_numerical_features]) X_num_ = D.num_transform.inverse_transform(X_gen[:, :num_numerical_features]) X_num = X_num_[:, :num_numerical_features]
X_num_real = np.load(os.path.join(real_data_path, "X_num_train.npy"), allow_pickle=True) disc_cols = [] for col in range(X_num_real.shape[1]): uniq_vals = np.unique(X_num_real[:, col]) if len(uniq_vals) <= 32 and ((uniq_vals - np.round(uniq_vals)) == 0).all(): disc_cols.append(col) print("Discrete cols:", disc_cols) # 仅当 regression 且 y 在 X_num 中(非 is_y_cond)时才提取 y;否则 y_gen 已由 sample_all 返回 if model_params['num_classes'] == 0 and not model_params.get('is_y_cond', True): y_gen = X_num[:, 0] X_num = X_num[:, 1:] if len(disc_cols): X_num = round_columns(X_num_real, X_num, disc_cols)
if num_numerical_features != 0: print("Num shape: ", X_num.shape) np.save(os.path.join(parent_dir, 'X_num_train'), X_num) if num_numerical_features < X_gen.shape[1]: np.save(os.path.join(parent_dir, 'X_cat_train'), X_cat) np.save(os.path.join(parent_dir, 'y_train'), y_gen)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158from copy import deepcopyimport torchimport osimport numpy as npimport zerofrom tab_ddpm import GaussianMultinomialDiffusionfrom scripts.utils_train import get_model, make_dataset, update_emaimport libimport pandas as pd
class Trainer: def __init__(self, diffusion, train_iter, lr, weight_decay, steps, device=torch.device('cuda:1')): self.diffusion = diffusion self.ema_model = deepcopy(self.diffusion._denoise_fn) for param in self.ema_model.parameters(): param.detach_()
self.train_iter = train_iter self.steps = steps self.init_lr = lr self.optimizer = torch.optim.AdamW(self.diffusion.parameters(), lr=lr, weight_decay=weight_decay) self.device = device self.loss_history = pd.DataFrame(columns=['step', 'mloss', 'gloss', 'loss']) self.log_every = 100 self.print_every = 500 self.ema_every = 1000
def _anneal_lr(self, step): frac_done = step / self.steps lr = self.init_lr * (1 - frac_done) for param_group in self.optimizer.param_groups: param_group["lr"] = lr
def _run_step(self, x, out_dict): x = x.to(self.device) for k in out_dict: out_dict[k] = out_dict[k].long().to(self.device) self.optimizer.zero_grad() loss_multi, loss_gauss = self.diffusion.mixed_loss(x, out_dict) loss = loss_multi + loss_gauss loss.backward() self.optimizer.step()
return loss_multi, loss_gauss
def run_loop(self): step = 0 curr_loss_multi = 0.0 curr_loss_gauss = 0.0
curr_count = 0 while step < self.steps: x, out_dict = next(self.train_iter) out_dict = {'y': out_dict} batch_loss_multi, batch_loss_gauss = self._run_step(x, out_dict)
self._anneal_lr(step)
curr_count += len(x) curr_loss_multi += batch_loss_multi.item() * len(x) curr_loss_gauss += batch_loss_gauss.item() * len(x)
if (step + 1) % self.log_every == 0: mloss = np.around(curr_loss_multi / curr_count, 4) gloss = np.around(curr_loss_gauss / curr_count, 4) if (step + 1) % self.print_every == 0: print(f'Step {(step + 1)}/{self.steps} MLoss: {mloss} GLoss: {gloss} Sum: {mloss + gloss}') self.loss_history.loc[len(self.loss_history)] =[step + 1, mloss, gloss, mloss + gloss] curr_count = 0 curr_loss_gauss = 0.0 curr_loss_multi = 0.0
update_ema(self.ema_model.parameters(), self.diffusion._denoise_fn.parameters())
step += 1
def train( parent_dir, real_data_path = 'data/higgs-small', steps = 1000, lr = 0.002, weight_decay = 1e-4, batch_size = 1024, model_type = 'mlp', model_params = None, num_timesteps = 1000, gaussian_loss_type = 'mse', scheduler = 'cosine', T_dict = None, num_numerical_features = 0, device = torch.device('cuda:1'), seed = 0, change_val = False): real_data_path = os.path.normpath(real_data_path) parent_dir = os.path.normpath(parent_dir)
zero.improve_reproducibility(seed)
T = lib.Transformations(**T_dict)
dataset = make_dataset( real_data_path, T, num_classes=model_params['num_classes'], is_y_cond=model_params['is_y_cond'], change_val=change_val )
K = np.array(dataset.get_category_sizes('train')) if len(K) == 0 or T_dict['cat_encoding'] == 'one-hot': K = np.array([0]) print(K)
num_numerical_features = dataset.X_num['train'].shape[1] if dataset.X_num is not None else 0 d_in = np.sum(K) + num_numerical_features model_params['d_in'] = d_in print(d_in) print(model_params) model = get_model( model_type, model_params, num_numerical_features, category_sizes=dataset.get_category_sizes('train') ) model.to(device)
# train_loader = lib.prepare_beton_loader(dataset, split='train', batch_size=batch_size) train_loader = lib.prepare_fast_dataloader(dataset, split='train', batch_size=batch_size)
diffusion = GaussianMultinomialDiffusion( num_classes=K, num_numerical_features=num_numerical_features, denoise_fn=model, gaussian_loss_type=gaussian_loss_type, num_timesteps=num_timesteps, scheduler=scheduler, device=device ) diffusion.to(device) diffusion.train()
trainer = Trainer( diffusion, train_loader, lr=lr, weight_decay=weight_decay, steps=steps, device=device ) trainer.run_loop()
trainer.loss_history.to_csv(os.path.join(parent_dir, 'loss.csv'), index=False) torch.save(diffusion._denoise_fn.state_dict(), os.path.join(parent_dir, 'model.pt')) torch.save(trainer.ema_model.state_dict(), os.path.join(parent_dir, 'model_ema.pt'))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145import optunaimport libimport argparsefrom eval_catboost import train_catboostfrom eval_mlp import train_mlpfrom pathlib import Path
parser = argparse.ArgumentParser()parser.add_argument('ds_name', type=str)parser.add_argument('model', type=str)parser.add_argument('tune_type', type=str)parser.add_argument('device', type=str)
args = parser.parse_args()data_path = Path(f"data/{args.ds_name}")best_params = None
assert args.tune_type in ("cv", "val")
def _suggest(trial: optuna.trial.Trial, distribution: str, label: str, *args): return getattr(trial, f'suggest_{distribution}')(label, *args)
def _suggest_optional(trial: optuna.trial.Trial, distribution: str, label: str, *args): if trial.suggest_categorical(f"optional_{label}", [True, False]): return _suggest(trial, distribution, label, *args) else: return 0.0
def _suggest_mlp_layers(trial: optuna.trial.Trial, mlp_d_layers: list[int]):
min_n_layers, max_n_layers = mlp_d_layers[0], mlp_d_layers[1] d_min, d_max = mlp_d_layers[2], mlp_d_layers[3]
def suggest_dim(name): t = trial.suggest_int(name, d_min, d_max) return 2 ** t
n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers) d_first = [suggest_dim('d_first')] if n_layers else [] d_middle = ( [suggest_dim('d_middle')] * (n_layers - 2) if n_layers > 2 else [] ) d_last = [suggest_dim('d_last')] if n_layers > 1 else [] d_layers = d_first + d_middle + d_last
return d_layers
def suggest_mlp_params(trial): params = {} params["lr"] = trial.suggest_loguniform("lr", 5e-5, 0.005) params["dropout"] = _suggest_optional(trial, "uniform", "dropout", 0.0, 0.5) params["weight_decay"] = _suggest_optional(trial, "loguniform", "weight_decay", 1e-6, 1e-2) params["d_layers"] = _suggest_mlp_layers(trial, [1, 8, 6, 10])
return params
def suggest_catboost_params(trial): params = {} params["learning_rate"] = trial.suggest_loguniform("learning_rate", 0.001, 1.0) params["depth"] = trial.suggest_int("depth", 3, 10) params["l2_leaf_reg"] = trial.suggest_uniform("l2_leaf_reg", 0.1, 10.0) params["bagging_temperature"] = trial.suggest_uniform("bagging_temperature", 0.0, 1.0) params["leaf_estimation_iterations"] = trial.suggest_int("leaf_estimation_iterations", 1, 10)
params = params | { "iterations": 2000, "early_stopping_rounds": 50, "od_pval": 0.001, "task_type": "CPU", # "GPU", may affect performance "thread_count": 4, # "devices": "0", # for GPU }
return params
def objective(trial): if args.model == "mlp": params = suggest_mlp_params(trial) train_func = train_mlp T_dict = { "seed": 0, "normalization": "quantile", "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": "one-hot", "y_policy": "default" } else: params = suggest_catboost_params(trial) train_func = train_catboost T_dict = { "seed": 0, "normalization": None, "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": None, "y_policy": "default" } trial.set_user_attr("params", params) if args.tune_type == "cv": score = 0.0 for fold in range(5): metrics_report = train_func( parent_dir=None, real_data_path=data_path / f"kfolds/{fold}", eval_type="real", T_dict=T_dict, params=params, change_val=False, device=args.device ) score += metrics_report.get_val_score() score /= 5
elif args.tune_type == "val": metrics_report = train_func( parent_dir=None, real_data_path=data_path, eval_type="real", T_dict=T_dict, params=params, change_val=False, device=args.device ) score = metrics_report.get_val_score() return score
study = optuna.create_study( direction='maximize', sampler=optuna.samplers.TPESampler(seed=0),)
study.optimize(objective, n_trials=100, show_progress_bar=True) bets_params = study.best_trial.user_attrs['params']
best_params_path = f"tuned_models/{args.model}/{args.ds_name}_{args.tune_type}.json"
lib.dump_json(bets_params, best_params_path)12from .gaussian_multinomial_diffsuion import * # noqafrom .modules import * # noqa123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993"""Based on https://github.com/openai/guided-diffusion/blob/main/guided_diffusionand https://github.com/ehoogeboom/multinomial_diffusion"""
import torch.nn.functional as Fimport torchimport math
import numpy as npfrom .utils import *
"""Based in part on: https://github.com/lucidrains/denoising-diffusion-pytorch/blob/5989f4c77eafcdc6be0fb4739f0f277a6dd7f7d8/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py#L281"""eps = 1e-8
def get_named_beta_schedule(schedule_name, num_diffusion_timesteps): """ Get a pre-defined beta schedule for the given name. The beta schedule library consists of beta schedules which remain similar in the limit of num_diffusion_timesteps. Beta schedules may be added, but should not be removed or changed once they are committed to maintain backwards compatibility. """ if schedule_name == "linear": # Linear schedule from Ho et al, extended to work for any number of # diffusion steps. scale = 1000 / num_diffusion_timesteps beta_start = scale * 0.0001 beta_end = scale * 0.02 return np.linspace( beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64 ) elif schedule_name == "cosine": return betas_for_alpha_bar( num_diffusion_timesteps, lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2, ) else: raise NotImplementedError(f"unknown beta schedule: {schedule_name}")
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): """ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. :param num_diffusion_timesteps: the number of betas to produce. :param alpha_bar: a lambda that takes an argument t from 0 to 1 and produces the cumulative product of (1-beta) up to that part of the diffusion process. :param max_beta: the maximum beta to use; use values lower than 1 to prevent singularities. """ betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps t2 = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) return np.array(betas)
class GaussianMultinomialDiffusion(torch.nn.Module): def __init__( self, num_classes: np.array, num_numerical_features: int, denoise_fn, num_timesteps=1000, gaussian_loss_type='mse', gaussian_parametrization='eps', multinomial_loss_type='vb_stochastic', parametrization='x0', scheduler='cosine', device=torch.device('cpu') ):
super(GaussianMultinomialDiffusion, self).__init__() assert multinomial_loss_type in ('vb_stochastic', 'vb_all') assert parametrization in ('x0', 'direct')
if multinomial_loss_type == 'vb_all': print('Computing the loss using the bound on _all_ timesteps.' ' This is expensive both in terms of memory and computation.')
self.num_numerical_features = num_numerical_features self.num_classes = num_classes # it as a vector [K1, K2, ..., Km] self.num_classes_expanded = torch.from_numpy( np.concatenate([num_classes[i].repeat(num_classes[i]) for i in range(len(num_classes))]) ).to(device)
self.slices_for_classes = [np.arange(self.num_classes[0])] offsets = np.cumsum(self.num_classes) for i in range(1, len(offsets)): self.slices_for_classes.append(np.arange(offsets[i - 1], offsets[i])) self.offsets = torch.from_numpy(np.append([0], offsets)).to(device)
self._denoise_fn = denoise_fn self.gaussian_loss_type = gaussian_loss_type self.gaussian_parametrization = gaussian_parametrization self.multinomial_loss_type = multinomial_loss_type self.num_timesteps = num_timesteps self.parametrization = parametrization self.scheduler = scheduler
alphas = 1. - get_named_beta_schedule(scheduler, num_timesteps) alphas = torch.tensor(alphas.astype('float64')) betas = 1. - alphas
log_alpha = np.log(alphas) log_cumprod_alpha = np.cumsum(log_alpha)
log_1_min_alpha = log_1_min_a(log_alpha) log_1_min_cumprod_alpha = log_1_min_a(log_cumprod_alpha)
alphas_cumprod = np.cumprod(alphas, axis=0) alphas_cumprod_prev = torch.tensor(np.append(1.0, alphas_cumprod[:-1])) alphas_cumprod_next = torch.tensor(np.append(alphas_cumprod[1:], 0.0)) sqrt_alphas_cumprod = np.sqrt(alphas_cumprod) sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - alphas_cumprod) sqrt_recip_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod) sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / alphas_cumprod - 1)
# Gaussian diffusion
self.posterior_variance = ( betas * (1.0 - alphas_cumprod_prev) / (1.0 - alphas_cumprod) ) self.posterior_log_variance_clipped = torch.from_numpy( np.log(np.append(self.posterior_variance[1], self.posterior_variance[1:])) ).float().to(device) self.posterior_mean_coef1 = ( betas * np.sqrt(alphas_cumprod_prev) / (1.0 - alphas_cumprod) ).float().to(device) self.posterior_mean_coef2 = ( (1.0 - alphas_cumprod_prev) * np.sqrt(alphas.numpy()) / (1.0 - alphas_cumprod) ).float().to(device)
assert log_add_exp(log_alpha, log_1_min_alpha).abs().sum().item() < 1.e-5 assert log_add_exp(log_cumprod_alpha, log_1_min_cumprod_alpha).abs().sum().item() < 1e-5 assert (np.cumsum(log_alpha) - log_cumprod_alpha).abs().sum().item() < 1.e-5
# Convert to float32 and register buffers. self.register_buffer('alphas', alphas.float().to(device)) self.register_buffer('log_alpha', log_alpha.float().to(device)) self.register_buffer('log_1_min_alpha', log_1_min_alpha.float().to(device)) self.register_buffer('log_1_min_cumprod_alpha', log_1_min_cumprod_alpha.float().to(device)) self.register_buffer('log_cumprod_alpha', log_cumprod_alpha.float().to(device)) self.register_buffer('alphas_cumprod', alphas_cumprod.float().to(device)) self.register_buffer('alphas_cumprod_prev', alphas_cumprod_prev.float().to(device)) self.register_buffer('alphas_cumprod_next', alphas_cumprod_next.float().to(device)) self.register_buffer('sqrt_alphas_cumprod', sqrt_alphas_cumprod.float().to(device)) self.register_buffer('sqrt_one_minus_alphas_cumprod', sqrt_one_minus_alphas_cumprod.float().to(device)) self.register_buffer('sqrt_recip_alphas_cumprod', sqrt_recip_alphas_cumprod.float().to(device)) self.register_buffer('sqrt_recipm1_alphas_cumprod', sqrt_recipm1_alphas_cumprod.float().to(device))
self.register_buffer('Lt_history', torch.zeros(num_timesteps)) self.register_buffer('Lt_count', torch.zeros(num_timesteps)) # Gaussian part def gaussian_q_mean_variance(self, x_start, t): mean = ( extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start ) variance = extract(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = extract( self.log_1_min_cumprod_alpha, t, x_start.shape ) return mean, variance, log_variance def gaussian_q_sample(self, x_start, t, noise=None): if noise is None: noise = torch.randn_like(x_start) assert noise.shape == x_start.shape return ( extract(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + extract(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise ) def gaussian_q_posterior_mean_variance(self, x_start, x_t, t): assert x_start.shape == x_t.shape posterior_mean = ( extract(self.posterior_mean_coef1, t, x_t.shape) * x_start + extract(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = extract(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = extract( self.posterior_log_variance_clipped, t, x_t.shape ) assert ( posterior_mean.shape[0] == posterior_variance.shape[0] == posterior_log_variance_clipped.shape[0] == x_start.shape[0] ) return posterior_mean, posterior_variance, posterior_log_variance_clipped
def gaussian_p_mean_variance( self, model_output, x, t, clip_denoised=False, denoised_fn=None, model_kwargs=None ): if model_kwargs is None: model_kwargs = {}
B, C = x.shape[:2] assert t.shape == (B,)
model_variance = torch.cat([self.posterior_variance[1].unsqueeze(0).to(x.device), (1. - self.alphas)[1:]], dim=0) # model_variance = self.posterior_variance.to(x.device) model_log_variance = torch.log(model_variance)
model_variance = extract(model_variance, t, x.shape) model_log_variance = extract(model_log_variance, t, x.shape)
if self.gaussian_parametrization == 'eps': pred_xstart = self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output) elif self.gaussian_parametrization == 'x0': pred_xstart = model_output else: raise NotImplementedError model_mean, _, _ = self.gaussian_q_posterior_mean_variance( x_start=pred_xstart, x_t=x, t=t )
assert ( model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape ), f'{model_mean.shape}, {model_log_variance.shape}, {pred_xstart.shape}, {x.shape}'
return { "mean": model_mean, "variance": model_variance, "log_variance": model_log_variance, "pred_xstart": pred_xstart, } def _vb_terms_bpd( self, model_output, x_start, x_t, t, clip_denoised=False, model_kwargs=None ): true_mean, _, true_log_variance_clipped = self.gaussian_q_posterior_mean_variance( x_start=x_start, x_t=x_t, t=t ) out = self.gaussian_p_mean_variance( model_output, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs ) kl = normal_kl( true_mean, true_log_variance_clipped, out["mean"], out["log_variance"] ) kl = mean_flat(kl) / np.log(2.0)
decoder_nll = -discretized_gaussian_log_likelihood( x_start, means=out["mean"], log_scales=0.5 * out["log_variance"] ) assert decoder_nll.shape == x_start.shape decoder_nll = mean_flat(decoder_nll) / np.log(2.0)
# At the first timestep return the decoder NLL, # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t)) output = torch.where((t == 0), decoder_nll, kl) return {"output": output, "pred_xstart": out["pred_xstart"], "out_mean": out["mean"], "true_mean": true_mean} def _prior_gaussian(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim.
This term can't be optimized, as it only depends on the encoder.
:param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.gaussian_q_mean_variance(x_start, t) kl_prior = normal_kl( mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0 ) return mean_flat(kl_prior) / np.log(2.0) def _gaussian_loss(self, model_out, x_start, x_t, t, noise, model_kwargs=None): if model_kwargs is None: model_kwargs = {}
terms = {} if self.gaussian_loss_type == 'mse': terms["loss"] = mean_flat((noise - model_out) ** 2) elif self.gaussian_loss_type == 'kl': terms["loss"] = self._vb_terms_bpd( model_output=model_out, x_start=x_start, x_t=x_t, t=t, clip_denoised=False, model_kwargs=model_kwargs, )["output"]
return terms['loss'] def _predict_xstart_from_eps(self, x_t, t, eps): assert x_t.shape == eps.shape return ( extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps ) def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return ( extract(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart ) / extract(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
def gaussian_p_sample( self, model_out, x, t, clip_denoised=False, denoised_fn=None, model_kwargs=None, ): out = self.gaussian_p_mean_variance( model_out, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) noise = torch.randn_like(x) nonzero_mask = ( (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) ) # no noise when t == 0
sample = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * noise return {"sample": sample, "pred_xstart": out["pred_xstart"]}
# Multinomial part
def multinomial_kl(self, log_prob1, log_prob2): kl = (log_prob1.exp() * (log_prob1 - log_prob2)).sum(dim=1) return kl
def q_pred_one_timestep(self, log_x_t, t): log_alpha_t = extract(self.log_alpha, t, log_x_t.shape) log_1_min_alpha_t = extract(self.log_1_min_alpha, t, log_x_t.shape)
# alpha_t * E[xt] + (1 - alpha_t) 1 / K log_probs = log_add_exp( log_x_t + log_alpha_t, log_1_min_alpha_t - torch.log(self.num_classes_expanded) )
return log_probs
def q_pred(self, log_x_start, t): log_cumprod_alpha_t = extract(self.log_cumprod_alpha, t, log_x_start.shape) log_1_min_cumprod_alpha = extract(self.log_1_min_cumprod_alpha, t, log_x_start.shape)
log_probs = log_add_exp( log_x_start + log_cumprod_alpha_t, log_1_min_cumprod_alpha - torch.log(self.num_classes_expanded) )
return log_probs
def predict_start(self, model_out, log_x_t, t, out_dict):
# model_out = self._denoise_fn(x_t, t.to(x_t.device), **out_dict)
assert model_out.size(0) == log_x_t.size(0) assert model_out.size(1) == self.num_classes.sum(), f'{model_out.size()}'
log_pred = torch.empty_like(model_out) for ix in self.slices_for_classes: log_pred[:, ix] = F.log_softmax(model_out[:, ix], dim=1) return log_pred
def q_posterior(self, log_x_start, log_x_t, t): # q(xt-1 | xt, x0) = q(xt | xt-1, x0) * q(xt-1 | x0) / q(xt | x0) # where q(xt | xt-1, x0) = q(xt | xt-1).
# EV_log_qxt_x0 = self.q_pred(log_x_start, t)
# print('sum exp', EV_log_qxt_x0.exp().sum(1).mean()) # assert False
# log_qxt_x0 = (log_x_t.exp() * EV_log_qxt_x0).sum(dim=1) t_minus_1 = t - 1 # Remove negative values, will not be used anyway for final decoder t_minus_1 = torch.where(t_minus_1 < 0, torch.zeros_like(t_minus_1), t_minus_1) log_EV_qxtmin_x0 = self.q_pred(log_x_start, t_minus_1)
num_axes = (1,) * (len(log_x_start.size()) - 1) t_broadcast = t.to(log_x_start.device).view(-1, *num_axes) * torch.ones_like(log_x_start) log_EV_qxtmin_x0 = torch.where(t_broadcast == 0, log_x_start, log_EV_qxtmin_x0.to(torch.float32))
# unnormed_logprobs = log_EV_qxtmin_x0 + # log q_pred_one_timestep(x_t, t) # Note: _NOT_ x_tmin1, which is how the formula is typically used!!! # Not very easy to see why this is true. But it is :) unnormed_logprobs = log_EV_qxtmin_x0 + self.q_pred_one_timestep(log_x_t, t)
log_EV_xtmin_given_xt_given_xstart = \ unnormed_logprobs \ - sliced_logsumexp(unnormed_logprobs, self.offsets)
return log_EV_xtmin_given_xt_given_xstart
def p_pred(self, model_out, log_x, t, out_dict): if self.parametrization == 'x0': log_x_recon = self.predict_start(model_out, log_x, t=t, out_dict=out_dict) log_model_pred = self.q_posterior( log_x_start=log_x_recon, log_x_t=log_x, t=t) elif self.parametrization == 'direct': log_model_pred = self.predict_start(model_out, log_x, t=t, out_dict=out_dict) else: raise ValueError return log_model_pred
@torch.no_grad() def p_sample(self, model_out, log_x, t, out_dict): model_log_prob = self.p_pred(model_out, log_x=log_x, t=t, out_dict=out_dict) out = self.log_sample_categorical(model_log_prob) return out
@torch.no_grad() def p_sample_loop(self, shape, out_dict): device = self.log_alpha.device
b = shape[0] # start with random normal image. img = torch.randn(shape, device=device)
for i in reversed(range(1, self.num_timesteps)): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long), out_dict) return img
@torch.no_grad() def _sample(self, image_size, out_dict, batch_size = 16): return self.p_sample_loop((batch_size, 3, image_size, image_size), out_dict)
@torch.no_grad() def interpolate(self, x1, x2, t = None, lam = 0.5): b, *_, device = *x1.shape, x1.device t = default(t, self.num_timesteps - 1)
assert x1.shape == x2.shape
t_batched = torch.stack([torch.tensor(t, device=device)] * b) xt1, xt2 = map(lambda x: self.q_sample(x, t=t_batched), (x1, x2))
img = (1 - lam) * xt1 + lam * xt2 for i in reversed(range(0, t)): img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long))
return img
def log_sample_categorical(self, logits): full_sample = [] for i in range(len(self.num_classes)): one_class_logits = logits[:, self.slices_for_classes[i]] uniform = torch.rand_like(one_class_logits) gumbel_noise = -torch.log(-torch.log(uniform + 1e-30) + 1e-30) sample = (gumbel_noise + one_class_logits).argmax(dim=1) full_sample.append(sample.unsqueeze(1)) full_sample = torch.cat(full_sample, dim=1) log_sample = index_to_log_onehot(full_sample, self.num_classes) return log_sample
def q_sample(self, log_x_start, t): log_EV_qxt_x0 = self.q_pred(log_x_start, t)
log_sample = self.log_sample_categorical(log_EV_qxt_x0)
return log_sample
def nll(self, log_x_start, out_dict): b = log_x_start.size(0) device = log_x_start.device loss = 0 for t in range(0, self.num_timesteps): t_array = (torch.ones(b, device=device) * t).long()
kl = self.compute_Lt( log_x_start=log_x_start, log_x_t=self.q_sample(log_x_start=log_x_start, t=t_array), t=t_array, out_dict=out_dict)
loss += kl
loss += self.kl_prior(log_x_start)
return loss
def kl_prior(self, log_x_start): b = log_x_start.size(0) device = log_x_start.device ones = torch.ones(b, device=device).long()
log_qxT_prob = self.q_pred(log_x_start, t=(self.num_timesteps - 1) * ones) log_half_prob = -torch.log(self.num_classes_expanded * torch.ones_like(log_qxT_prob))
kl_prior = self.multinomial_kl(log_qxT_prob, log_half_prob) return sum_except_batch(kl_prior)
def compute_Lt(self, model_out, log_x_start, log_x_t, t, out_dict, detach_mean=False): log_true_prob = self.q_posterior( log_x_start=log_x_start, log_x_t=log_x_t, t=t) log_model_prob = self.p_pred(model_out, log_x=log_x_t, t=t, out_dict=out_dict)
if detach_mean: log_model_prob = log_model_prob.detach()
kl = self.multinomial_kl(log_true_prob, log_model_prob) kl = sum_except_batch(kl)
decoder_nll = -log_categorical(log_x_start, log_model_prob) decoder_nll = sum_except_batch(decoder_nll)
mask = (t == torch.zeros_like(t)).float() loss = mask * decoder_nll + (1. - mask) * kl
return loss
def sample_time(self, b, device, method='uniform'): if method == 'importance': if not (self.Lt_count > 10).all(): return self.sample_time(b, device, method='uniform')
Lt_sqrt = torch.sqrt(self.Lt_history + 1e-10) + 0.0001 Lt_sqrt[0] = Lt_sqrt[1] # Overwrite decoder term with L1. pt_all = (Lt_sqrt / Lt_sqrt.sum()).to(device)
t = torch.multinomial(pt_all, num_samples=b, replacement=True).to(device)
pt = pt_all.gather(dim=0, index=t)
return t, pt
elif method == 'uniform': t = torch.randint(0, self.num_timesteps, (b,), device=device).long()
pt = torch.ones_like(t).float() / self.num_timesteps return t, pt else: raise ValueError
def _multinomial_loss(self, model_out, log_x_start, log_x_t, t, pt, out_dict):
if self.multinomial_loss_type == 'vb_stochastic': kl = self.compute_Lt( model_out, log_x_start, log_x_t, t, out_dict ) kl_prior = self.kl_prior(log_x_start) # Upweigh loss term of the kl vb_loss = kl / pt + kl_prior
return vb_loss
elif self.multinomial_loss_type == 'vb_all': # Expensive, dont do it ;). # DEPRECATED return -self.nll(log_x_start) else: raise ValueError()
def log_prob(self, x, out_dict): b, device = x.size(0), x.device if self.training: return self._multinomial_loss(x, out_dict)
else: log_x_start = index_to_log_onehot(x, self.num_classes)
t, pt = self.sample_time(b, device, 'importance')
kl = self.compute_Lt( log_x_start, self.q_sample(log_x_start=log_x_start, t=t), t, out_dict)
kl_prior = self.kl_prior(log_x_start)
# Upweigh loss term of the kl loss = kl / pt + kl_prior
return -loss def mixed_loss(self, x, out_dict): b = x.shape[0] device = x.device t, pt = self.sample_time(b, device, 'uniform')
x_num = x[:, :self.num_numerical_features] x_cat = x[:, self.num_numerical_features:] x_num_t = x_num log_x_cat_t = x_cat if x_num.shape[1] > 0: noise = torch.randn_like(x_num) x_num_t = self.gaussian_q_sample(x_num, t, noise=noise) if x_cat.shape[1] > 0: log_x_cat = index_to_log_onehot(x_cat.long(), self.num_classes) log_x_cat_t = self.q_sample(log_x_start=log_x_cat, t=t) x_in = torch.cat([x_num_t, log_x_cat_t], dim=1)
model_out = self._denoise_fn( x_in, t, **out_dict )
model_out_num = model_out[:, :self.num_numerical_features] model_out_cat = model_out[:, self.num_numerical_features:]
loss_multi = torch.zeros((1,)).float() loss_gauss = torch.zeros((1,)).float() if x_cat.shape[1] > 0: loss_multi = self._multinomial_loss(model_out_cat, log_x_cat, log_x_cat_t, t, pt, out_dict) / len(self.num_classes) if x_num.shape[1] > 0: loss_gauss = self._gaussian_loss(model_out_num, x_num, x_num_t, t, noise)
# loss_multi = torch.where(out_dict['y'] == 1, loss_multi, 2 * loss_multi) # loss_gauss = torch.where(out_dict['y'] == 1, loss_gauss, 2 * loss_gauss)
return loss_multi.mean(), loss_gauss.mean() @torch.no_grad() def mixed_elbo(self, x0, out_dict): b = x0.size(0) device = x0.device
x_num = x0[:, :self.num_numerical_features] x_cat = x0[:, self.num_numerical_features:] has_cat = x_cat.shape[1] > 0 if has_cat: log_x_cat = index_to_log_onehot(x_cat.long(), self.num_classes).to(device)
gaussian_loss = [] xstart_mse = [] mse = [] mu_mse = [] out_mean = [] true_mean = [] multinomial_loss = [] for t in range(self.num_timesteps): t_array = (torch.ones(b, device=device) * t).long() noise = torch.randn_like(x_num)
x_num_t = self.gaussian_q_sample(x_start=x_num, t=t_array, noise=noise) if has_cat: log_x_cat_t = self.q_sample(log_x_start=log_x_cat, t=t_array) else: log_x_cat_t = x_cat
model_out = self._denoise_fn( torch.cat([x_num_t, log_x_cat_t], dim=1), t_array, **out_dict ) model_out_num = model_out[:, :self.num_numerical_features] model_out_cat = model_out[:, self.num_numerical_features:]
kl = torch.tensor([0.0]) if has_cat: kl = self.compute_Lt( model_out=model_out_cat, log_x_start=log_x_cat, log_x_t=log_x_cat_t, t=t_array, out_dict=out_dict )
out = self._vb_terms_bpd( model_out_num, x_start=x_num, x_t=x_num_t, t=t_array, clip_denoised=False )
multinomial_loss.append(kl) gaussian_loss.append(out["output"]) xstart_mse.append(mean_flat((out["pred_xstart"] - x_num) ** 2)) # mu_mse.append(mean_flat(out["mean_mse"])) out_mean.append(mean_flat(out["out_mean"])) true_mean.append(mean_flat(out["true_mean"]))
eps = self._predict_eps_from_xstart(x_num_t, t_array, out["pred_xstart"]) mse.append(mean_flat((eps - noise) ** 2))
gaussian_loss = torch.stack(gaussian_loss, dim=1) multinomial_loss = torch.stack(multinomial_loss, dim=1) xstart_mse = torch.stack(xstart_mse, dim=1) mse = torch.stack(mse, dim=1) # mu_mse = torch.stack(mu_mse, dim=1) out_mean = torch.stack(out_mean, dim=1) true_mean = torch.stack(true_mean, dim=1)
prior_gauss = self._prior_gaussian(x_num)
prior_multin = torch.tensor([0.0]) if has_cat: prior_multin = self.kl_prior(log_x_cat)
total_gauss = gaussian_loss.sum(dim=1) + prior_gauss total_multin = multinomial_loss.sum(dim=1) + prior_multin return { "total_gaussian": total_gauss, "total_multinomial": total_multin, "losses_gaussian": gaussian_loss, "losses_multinimial": multinomial_loss, "xstart_mse": xstart_mse, "mse": mse, # "mu_mse": mu_mse "out_mean": out_mean, "true_mean": true_mean }
@torch.no_grad() def gaussian_ddim_step( self, model_out_num, x, t, clip_denoised=False, denoised_fn=None, eta=0.0 ): out = self.gaussian_p_mean_variance( model_out_num, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=None, )
eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"])
alpha_bar = extract(self.alphas_cumprod, t, x.shape) alpha_bar_prev = extract(self.alphas_cumprod_prev, t, x.shape) sigma = ( eta * torch.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar)) * torch.sqrt(1 - alpha_bar / alpha_bar_prev) )
noise = torch.randn_like(x) mean_pred = ( out["pred_xstart"] * torch.sqrt(alpha_bar_prev) + torch.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps ) nonzero_mask = ( (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) ) # no noise when t == 0 sample = mean_pred + nonzero_mask * sigma * noise
return sample @torch.no_grad() def gaussian_ddim_sample( self, noise, T, out_dict, eta=0.0 ): x = noise b = x.shape[0] device = x.device for t in reversed(range(T)): print(f'Sample timestep {t:4d}', end='\r') t_array = (torch.ones(b, device=device) * t).long() out_num = self._denoise_fn(x, t_array, **out_dict) x = self.gaussian_ddim_step( out_num, x, t_array ) print() return x
@torch.no_grad() def gaussian_ddim_reverse_step( self, model_out_num, x, t, clip_denoised=False, eta=0.0 ): assert eta == 0.0, "Eta must be zero." out = self.gaussian_p_mean_variance( model_out_num, x, t, clip_denoised=clip_denoised, denoised_fn=None, model_kwargs=None, )
eps = ( extract(self.sqrt_recip_alphas_cumprod, t, x.shape) * x - out["pred_xstart"] ) / extract(self.sqrt_recipm1_alphas_cumprod, t, x.shape) alpha_bar_next = extract(self.alphas_cumprod_next, t, x.shape)
mean_pred = ( out["pred_xstart"] * torch.sqrt(alpha_bar_next) + torch.sqrt(1 - alpha_bar_next) * eps )
return mean_pred
@torch.no_grad() def gaussian_ddim_reverse_sample( self, x, T, out_dict, ): b = x.shape[0] device = x.device for t in range(T): print(f'Reverse timestep {t:4d}', end='\r') t_array = (torch.ones(b, device=device) * t).long() out_num = self._denoise_fn(x, t_array, **out_dict) x = self.gaussian_ddim_reverse_step( out_num, x, t_array, eta=0.0 ) print()
return x
@torch.no_grad() def multinomial_ddim_step( self, model_out_cat, log_x_t, t, out_dict, eta=0.0 ): # not ddim, essentially log_x0 = self.predict_start(model_out_cat, log_x_t=log_x_t, t=t, out_dict=out_dict)
alpha_bar = extract(self.alphas_cumprod, t, log_x_t.shape) alpha_bar_prev = extract(self.alphas_cumprod_prev, t, log_x_t.shape) sigma = ( eta * torch.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar)) * torch.sqrt(1 - alpha_bar / alpha_bar_prev) )
coef1 = sigma coef2 = alpha_bar_prev - sigma * alpha_bar coef3 = 1 - coef1 - coef2
log_ps = torch.stack([ torch.log(coef1) + log_x_t, torch.log(coef2) + log_x0, torch.log(coef3) - torch.log(self.num_classes_expanded) ], dim=2)
log_prob = torch.logsumexp(log_ps, dim=2)
out = self.log_sample_categorical(log_prob)
return out
@torch.no_grad() def sample_ddim(self, num_samples, y_dist): b = num_samples device = self.log_alpha.device z_norm = torch.randn((b, self.num_numerical_features), device=device)
has_cat = self.num_classes[0] != 0 log_z = torch.zeros((b, 0), device=device).float() if has_cat: uniform_logits = torch.zeros((b, len(self.num_classes_expanded)), device=device) log_z = self.log_sample_categorical(uniform_logits)
y = torch.multinomial( y_dist, num_samples=b, replacement=True ) out_dict = {'y': y.long().to(device)} for i in reversed(range(0, self.num_timesteps)): print(f'Sample timestep {i:4d}', end='\r') t = torch.full((b,), i, device=device, dtype=torch.long) model_out = self._denoise_fn( torch.cat([z_norm, log_z], dim=1).float(), t, **out_dict ) model_out_num = model_out[:, :self.num_numerical_features] model_out_cat = model_out[:, self.num_numerical_features:] z_norm = self.gaussian_ddim_step(model_out_num, z_norm, t, clip_denoised=False) if has_cat: log_z = self.multinomial_ddim_step(model_out_cat, log_z, t, out_dict)
print() z_ohe = torch.exp(log_z).round() z_cat = log_z if has_cat: z_cat = ohe_to_categories(z_ohe, self.num_classes) sample = torch.cat([z_norm, z_cat], dim=1).cpu() return sample, out_dict
@torch.no_grad() def sample(self, num_samples, y_dist): b = num_samples device = self.log_alpha.device z_norm = torch.randn((b, self.num_numerical_features), device=device)
has_cat = self.num_classes[0] != 0 log_z = torch.zeros((b, 0), device=device).float() if has_cat: uniform_logits = torch.zeros((b, len(self.num_classes_expanded)), device=device) log_z = self.log_sample_categorical(uniform_logits)
y = torch.multinomial( y_dist, num_samples=b, replacement=True ) out_dict = {'y': y.long().to(device)} for i in reversed(range(0, self.num_timesteps)): print(f'Sample timestep {i:4d}', end='\r') t = torch.full((b,), i, device=device, dtype=torch.long) model_out = self._denoise_fn( torch.cat([z_norm, log_z], dim=1).float(), t, **out_dict ) model_out_num = model_out[:, :self.num_numerical_features] model_out_cat = model_out[:, self.num_numerical_features:] z_norm = self.gaussian_p_sample(model_out_num, z_norm, t, clip_denoised=False)['sample'] if has_cat: log_z = self.p_sample(model_out_cat, log_z, t, out_dict)
print() z_ohe = torch.exp(log_z).round() z_cat = log_z if has_cat: z_cat = ohe_to_categories(z_ohe, self.num_classes) sample = torch.cat([z_norm, z_cat], dim=1).cpu() return sample, out_dict def sample_all(self, num_samples, batch_size, y_dist, ddim=False): if ddim: print('Sample using DDIM.') sample_fn = self.sample_ddim else: sample_fn = self.sample b = batch_size
all_y = [] all_samples = [] num_generated = 0 while num_generated < num_samples: sample, out_dict = sample_fn(b, y_dist) mask_nan = torch.any(sample.isnan(), dim=1) sample = sample[~mask_nan] out_dict['y'] = out_dict['y'][~mask_nan]
all_samples.append(sample) all_y.append(out_dict['y'].cpu()) if sample.shape[0] != b: raise FoundNANsError num_generated += sample.shape[0]
x_gen = torch.cat(all_samples, dim=0)[:num_samples] y_gen = torch.cat(all_y, dim=0)[:num_samples]
return x_gen, y_gen123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486"""Code was adapted from https://github.com/Yura52/rtdl"""
import mathfrom typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union, cast
import torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.optimfrom torch import Tensor
ModuleType = Union[str, Callable[..., nn.Module]]
class SiLU(nn.Module): def forward(self, x): return x * torch.sigmoid(x)
def timestep_embedding(timesteps, dim, max_period=10000): """ Create sinusoidal timestep embeddings.
:param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an [N x dim] Tensor of positional embeddings. """ half = dim // 2 freqs = torch.exp( -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half ).to(device=timesteps.device) args = timesteps[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) return embedding
def _is_glu_activation(activation: ModuleType): return ( isinstance(activation, str) and activation.endswith('GLU') or activation in [ReGLU, GEGLU] )
def _all_or_none(values): assert all(x is None for x in values) or all(x is not None for x in values)
def reglu(x: Tensor) -> Tensor: """The ReGLU activation function from [1]. References: [1] Noam Shazeer, "GLU Variants Improve Transformer", 2020 """ assert x.shape[-1] % 2 == 0 a, b = x.chunk(2, dim=-1) return a * F.relu(b)
def geglu(x: Tensor) -> Tensor: """The GEGLU activation function from [1]. References: [1] Noam Shazeer, "GLU Variants Improve Transformer", 2020 """ assert x.shape[-1] % 2 == 0 a, b = x.chunk(2, dim=-1) return a * F.gelu(b)
class ReGLU(nn.Module): """The ReGLU activation function from [shazeer2020glu].
Examples: .. testcode::
module = ReGLU() x = torch.randn(3, 4) assert module(x).shape == (3, 2)
References: * [shazeer2020glu] Noam Shazeer, "GLU Variants Improve Transformer", 2020 """
def forward(self, x: Tensor) -> Tensor: return reglu(x)
class GEGLU(nn.Module): """The GEGLU activation function from [shazeer2020glu].
Examples: .. testcode::
module = GEGLU() x = torch.randn(3, 4) assert module(x).shape == (3, 2)
References: * [shazeer2020glu] Noam Shazeer, "GLU Variants Improve Transformer", 2020 """
def forward(self, x: Tensor) -> Tensor: return geglu(x)
def _make_nn_module(module_type: ModuleType, *args) -> nn.Module: return ( ( ReGLU() if module_type == 'ReGLU' else GEGLU() if module_type == 'GEGLU' else getattr(nn, module_type)(*args) ) if isinstance(module_type, str) else module_type(*args) )
class MLP(nn.Module): """The MLP model used in [gorishniy2021revisiting].
The following scheme describes the architecture:
.. code-block:: text
MLP: (in) -> Block -> ... -> Block -> Linear -> (out) Block: (in) -> Linear -> Activation -> Dropout -> (out)
Examples: .. testcode::
x = torch.randn(4, 2) module = MLP.make_baseline(x.shape[1], [3, 5], 0.1, 1) assert module(x).shape == (len(x), 1)
References: * [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021 """
class Block(nn.Module): """The main building block of `MLP`."""
def __init__( self, *, d_in: int, d_out: int, bias: bool, activation: ModuleType, dropout: float, ) -> None: super().__init__() self.linear = nn.Linear(d_in, d_out, bias) self.activation = _make_nn_module(activation) self.dropout = nn.Dropout(dropout)
def forward(self, x: Tensor) -> Tensor: return self.dropout(self.activation(self.linear(x)))
def __init__( self, *, d_in: int, d_layers: List[int], dropouts: Union[float, List[float]], activation: Union[str, Callable[[], nn.Module]], d_out: int, ) -> None: """ Note: `make_baseline` is the recommended constructor. """ super().__init__() if isinstance(dropouts, float): dropouts = [dropouts] * len(d_layers) assert len(d_layers) == len(dropouts) assert activation not in ['ReGLU', 'GEGLU']
self.blocks = nn.ModuleList( [ MLP.Block( d_in=d_layers[i - 1] if i else d_in, d_out=d, bias=True, activation=activation, dropout=dropout, ) for i, (d, dropout) in enumerate(zip(d_layers, dropouts)) ] ) self.head = nn.Linear(d_layers[-1] if d_layers else d_in, d_out)
@classmethod def make_baseline( cls: Type['MLP'], d_in: int, d_layers: List[int], dropout: float, d_out: int, ) -> 'MLP': """Create a "baseline" `MLP`.
This variation of MLP was used in [gorishniy2021revisiting]. Features:
* :code:`Activation` = :code:`ReLU` * all linear layers except for the first one and the last one are of the same dimension * the dropout rate is the same for all dropout layers
Args: d_in: the input size d_layers: the dimensions of the linear layers. If there are more than two layers, then all of them except for the first and the last ones must have the same dimension. Valid examples: :code:`[]`, :code:`[8]`, :code:`[8, 16]`, :code:`[2, 2, 2, 2]`, :code:`[1, 2, 2, 4]`. Invalid example: :code:`[1, 2, 3, 4]`. dropout: the dropout rate for all hidden layers d_out: the output size Returns: MLP
References: * [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021 """ assert isinstance(dropout, float) if len(d_layers) > 2: assert len(set(d_layers[1:-1])) == 1, ( 'if d_layers contains more than two elements, then' ' all elements except for the first and the last ones must be equal.' ) return MLP( d_in=d_in, d_layers=d_layers, # type: ignore dropouts=dropout, activation='ReLU', d_out=d_out, )
def forward(self, x: Tensor) -> Tensor: x = x.float() for block in self.blocks: x = block(x) x = self.head(x) return x
class ResNet(nn.Module): """The ResNet model used in [gorishniy2021revisiting]. The following scheme describes the architecture: .. code-block:: text ResNet: (in) -> Linear -> Block -> ... -> Block -> Head -> (out) |-> Norm -> Linear -> Activation -> Dropout -> Linear -> Dropout ->| | | Block: (in) ------------------------------------------------------------> Add -> (out) Head: (in) -> Norm -> Activation -> Linear -> (out) Examples: .. testcode:: x = torch.randn(4, 2) module = ResNet.make_baseline( d_in=x.shape[1], n_blocks=2, d_main=3, d_hidden=4, dropout_first=0.25, dropout_second=0.0, d_out=1 ) assert module(x).shape == (len(x), 1) References: * [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021 """
class Block(nn.Module): """The main building block of `ResNet`."""
def __init__( self, *, d_main: int, d_hidden: int, bias_first: bool, bias_second: bool, dropout_first: float, dropout_second: float, normalization: ModuleType, activation: ModuleType, skip_connection: bool, ) -> None: super().__init__() self.normalization = _make_nn_module(normalization, d_main) self.linear_first = nn.Linear(d_main, d_hidden, bias_first) self.activation = _make_nn_module(activation) self.dropout_first = nn.Dropout(dropout_first) self.linear_second = nn.Linear(d_hidden, d_main, bias_second) self.dropout_second = nn.Dropout(dropout_second) self.skip_connection = skip_connection
def forward(self, x: Tensor) -> Tensor: x_input = x x = self.normalization(x) x = self.linear_first(x) x = self.activation(x) x = self.dropout_first(x) x = self.linear_second(x) x = self.dropout_second(x) if self.skip_connection: x = x_input + x return x
class Head(nn.Module): """The final module of `ResNet`."""
def __init__( self, *, d_in: int, d_out: int, bias: bool, normalization: ModuleType, activation: ModuleType, ) -> None: super().__init__() self.normalization = _make_nn_module(normalization, d_in) self.activation = _make_nn_module(activation) self.linear = nn.Linear(d_in, d_out, bias)
def forward(self, x: Tensor) -> Tensor: if self.normalization is not None: x = self.normalization(x) x = self.activation(x) x = self.linear(x) return x
def __init__( self, *, d_in: int, n_blocks: int, d_main: int, d_hidden: int, dropout_first: float, dropout_second: float, normalization: ModuleType, activation: ModuleType, d_out: int, ) -> None: """ Note: `make_baseline` is the recommended constructor. """ super().__init__()
self.first_layer = nn.Linear(d_in, d_main) if d_main is None: d_main = d_in self.blocks = nn.Sequential( *[ ResNet.Block( d_main=d_main, d_hidden=d_hidden, bias_first=True, bias_second=True, dropout_first=dropout_first, dropout_second=dropout_second, normalization=normalization, activation=activation, skip_connection=True, ) for _ in range(n_blocks) ] ) self.head = ResNet.Head( d_in=d_main, d_out=d_out, bias=True, normalization=normalization, activation=activation, )
@classmethod def make_baseline( cls: Type['ResNet'], *, d_in: int, n_blocks: int, d_main: int, d_hidden: int, dropout_first: float, dropout_second: float, d_out: int, ) -> 'ResNet': """Create a "baseline" `ResNet`. This variation of ResNet was used in [gorishniy2021revisiting]. Features: * :code:`Activation` = :code:`ReLU` * :code:`Norm` = :code:`BatchNorm1d` Args: d_in: the input size n_blocks: the number of Blocks d_main: the input size (or, equivalently, the output size) of each Block d_hidden: the output size of the first linear layer in each Block dropout_first: the dropout rate of the first dropout layer in each Block. dropout_second: the dropout rate of the second dropout layer in each Block. References: * [gorishniy2021revisiting] Yury Gorishniy, Ivan Rubachev, Valentin Khrulkov, Artem Babenko, "Revisiting Deep Learning Models for Tabular Data", 2021 """ return cls( d_in=d_in, n_blocks=n_blocks, d_main=d_main, d_hidden=d_hidden, dropout_first=dropout_first, dropout_second=dropout_second, normalization='BatchNorm1d', activation='ReLU', d_out=d_out, )
def forward(self, x: Tensor) -> Tensor: x = x.float() x = self.first_layer(x) x = self.blocks(x) x = self.head(x) return x#### For diffusion
class MLPDiffusion(nn.Module): def __init__(self, d_in, num_classes, is_y_cond, rtdl_params, dim_t = 128): super().__init__() self.dim_t = dim_t self.num_classes = num_classes self.is_y_cond = is_y_cond
# d0 = rtdl_params['d_layers'][0]
rtdl_params['d_in'] = dim_t rtdl_params['d_out'] = d_in
self.mlp = MLP.make_baseline(**rtdl_params)
if self.num_classes > 0 and is_y_cond: self.label_emb = nn.Embedding(self.num_classes, dim_t) elif self.num_classes == 0 and is_y_cond: self.label_emb = nn.Linear(1, dim_t) self.proj = nn.Linear(d_in, dim_t) self.time_embed = nn.Sequential( nn.Linear(dim_t, dim_t), nn.SiLU(), nn.Linear(dim_t, dim_t) ) def forward(self, x, timesteps, y=None): emb = self.time_embed(timestep_embedding(timesteps, self.dim_t)) if self.is_y_cond and y is not None: if self.num_classes > 0: y = y.squeeze() else: y = y.resize(y.size(0), 1).float() emb += F.silu(self.label_emb(y)) x = self.proj(x) + emb return self.mlp(x)
class ResNetDiffusion(nn.Module): def __init__(self, d_in, num_classes, rtdl_params, dim_t = 256): super().__init__() self.dim_t = dim_t self.num_classes = num_classes
rtdl_params['d_in'] = d_in rtdl_params['d_out'] = d_in rtdl_params['emb_d'] = dim_t self.resnet = ResNet.make_baseline(**rtdl_params)
if self.num_classes > 0: self.label_emb = nn.Embedding(self.num_classes, dim_t) self.time_embed = nn.Sequential( nn.Linear(dim_t, dim_t), nn.SiLU(), nn.Linear(dim_t, dim_t) ) def forward(self, x, timesteps, y=None): emb = self.time_embed(timestep_embedding(timesteps, self.dim_t)) if y is not None and self.num_classes > 0: emb += self.label_emb(y.squeeze()) return self.resnet(x, emb)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174import torchimport numpy as npimport torch.nn.functional as Ffrom torch.profiler import record_functionfrom inspect import isfunction
def normal_kl(mean1, logvar1, mean2, logvar2): """ Compute the KL divergence between two gaussians.
Shapes are automatically broadcasted, so batches can be compared to scalars, among other use cases. """ tensor = None for obj in (mean1, logvar1, mean2, logvar2): if isinstance(obj, torch.Tensor): tensor = obj break assert tensor is not None, "at least one argument must be a Tensor"
# Force variances to be Tensors. Broadcasting helps convert scalars to # Tensors, but it does not work for torch.exp(). logvar1, logvar2 = [ x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor) for x in (logvar1, logvar2) ]
return 0.5 * ( -1.0 + logvar2 - logvar1 + torch.exp(logvar1 - logvar2) + ((mean1 - mean2) ** 2) * torch.exp(-logvar2) )
def approx_standard_normal_cdf(x): """ A fast approximation of the cumulative distribution function of the standard normal. """ return 0.5 * (1.0 + torch.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * torch.pow(x, 3))))
def discretized_gaussian_log_likelihood(x, *, means, log_scales): """ Compute the log-likelihood of a Gaussian distribution discretizing to a given image.
:param x: the target images. It is assumed that this was uint8 values, rescaled to the range [-1, 1]. :param means: the Gaussian mean Tensor. :param log_scales: the Gaussian log stddev Tensor. :return: a tensor like x of log probabilities (in nats). """ assert x.shape == means.shape == log_scales.shape centered_x = x - means inv_stdv = torch.exp(-log_scales) plus_in = inv_stdv * (centered_x + 1.0 / 255.0) cdf_plus = approx_standard_normal_cdf(plus_in) min_in = inv_stdv * (centered_x - 1.0 / 255.0) cdf_min = approx_standard_normal_cdf(min_in) log_cdf_plus = torch.log(cdf_plus.clamp(min=1e-12)) log_one_minus_cdf_min = torch.log((1.0 - cdf_min).clamp(min=1e-12)) cdf_delta = cdf_plus - cdf_min log_probs = torch.where( x < -0.999, log_cdf_plus, torch.where(x > 0.999, log_one_minus_cdf_min, torch.log(cdf_delta.clamp(min=1e-12))), ) assert log_probs.shape == x.shape return log_probs
def sum_except_batch(x, num_dims=1): ''' Sums all dimensions except the first.
Args: x: Tensor, shape (batch_size, ...) num_dims: int, number of batch dims (default=1)
Returns: x_sum: Tensor, shape (batch_size,) ''' return x.reshape(*x.shape[:num_dims], -1).sum(-1)
def mean_flat(tensor): """ Take the mean over all non-batch dimensions. """ return tensor.mean(dim=list(range(1, len(tensor.shape))))
def ohe_to_categories(ohe, K): K = torch.from_numpy(K) indices = torch.cat([torch.zeros((1,)), K.cumsum(dim=0)], dim=0).int().tolist() res = [] for i in range(len(indices) - 1): res.append(ohe[:, indices[i]:indices[i+1]].argmax(dim=1)) return torch.stack(res, dim=1)
def log_1_min_a(a): return torch.log(1 - a.exp() + 1e-40)
def log_add_exp(a, b): maximum = torch.max(a, b) return maximum + torch.log(torch.exp(a - maximum) + torch.exp(b - maximum))
def exists(x): return x is not None
def extract(a, t, x_shape): b, *_ = t.shape t = t.to(a.device) out = a.gather(-1, t) while len(out.shape) < len(x_shape): out = out[..., None] return out.expand(x_shape)
def default(val, d): if exists(val): return val return d() if isfunction(d) else d
def log_categorical(log_x_start, log_prob): return (log_x_start.exp() * log_prob).sum(dim=1)
def index_to_log_onehot(x, num_classes): onehots = [] for i in range(len(num_classes)): onehots.append(F.one_hot(x[:, i], num_classes[i])) x_onehot = torch.cat(onehots, dim=1) log_onehot = torch.log(x_onehot.float().clamp(min=1e-30)) return log_onehot
def log_sum_exp_by_classes(x, slices): device = x.device res = torch.zeros_like(x) for ixs in slices: res[:, ixs] = torch.logsumexp(x[:, ixs], dim=1, keepdim=True)
assert x.size() == res.size()
return res
@torch.jit.scriptdef log_sub_exp(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: m = torch.maximum(a, b) return torch.log(torch.exp(a - m) - torch.exp(b - m)) + m
@torch.jit.scriptdef sliced_logsumexp(x, slices): lse = torch.logcumsumexp( torch.nn.functional.pad(x, [1, 0, 0, 0], value=-float('inf')), dim=-1)
slice_starts = slices[:-1] slice_ends = slices[1:]
slice_lse = log_sub_exp(lse[:, slice_ends], lse[:, slice_starts]) slice_lse_repeated = torch.repeat_interleave( slice_lse, slice_ends - slice_starts, dim=-1 ) return slice_lse_repeated
def log_onehot_to_index(log_x): return log_x.argmax(1)
class FoundNANsError(BaseException): """Found NANs during sampling""" def __init__(self, message='Found NANs during sampling.'): super(FoundNANsError, self).__init__(message)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475import os, sys, subprocess, jsonimport numpy as npimport pandas as pd
tabddpm_root = "/workspace/tabddpm/code"runtime_root = "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime"assert os.path.isdir(tabddpm_root), f"TabDDPM source not mounted: {tabddpm_root}"
if not os.path.exists(runtime_root): def _ignore(_, names): skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"} return [n for n in names if n in skip or n.endswith(".pyc")] import shutil shutil.copytree(tabddpm_root, runtime_root, ignore=_ignore)
env = os.environ.copy()env["PYTHONPATH"] = runtime_root + (os.pathsep + env.get("PYTHONPATH", ""))
# Reuse the compat wrapper (patches collections.Sequence for skorch)wrapper = os.path.join(runtime_root, "_compat_run.py")if not os.path.exists(wrapper): with open(wrapper, "w") as f: f.write( "import collections, collections.abc\n" "for _a in ('Sequence','MutableSequence','MutableMapping','Mapping'," "'MutableSet','Set','Callable','Iterable','Iterator'):\n" " if not hasattr(collections, _a): setattr(collections, _a, getattr(collections.abc, _a, None))\n" "import sys, runpy\n" "sys.argv = sys.argv[1:]\n" "runpy.run_path(sys.argv[0], run_name='__main__')\n" )
print(f"[TabDDPM] Sampling 7636 rows")ret = subprocess.run( [sys.executable, wrapper, "scripts/pipeline.py", "--config", "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/config_sample_20260510_222509_r0.toml", "--sample"], cwd=runtime_root, env=env)if ret.returncode != 0: sys.exit(ret.returncode)
# 将 .npy 输出转为 CSV(npy 在 TabDDPM 的 parent_dir,即 npy_dir)info_path = "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/data/info.json"with open(info_path) as f: info = json.load(f)
output_dir = "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/output"col_names = info.get("column_names", [])
parts = []x_num_path = os.path.join(output_dir, "X_num_train.npy")x_cat_path = os.path.join(output_dir, "X_cat_train.npy")y_path = os.path.join(output_dir, "y_train.npy")
if os.path.exists(x_num_path): parts.append(np.load(x_num_path, allow_pickle=True))if os.path.exists(x_cat_path): parts.append(np.load(x_cat_path, allow_pickle=True).astype(float))if os.path.exists(y_path): y = np.load(y_path, allow_pickle=True) parts.append(y.reshape(-1, 1) if y.ndim == 1 else y)
if parts: combined = np.concatenate(parts, axis=1) if col_names and len(col_names) == combined.shape[1]: df = pd.DataFrame(combined, columns=col_names) else: df = pd.DataFrame(combined) df.to_csv("/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/tabddpm-c6-7636-20260510_222509.csv", index=False) print(f"[TabDDPM] Saved {len(df)} rows -> /work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/tabddpm-c6-7636-20260510_222509.csv")else: print("[TabDDPM] WARNING: No output .npy files found") sys.exit(1)123456789101112131415161718192021222324252627282930313233343536373839404142import os, sys, subprocess
tabddpm_root = "/workspace/tabddpm/code"runtime_root = "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime"assert os.path.isdir(tabddpm_root), f"TabDDPM source not mounted: {tabddpm_root}"
def _ignore(_, names): skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"} return [n for n in names if n in skip or n.endswith(".pyc")]
import shutilshutil.rmtree(runtime_root, ignore_errors=True)shutil.copytree(tabddpm_root, runtime_root, ignore=_ignore)
env = os.environ.copy()env["PYTHONPATH"] = runtime_root + (os.pathsep + env.get("PYTHONPATH", ""))
# Write a wrapper that patches collections.Sequence (removed in Python 3.10+)# before running pipeline.py - needed because skorch uses old APIwrapper = os.path.join(runtime_root, "_compat_run.py")with open(wrapper, "w") as f: f.write( "import collections, collections.abc\n" "for _a in ('Sequence','MutableSequence','MutableMapping','Mapping'," "'MutableSet','Set','Callable','Iterable','Iterator'):\n" " if not hasattr(collections, _a): setattr(collections, _a, getattr(collections.abc, _a, None))\n" "import sys, runpy\n" "sys.argv = sys.argv[1:]\n" "runpy.run_path(sys.argv[0], run_name='__main__')\n" )
print(f"[TabDDPM] Training, config=/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/config.toml")ret = subprocess.run( [sys.executable, wrapper, "scripts/pipeline.py", "--config", "/work/output-Benchmark-trainonly-v1/c6/tabddpm/tabddpm-c6-20260510_222430/config.toml", "--train"], cwd=runtime_root, env=env)if ret.returncode != 0: sys.exit(ret.returncode)print("[TabDDPM] Training complete")syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/._dataAdded
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/.gitignoreAdded+22
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/.gitmodulesAdded+9
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CONFIG_DESCRIPTION.mdAdded+78
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/.gitignoreAdded+1
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/README.mdAdded+49
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.pyAdded+81
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.pyAdded+110
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.pyAdded+153
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/.gitignoreAdded+1
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/LICENSEAdded+201
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/License.txtAdded+15
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/README.mdAdded+50
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/pipeline_ctabgan.pyAdded+80
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/requirements.txtAdded+6
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/train_sample_ctabgan.pyAdded+108
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/tune_ctabgan.pyAdded+150
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/pipeline_tvae.pyAdded+80
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/train_sample_tvae.pyAdded+117
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/tune_tvae.pyAdded+153
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/LICENSE.mdAdded+21
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/README.mdAdded+99
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/_compat_run.pyAdded+6
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/agg_results.ipynbAdded+315
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__init__.pyAdded+12
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/data.pyAdded+719
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/deep.pyAdded+168
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/env.pyAdded+39
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/metrics.pyAdded+158
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/util.pyAdded+433
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/requirements.txtAdded+22
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm.shAdded+5
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/run_tabddpm_docker.shAdded+5
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/__init__.pyAdded
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_catboost.pyAdded+145
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_mlp.pyAdded+176
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds.pyAdded+121
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_seeds_simple.pyAdded+130
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/eval_simple.pyAdded+141
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/pipeline.pyAdded+112
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/resample_privacy.pyAdded+257
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/sample.pyAdded+160
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/train.pyAdded+158
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_evaluation_model.pyAdded+145
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/__init__.pyAdded+2
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/gaussian_multinomial_diffsuion.pyAdded+993
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/modules.pyAdded+486
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tab_ddpm/utils.pyAdded+174
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_sample_r0.pyAdded+75
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_train.pyAdded+42