TabQueryBench commited on
Commit
490d23c
·
verified ·
1 Parent(s): 5f6fc33

Resume SynthData0523 main/c19 batch 6

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +27 -0
  2. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/y_train.npy +3 -0
  3. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/y_val.npy +3 -0
  4. SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/train_20260510_210216.log +3 -0
  5. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_gen.py +42 -0
  6. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/.gitignore +15 -0
  7. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/LICENSE +7 -0
  8. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/README.md +201 -0
  9. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_cat_test.npy +3 -0
  10. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_cat_train.npy +3 -0
  11. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_cat_val.npy +3 -0
  12. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_num_test.npy +3 -0
  13. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_num_train.npy +3 -0
  14. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_num_val.npy +3 -0
  15. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/info.json +3 -0
  16. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/real.csv +3 -0
  17. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/staged_features.json +3 -0
  18. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/test.csv +3 -0
  19. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/train.csv +3 -0
  20. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/val.csv +3 -0
  21. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/y_test.npy +3 -0
  22. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/y_train.npy +3 -0
  23. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/y_val.npy +3 -0
  24. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/download_dataset.py +51 -0
  25. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/eval_quality.py +151 -0
  26. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/mle/mle.py +781 -0
  27. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/mle/tabular_dataload.py +111 -0
  28. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/mle/tabular_transformer.py +110 -0
  29. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/visualize_density.py +85 -0
  30. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval_impute.py +82 -0
  31. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/images/tabdiff_demo.gif +3 -0
  32. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/images/tabdiff_demo.mp4 +3 -0
  33. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/images/tabdiff_flowchart.jpg +3 -0
  34. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/main.py +46 -0
  35. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/process_dataset.py +646 -0
  36. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/__init__.py +11 -0
  37. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/data.py +780 -0
  38. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/env.py +39 -0
  39. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/metrics.py +157 -0
  40. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/util.py +347 -0
  41. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthcity.yaml +11 -0
  42. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthetic/pipeline_c19/real.csv +3 -0
  43. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthetic/pipeline_c19/test.csv +3 -0
  44. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthetic/pipeline_c19/val.csv +3 -0
  45. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff.yaml +35 -0
  46. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/config.pkl +3 -0
  47. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/ema_model_200.pt +3 -0
  48. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/model_200.pt +3 -0
  49. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml +3 -0
  50. SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/main.py +331 -0
.gitattributes CHANGED
@@ -2852,3 +2852,30 @@ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pi
2852
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/train.csv filter=lfs diff=lfs merge=lfs -text
2853
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/val.csv filter=lfs diff=lfs merge=lfs -text
2854
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/y_test.npy filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2852
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/train.csv filter=lfs diff=lfs merge=lfs -text
2853
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/val.csv filter=lfs diff=lfs merge=lfs -text
2854
  SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/y_test.npy filter=lfs diff=lfs merge=lfs -text
2855
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/y_train.npy filter=lfs diff=lfs merge=lfs -text
2856
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/y_val.npy filter=lfs diff=lfs merge=lfs -text
2857
+ SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/train_20260510_210216.log filter=lfs diff=lfs merge=lfs -text
2858
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_cat_test.npy filter=lfs diff=lfs merge=lfs -text
2859
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_cat_train.npy filter=lfs diff=lfs merge=lfs -text
2860
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_cat_val.npy filter=lfs diff=lfs merge=lfs -text
2861
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_num_test.npy filter=lfs diff=lfs merge=lfs -text
2862
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_num_train.npy filter=lfs diff=lfs merge=lfs -text
2863
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_num_val.npy filter=lfs diff=lfs merge=lfs -text
2864
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/info.json filter=lfs diff=lfs merge=lfs -text
2865
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/real.csv filter=lfs diff=lfs merge=lfs -text
2866
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/staged_features.json filter=lfs diff=lfs merge=lfs -text
2867
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/test.csv filter=lfs diff=lfs merge=lfs -text
2868
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/train.csv filter=lfs diff=lfs merge=lfs -text
2869
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/val.csv filter=lfs diff=lfs merge=lfs -text
2870
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/y_test.npy filter=lfs diff=lfs merge=lfs -text
2871
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/y_train.npy filter=lfs diff=lfs merge=lfs -text
2872
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/y_val.npy filter=lfs diff=lfs merge=lfs -text
2873
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/images/tabdiff_demo.gif filter=lfs diff=lfs merge=lfs -text
2874
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/images/tabdiff_demo.mp4 filter=lfs diff=lfs merge=lfs -text
2875
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthetic/pipeline_c19/real.csv filter=lfs diff=lfs merge=lfs -text
2876
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthetic/pipeline_c19/test.csv filter=lfs diff=lfs merge=lfs -text
2877
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthetic/pipeline_c19/val.csv filter=lfs diff=lfs merge=lfs -text
2878
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/config.pkl filter=lfs diff=lfs merge=lfs -text
2879
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/ema_model_200.pt filter=lfs diff=lfs merge=lfs -text
2880
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/model_200.pt filter=lfs diff=lfs merge=lfs -text
2881
+ SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml filter=lfs diff=lfs merge=lfs -text
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:977de15b5bd4785ce2c1370504303a66f974c6dd474345dc88784832776cf98f
3
+ size 262200
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/tabular_bundle/pipeline_c19/y_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a9ff40f59b5afc2a1752a1d42a673b1c24c422c859c9e3c35d6110919dfb7f7
3
+ size 32880
SynthData0523/main/c19/tabbyflow/tabbyflow-c19-20260510_210211/train_20260510_210216.log ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92927c626bcac734e7a1e18a1ebeebc825ea92b048b0036eaaa7a097f0897286
3
+ size 270435
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_gen.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os, shutil, subprocess, sys
3
+ td = r"/workspace/TabDiff"
4
+ name = r"pipeline_c19"
5
+ src = r"/work/output-Benchmark-trainonly-v1/c19/tabdiff/tabdiff-c19-20260512_231303/tabular_bundle/pipeline_c19"
6
+ rt = r"/work/output-Benchmark-trainonly-v1/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime"
7
+ if not os.path.exists(rt):
8
+ def _ignore(_, names):
9
+ skip = {"__pycache__", "data", "synthetic", "result", "results", "ckpt"}
10
+ return [n for n in names if n in skip or n.endswith(".pyc")]
11
+ shutil.copytree(td, rt, ignore=_ignore)
12
+ dst_data = os.path.join(rt, "data", name)
13
+ dst_syn = os.path.join(rt, "synthetic", name)
14
+ shutil.rmtree(dst_data, ignore_errors=True)
15
+ os.makedirs(os.path.dirname(dst_data), exist_ok=True)
16
+ shutil.copytree(src, dst_data)
17
+ os.makedirs(dst_syn, exist_ok=True)
18
+ for fn in ("real.csv", "test.csv", "val.csv"):
19
+ shutil.copy(os.path.join(src, fn), os.path.join(dst_syn, fn))
20
+ os.chdir(rt)
21
+ os.environ["PYTHONPATH"] = rt + os.pathsep + os.environ.get("PYTHONPATH", "")
22
+ subprocess.check_call([
23
+ sys.executable, "-m", "tabdiff.main",
24
+ "--dataname", name, "--mode", "test", "--gpu", "0",
25
+ "--no_wandb", "--exp_name", r"adapter_learnable",
26
+ "--ckpt_path", r"/work/output-Benchmark-trainonly-v1/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/model_200.pt",
27
+ "--num_samples_to_generate", str(int(32759)),
28
+ ])
29
+ # test() 写入 tabdiff/result/<dataname>/<exp>/<epoch>/samples.csv
30
+ base = os.path.join(rt, "tabdiff", "result", name, r"adapter_learnable")
31
+ best = None
32
+ best_t = -1.0
33
+ for root, _, files in os.walk(base):
34
+ if "samples.csv" in files:
35
+ p = os.path.join(root, "samples.csv")
36
+ t = os.path.getmtime(p)
37
+ if t > best_t:
38
+ best_t = t
39
+ best = p
40
+ if not best:
41
+ raise SystemExit("tabdiff: no samples.csv under " + base)
42
+ shutil.copy(best, r"/work/output-Benchmark-trainonly-v1/c19/tabdiff/tabdiff-c19-20260512_231303/tabdiff-c19-32759-20260512_235639.csv")
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/.gitignore ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ **/__pycache__/**
2
+ *.pyc
3
+
4
+ data/*
5
+ !/data/Info/
6
+
7
+ wandb/
8
+ eval/
9
+ synthetic/
10
+ impute/
11
+ workspace/
12
+ debug/
13
+ tabdiff/result/
14
+
15
+ **/ckpt/*
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/LICENSE ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Copyright 2024 Minkai Xu
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 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 THE SOFTWARE.
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/README.md ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TabDiff: a Mixed-type Diffusion Model for Tabular Data Generation
2
+
3
+ <p align="center">
4
+ <a href="https://github.com/MinkaiXu/TabDiff/blob/main/LICENSE">
5
+ <img alt="MIT License" src="https://img.shields.io/badge/License-MIT-yellow.svg">
6
+ </a>
7
+ <a href="https://openreview.net/forum?id=swvURjrt8z">
8
+ <img alt="Openreview" src="https://img.shields.io/badge/review-OpenReview-blue">
9
+ </a>
10
+ <a href="https://arxiv.org/abs/2410.20626">
11
+ <img alt="Paper URL" src="https://img.shields.io/badge/cs.LG-2410.20626-B31B1B.svg">
12
+ </a>
13
+ </p>
14
+
15
+ <div align="center">
16
+ <img src="images/tabdiff_demo.gif" alt="Model Logo" width="800" style="margin-left:'auto' margin-right:'auto' display:'block'"/>
17
+ <p><em>Figure 1: Visualing the generative process of TabDiff. A high-quality version of this video can be found at <a href="images/tabdiff_demo.mp4" download>tabdiff_demo.mp4</a></em></p>
18
+ </div>
19
+
20
+ This repository provides the official implementation of TabDiff: a Mixed-type Diffusion Model for Tabular Data Generation (ICLR 2025).
21
+
22
+ ## Latest Update
23
+ - [2025.04]:The categorical-heavy dataset **[Diabetes](https://archive.ics.uci.edu/dataset/296/diabetes+130-us+hospitals+for+years+1999-2008)** evaluated in the paper has now been released!
24
+ - [2025.02]:Our code is finally released! We have released part of the tested datasets. The rest will be released soon!
25
+
26
+ ## Introduction
27
+
28
+ <div align="center">
29
+ <img src="images/tabdiff_flowchart.jpg" alt="Model Logo" width="800" style="margin-left:'auto' margin-right:'auto' display:'block'"/>
30
+ <p><em>Figure 2: The high-level schema of TabDiff</a></em></p>
31
+ </div>
32
+ TabDiff is a unified diffusion framework designed to model all muti-modal distributions of tabular data in a single model. Its key innovations include:
33
+
34
+ 1) Framing the joint diffusion process in continuous time,
35
+ 2) A feature-wised learnable diffusion process that offsets the heterogeneity across different feature distributions,
36
+ 3) Classifier-free guidance conditional generation for missing column value imputation.
37
+
38
+ The schema of TabDiff is presented in the figure above. For more details, please refer to [our paper](https://arxiv.org/abs/2410.20626).
39
+
40
+
41
+ ## Environment Setup
42
+
43
+ Create the main environment with [tabdiff.yaml](tabdiff.yaml). This environment will be used for all tasks except for the evaluation of additional data fidelity metrics (i.e., $\alpha$-precision and $\beta$-recall scores)
44
+
45
+ ```
46
+ conda env create -f tabdiff.yaml
47
+ ```
48
+
49
+ Create another environment with [synthcity.yaml](synthcity.yaml) to evaluate additional data fidelity metrics
50
+
51
+ ```
52
+ conda env create -f synthcity.yaml
53
+ ```
54
+
55
+ ## Datasets Preparation
56
+
57
+ ### Using the datasets experimented in the paper
58
+
59
+ Download raw datasets:
60
+
61
+ ```
62
+ python download_dataset.py
63
+ ```
64
+
65
+ Process datasets:
66
+
67
+ ```
68
+ python process_dataset.py
69
+ ```
70
+
71
+ ### Using your own dataset
72
+
73
+ First, create a directory for your dataset in [./data](./data):
74
+ ```
75
+ cd data
76
+ mkdir <NAME_OF_YOUR_DATASET>
77
+ ```
78
+
79
+ Compile your raw tabular data in .csv format. **The first row should be the header** indicating the name of each column, and the remaining rows are records. After finishing these steps, place you data's csv file in the directory you just created and name it as <NAME_OF_YOUR_DATASET>.csv.
80
+
81
+ Then, create <NAME_OF_YOUR_DATASET>.json in [./data/Info](./data/Info). Write this file with the metadata of your dataset, covering the following information:
82
+ ```
83
+ {
84
+ "name": "<NAME_OF_YOUR_DATASET>",
85
+ "task_type": "[NAME_OF_TASK]", # binclass or regression
86
+ "header": "infer",
87
+ "column_names": null,
88
+ "num_col_idx": [LIST], # list of indices of numerical columns
89
+ "cat_col_idx": [LIST], # list of indices of categorical columns
90
+ "target_col_idx": [list], # list of indices of the target columns (for MLE)
91
+ "file_type": "csv",
92
+ "data_path": "data/<NAME_OF_YOUR_DATASET>/<NAME_OF_YOUR_DATASET>.csv"
93
+ "test_path": null,
94
+ }
95
+ ```
96
+
97
+ ### Important Notes When Creating the Info File
98
+ - The MLE evaluation and the imputation task (see later sections for details) assume that one column of your data is the regression or classification target. To enable these tasks, you will need to specify `target_col_idx`. If you don't need to evalute MLE, you can comment out the following line: https://github.com/MinkaiXu/TabDiff/blob/0c4fc3bbfa19046d36c5dce64628df52d5c73d15/tabdiff/main.py#L152
99
+ - The fields `target_col_idx`, `num_col_idx` and `cat_col_idx` must be multually exclusive—no column should appear in more than one of these lists.
100
+ - Set the task_type to "regression" if the target column is numerical, or "binclass" if it is categorical.
101
+
102
+ Finally, run the following command to process your dataset:
103
+ ```
104
+ python process_dataset.py --dataname <NAME_OF_YOUR_DATASET>
105
+ ```
106
+
107
+ ## Training TabDiff
108
+
109
+ To train an unconditional TabDiff model across the entire table, run
110
+
111
+ ```
112
+ python main.py --dataname <NAME_OF_DATASET> --mode train
113
+ ```
114
+
115
+ Current Options of ```<NAME_OF_DATASET>``` are: adult, default, shoppers, magic, beijing, news
116
+
117
+ Wanb logging is enabled by default. To disable it and log locally, add the ```--no_wandb``` flag.
118
+
119
+ To disable the learnable noise schedules, add the ```--non_learnable_schedule```. Please note that in order for the code to test/sample from such model properly, you need to add this flag for all commands below.
120
+
121
+ To specify your own experiment name, which will be used for logging and saving files, add ```--exp_name <your experiment name>```. This flag overwrites the default experiment name (learnable_schedule/non_learnable_schedule), so, similar to ```--non_learnable_schedule```, once added to training, you need to add it to all following commands as well.
122
+
123
+ ## Sampling and Evaluating TabDiff (Density, MLE, C2ST)
124
+
125
+ To sample synthetic tables from trained TabDiff models and evaluate them, run
126
+ ```
127
+ python main.py --dataname <NAME_OF_DATASET> --mode test --report --no_wandb
128
+ ```
129
+
130
+ This will sample 20 synthetic tables randomly. Meanwhile, it will evaluate the density, mle, and c2st scores for each sample and report their average and standard deviation. The results will be printed out in the terminal, and the samples and detailed evaluation results will be placed in ./eval/report_runs/<EXP_NAME>/<NAME_OF_DATASET>/.
131
+
132
+ ## Evaluating on Additional Fidelity Metrics ($\alpha$-precision and $\beta$-recall scores)
133
+ To evaluate TabDiff on the additional fidelity metrics ($\alpha$-precision and $\beta$-recall scores), you need to first make sure that you have already generated some samples by the previous commands. Then, you need to switch to the `synthcity` environment (as the synthcity packet used to compute those metrics conflicts with the main environment), by running
134
+ ```
135
+ conda activate synthcity
136
+ ```
137
+ Then, evaluate the metrics by running
138
+ ```
139
+ python eval/eval_quality.py --dataname <NAME_OF_DATASET>
140
+ ```
141
+
142
+ Similarly, the results will be printed out in the terminal and added to ./eval/report_runs/<EXP_NAME>/<NAME_OF_DATASET>/
143
+
144
+ ## Evaluating Data Privacy (DCR score)
145
+ To evalute the privacy metric DCR score, you first need to retrain all the models, as the metric requires an equal split between the training and testing data (our initial splits employ a 90/10 ratio). To retrain with an equal split, run the training command but append `_dcr` to ```<NAME_OF_DATASET>```
146
+ ```
147
+ python main.py --dataname <NAME_OF_DATASET>_dcr --mode train
148
+ ```
149
+
150
+ Then, test the models on DCR with the same `_dcr` suffix
151
+ ```
152
+ python main.py --dataname <NAME_OF_DATASET>_dcr --mode test --report --no_wandb
153
+ ```
154
+
155
+
156
+
157
+ ## Missing Value Imputation with Classifier-free Guidance (CFG)
158
+ Our current experiments only include imputing the target column. However, our implementation, located at ```sample_impute()``` in [unified_ctime_diffusion.py](./tabdiff/models/unified_ctime_diffusion.py), should support imputing multiple columns with different data types.
159
+
160
+ ### Training Guidance Model
161
+ In order to enable classifier-free guidance (CFG), you need to first train an unconditional guidance model on the target column by running the training command with the `--y_only` flag
162
+ ```
163
+ python main.py --dataname <NAME_OF_DATASET> --mode train --y_only
164
+ ```
165
+
166
+ ### Sampling Imputed Tables
167
+ With the trained guidance model, you can then impute the missing target column by running the testing command with the `--impute` flag
168
+ ```
169
+ python main.py --dataname <NAME_OF_DATASET> --mode test --impute --no_wandb
170
+ ```
171
+ This will, by default, randomly produce 50 imputed tables and save them to ./impute/<NAME_OF_DATASET>/<EXP_NAME>.
172
+
173
+ ### Evaluating Imputation
174
+ You can then evaluate the imputation quality by running
175
+ ```
176
+ python eval_impute.py --dataname <NAME_OF_DATASET>
177
+ ```
178
+
179
+ ## License
180
+
181
+ This work is licensed undeer the MIT License.
182
+
183
+ ## Acknowledgement
184
+ This repo is built upon the previous work TabSyn's [[codebase]](https://github.com/amazon-science/tabsyn). Many thanks to Hengrui!
185
+
186
+ ## Citation
187
+ Please consider citing our work if you find it helpful in your research!
188
+ ```
189
+ @inproceedings{
190
+ shi2025tabdiff,
191
+ title={TabDiff: a Mixed-type Diffusion Model for Tabular Data Generation},
192
+ author={Juntong Shi and Minkai Xu and Harper Hua and Hengrui Zhang and Stefano Ermon and Jure Leskovec},
193
+ booktitle={The Thirteenth International Conference on Learning Representations},
194
+ year={2025},
195
+ url={https://openreview.net/forum?id=swvURjrt8z}
196
+ }
197
+ ```
198
+ ## Contact
199
+ If you encounter any problem, please file an issue on this GitHub repo.
200
+
201
+ If you have any question regarding the paper, please contact Minkai at [minkai@stanford.edu](minkai@stanford.edu) or Juntong at [shisteve@usc.edu](shisteve@usc.edu).
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_cat_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7e8e273d7cebc9c535de23aac186a248e19f1b9270192e8516df2b3ff4d03b37
3
+ size 360576
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_cat_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:34a72bf9b360ceafc923a841725257c58f68702db5988848164e6a73030811ca
3
+ size 2882920
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_cat_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d7520984bdd5518919a6429f53fe78669a4c04ec06e58bb0b5388e56628d3080
3
+ size 360400
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_num_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:30bb71265025b7923a442d2e4818d163e76ace6a48bd5be6e29de20770bc8e15
3
+ size 65664
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_num_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:42ba0171576b4338cee3594e553bc298640933ba7a7c8a127ec106b642ee63e6
3
+ size 524272
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/X_num_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:adb8a29c75d7bdc3c8f7e797e555998c90f3b3154ccaeee3dc93d8cbe6c3c2d1
3
+ size 65632
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/info.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:26b65c13dd436fb96a31e3ea486b261897b74f9a192fe79828dc57be59be2f35
3
+ size 2739
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc
3
+ size 51459027
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/staged_features.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a57a0c3c2a45c85e74d4496ad733ad7f30b2615f97be5155850895fee1727948
3
+ size 1564
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd9c98343a92c7b1afe63b402f07b9a55013adbfcc60ec1e17d5e026385eeec8
3
+ size 6304860
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc
3
+ size 51459027
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69c75639e81916d3b4f2a28db38d7e15c78e442748aa5bf9fed2eb3784912a70
3
+ size 6331589
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/y_test.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81ee7259842c7941a044da2da22e21e7cfc06ae84f376f61f795079639c0f830
3
+ size 32896
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:977de15b5bd4785ce2c1370504303a66f974c6dd474345dc88784832776cf98f
3
+ size 262200
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/data/pipeline_c19/y_val.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7a9ff40f59b5afc2a1752a1d42a673b1c24c422c859c9e3c35d6110919dfb7f7
3
+ size 32880
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/download_dataset.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from urllib import request
3
+ import zipfile
4
+
5
+ DATA_DIR = 'data'
6
+
7
+
8
+ NAME_URL_DICT_UCI = {
9
+ 'adult': 'https://archive.ics.uci.edu/static/public/2/adult.zip',
10
+ 'default': 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip',
11
+ 'magic': 'https://archive.ics.uci.edu/static/public/159/magic+gamma+telescope.zip',
12
+ 'shoppers': 'https://archive.ics.uci.edu/static/public/468/online+shoppers+purchasing+intention+dataset.zip',
13
+ 'beijing': 'https://archive.ics.uci.edu/static/public/381/beijing+pm2+5+data.zip',
14
+ 'news': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',
15
+ 'news_nocat': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',
16
+ 'diabetes': 'https://archive.ics.uci.edu/static/public/296/diabetes+130-us+hospitals+for+years+1999-2008.zip',
17
+ 'adult_dcr': 'https://archive.ics.uci.edu/static/public/2/adult.zip',
18
+ 'default_dcr': 'https://archive.ics.uci.edu/static/public/350/default+of+credit+card+clients.zip',
19
+ 'magic_dcr': 'https://archive.ics.uci.edu/static/public/159/magic+gamma+telescope.zip',
20
+ 'shoppers_dcr': 'https://archive.ics.uci.edu/static/public/468/online+shoppers+purchasing+intention+dataset.zip',
21
+ 'beijing_dcr': 'https://archive.ics.uci.edu/static/public/381/beijing+pm2+5+data.zip',
22
+ 'news_dcr': 'https://archive.ics.uci.edu/static/public/332/online+news+popularity.zip',
23
+ 'diabetes_dcr': 'https://archive.ics.uci.edu/static/public/296/diabetes+130-us+hospitals+for+years+1999-2008.zip',
24
+ }
25
+
26
+ def unzip_file(zip_filepath, dest_path):
27
+ with zipfile.ZipFile(zip_filepath, 'r') as zip_ref:
28
+ zip_ref.extractall(dest_path)
29
+
30
+
31
+ def download_from_uci(name):
32
+
33
+ print(f'Start processing dataset {name} from UCI.')
34
+ save_dir = f'{DATA_DIR}/{name}'
35
+ if not os.path.exists(save_dir):
36
+ os.makedirs(save_dir)
37
+
38
+ url = NAME_URL_DICT_UCI[name]
39
+ request.urlretrieve(url, f'{save_dir}/{name}.zip')
40
+ print(f'Finish downloading dataset from {url}, data has been saved to {save_dir}.')
41
+
42
+ unzip_file(f'{save_dir}/{name}.zip', save_dir)
43
+ print(f'Finish unzipping {name}.')
44
+
45
+ else:
46
+ print('Aready downloaded.')
47
+
48
+ if __name__ == '__main__':
49
+ for name in NAME_URL_DICT_UCI.keys():
50
+ download_from_uci(name)
51
+
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/eval_quality.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import numpy as np
3
+ import pandas as pd
4
+ import os
5
+ import sys
6
+ import json
7
+
8
+ sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9
+ from sklearn.preprocessing import OneHotEncoder
10
+ from synthcity.metrics import eval_statistical
11
+ from synthcity.plugins.core.dataloader import GenericDataLoader
12
+
13
+ pd.options.mode.chained_assignment = None
14
+
15
+ import argparse
16
+
17
+ parser = argparse.ArgumentParser()
18
+ parser.add_argument('--dataname', type=str)
19
+ parser.add_argument('--exp_name', type=str, default=None)
20
+ parser.add_argument('--non_learnable_schedule', action='store_true')
21
+
22
+
23
+ args = parser.parse_args()
24
+
25
+ def evaluate_quality(real_path, syn_path, info_path):
26
+ with open(info_path, 'r') as f:
27
+ info = json.load(f)
28
+
29
+ syn_data = pd.read_csv(syn_path)
30
+ real_data = pd.read_csv(real_path)
31
+
32
+
33
+ ''' Special treatment for default dataset and CoDi model '''
34
+
35
+ real_data.columns = range(len(real_data.columns))
36
+ syn_data.columns = range(len(syn_data.columns))
37
+
38
+ num_col_idx = info['num_col_idx']
39
+ cat_col_idx = info['cat_col_idx']
40
+ target_col_idx = info['target_col_idx']
41
+ if info['task_type'] == 'regression':
42
+ num_col_idx += target_col_idx
43
+ else:
44
+ cat_col_idx += target_col_idx
45
+
46
+ num_real_data = real_data[num_col_idx]
47
+ cat_real_data = real_data[cat_col_idx]
48
+
49
+ num_real_data_np = num_real_data.to_numpy()
50
+ cat_real_data_np = cat_real_data.to_numpy().astype('str')
51
+
52
+
53
+ num_syn_data = syn_data[num_col_idx]
54
+ cat_syn_data = syn_data[cat_col_idx]
55
+
56
+ num_syn_data_np = num_syn_data.to_numpy()
57
+
58
+ # cat_syn_data_np = np.array
59
+ cat_syn_data_np = cat_syn_data.to_numpy().astype('str')
60
+
61
+ encoder = OneHotEncoder()
62
+ encoder.fit(cat_real_data_np)
63
+
64
+
65
+ cat_real_data_oh = encoder.transform(cat_real_data_np).toarray()
66
+ cat_syn_data_oh = encoder.transform(cat_syn_data_np).toarray()
67
+
68
+ le_real_data = pd.DataFrame(np.concatenate((num_real_data_np, cat_real_data_oh), axis = 1)).astype(float)
69
+ le_real_num = pd.DataFrame(num_real_data_np).astype(float)
70
+ le_real_cat = pd.DataFrame(cat_real_data_oh).astype(float)
71
+
72
+
73
+ le_syn_data = pd.DataFrame(np.concatenate((num_syn_data_np, cat_syn_data_oh), axis = 1)).astype(float)
74
+ le_syn_num = pd.DataFrame(num_syn_data_np).astype(float)
75
+ le_syn_cat = pd.DataFrame(cat_syn_data_oh).astype(float)
76
+
77
+ # Check for nan
78
+ if le_syn_data.isnull().values.any():
79
+ nan_coordinate = np.isnan(le_syn_data.to_numpy()).nonzero()
80
+ nan_row = np.unique(nan_coordinate[0])
81
+ print(f"Synthetic data contains NaN at row {nan_row}: ")
82
+ print(le_syn_data.iloc[nan_row])
83
+ return None, None
84
+
85
+
86
+ np.set_printoptions(precision=4)
87
+
88
+ result = []
89
+
90
+ print('=========== All Features ===========')
91
+ print('Data shape: ', le_syn_data.shape)
92
+
93
+ X_syn_loader = GenericDataLoader(le_syn_data)
94
+ X_real_loader = GenericDataLoader(le_real_data)
95
+
96
+ quality_evaluator = eval_statistical.AlphaPrecision()
97
+ qual_res = quality_evaluator.evaluate(X_real_loader, X_syn_loader)
98
+ qual_res = {
99
+ k: v for (k, v) in qual_res.items() if "naive" in k
100
+ } # use the naive implementation of AlphaPrecision
101
+ qual_score = np.mean(list(qual_res.values()))
102
+
103
+ print('alpha precision: {:.6f}, beta recall: {:.6f}'.format(qual_res['delta_precision_alpha_naive'], qual_res['delta_coverage_beta_naive'] ))
104
+
105
+ Alpha_Precision_all = qual_res['delta_precision_alpha_naive']
106
+ Beta_Recall_all = qual_res['delta_coverage_beta_naive']
107
+
108
+ return Alpha_Precision_all, Beta_Recall_all
109
+
110
+ if __name__ == '__main__':
111
+ exp_name = args.exp_name
112
+ if exp_name is None:
113
+ exp_name = "non_learnable_schedule" if args.non_learnable_schedule else "learnable_schedule"
114
+ dataname = args.dataname
115
+ data_dir = f'data/{dataname}'
116
+ info_path = f'{data_dir}/info.json'
117
+ real_path = f'synthetic/{dataname}/real.csv'
118
+
119
+ sample_dir = f"eval/report_runs/{exp_name}/{dataname}/all_samples"
120
+ sample_paths = glob.glob(os.path.join(sample_dir, "*.csv"))
121
+ print(f"{len(sample_paths )} samples loaded from {sample_dir}")
122
+
123
+ alphas, betas = [], []
124
+ for syn_path in sample_paths:
125
+ alpha_precision, beta_recall = evaluate_quality(real_path, syn_path, info_path)
126
+ if (alpha_precision is None) or (beta_recall is None):
127
+ continue
128
+ alphas.append(alpha_precision)
129
+ betas.append(beta_recall)
130
+
131
+ alphas = np.array(alphas)
132
+ betas = np.array(betas)
133
+ alpha_percent = alphas * 100
134
+ beta_percent = betas * 100
135
+
136
+ quality = pd.DataFrame({
137
+ 'alpha': alpha_percent,
138
+ 'beta': beta_percent
139
+ })
140
+ avg = quality.mean(axis=0).round(2)
141
+ std = quality.std(axis=0).round(2)
142
+ quality_avg_std = pd.concat([avg, std], axis=1, ignore_index=True)
143
+ quality_avg_std.columns = ["avg", "std"]
144
+ quality_avg_std.index = ["alpha", "beta"]
145
+
146
+ save_dir = os.path.dirname(sample_dir)
147
+ quality.to_csv(os.path.join(save_dir, "quality.csv"), index=True)
148
+ avg_std = pd.read_csv(os.path.join(save_dir, "avg_std.csv"), index_col=0)
149
+ avg_std = pd.concat([avg_std, quality_avg_std])
150
+ print(avg_std)
151
+ avg_std.to_csv(os.path.join(save_dir, "avg_std.csv"), index=True)
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/mle/mle.py ADDED
@@ -0,0 +1,781 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from xgboost import XGBClassifier, XGBRegressor
4
+ from sklearn.ensemble import AdaBoostClassifier, RandomForestClassifier, RandomForestRegressor
5
+ from sklearn.linear_model import LogisticRegression, LinearRegression
6
+ from sklearn.neural_network import MLPClassifier, MLPRegressor
7
+ from sklearn.preprocessing import OneHotEncoder, LabelEncoder
8
+ from sklearn.tree import DecisionTreeClassifier
9
+ from sklearn.metrics import classification_report, accuracy_score, f1_score, precision_score, recall_score, roc_auc_score
10
+ from sklearn.metrics import explained_variance_score, mean_squared_error, mean_absolute_error, r2_score
11
+ from sklearn.model_selection import ParameterGrid
12
+ from sklearn.utils._testing import ignore_warnings
13
+ from sklearn.exceptions import ConvergenceWarning
14
+ import logging
15
+ from prdc import compute_prdc
16
+ from tqdm import tqdm
17
+
18
+ CATEGORICAL = "categorical"
19
+ CONTINUOUS = "continuous"
20
+
21
+ _MODELS = {
22
+ 'binclass': [ # 184
23
+ # {
24
+ # 'class': DecisionTreeClassifier, # 48
25
+ # 'kwargs': {
26
+ # 'max_depth': [4, 8, 16, 32],
27
+ # 'min_samples_split': [2, 4, 8],
28
+ # 'min_samples_leaf': [1, 2, 4, 8]
29
+ # }
30
+ # },
31
+ # {
32
+ # 'class': AdaBoostClassifier, # 4
33
+ # 'kwargs': {
34
+ # 'n_estimators': [10, 50, 100, 200]
35
+ # }
36
+ # },
37
+ # {
38
+ # 'class': LogisticRegression, # 36
39
+ # 'kwargs': {
40
+ # 'solver': ['lbfgs'],
41
+ # 'n_jobs': [-1],
42
+ # 'max_iter': [10, 50, 100, 200],
43
+ # 'C': [0.01, 0.1, 1.0],
44
+ # 'tol': [1e-01, 1e-02, 1e-04]
45
+ # }
46
+ # },
47
+ # {
48
+ # 'class': MLPClassifier, # 12
49
+ # 'kwargs': {
50
+ # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)],
51
+ # 'max_iter': [50, 100],
52
+ # 'alpha': [0.0001, 0.001]
53
+ # }
54
+ # },
55
+ # {
56
+ # 'class': RandomForestClassifier, # 48
57
+ # 'kwargs': {
58
+ # 'max_depth': [8, 16, None],
59
+ # 'min_samples_split': [2, 4, 8],
60
+ # 'min_samples_leaf': [1, 2, 4, 8],
61
+ # 'n_jobs': [-1]
62
+
63
+ # }
64
+ # },
65
+ {
66
+ 'class': XGBClassifier, # 36
67
+ 'kwargs': {
68
+ 'n_estimators': [10, 50, 100],
69
+ 'min_child_weight': [1, 10],
70
+ 'max_depth': [5, 10, 20],
71
+ 'gamma': [0.0, 1.0],
72
+ 'objective': ['binary:logistic'],
73
+ 'nthread': [-1],
74
+ 'tree_method': ['gpu_hist']
75
+ },
76
+ }
77
+
78
+ ],
79
+ 'multiclass': [ # 132
80
+
81
+ # {
82
+ # 'class': MLPClassifier, # 12
83
+ # 'kwargs': {
84
+ # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)],
85
+ # 'max_iter': [50, 100],
86
+ # 'alpha': [0.0001, 0.001]
87
+ # }
88
+ # },
89
+ # {
90
+ # 'class': DecisionTreeClassifier, # 48
91
+ # 'kwargs': {
92
+ # 'max_depth': [4, 8, 16, 32],
93
+ # 'min_samples_split': [2, 4, 8],
94
+ # 'min_samples_leaf': [1, 2, 4, 8]
95
+ # }
96
+ # },
97
+ # {
98
+ # 'class': RandomForestClassifier, # 36
99
+ # 'kwargs': {
100
+ # 'max_depth': [8, 16, None],
101
+ # 'min_samples_split': [2, 4, 8],
102
+ # 'min_samples_leaf': [1, 2, 4, 8],
103
+ # 'n_jobs': [-1]
104
+
105
+ # }
106
+ # },
107
+ {
108
+ 'class': XGBClassifier, # 36
109
+ 'kwargs': {
110
+ 'n_estimators': [10, 50, 100],
111
+ 'min_child_weight': [1, 10],
112
+ 'max_depth': [5, 10, 20],
113
+ 'gamma': [0.0, 1.0],
114
+ 'objective': ['binary:logistic'],
115
+ 'nthread': [-1],
116
+ 'tree_method': ['gpu_hist']
117
+ }
118
+ }
119
+
120
+ ],
121
+ 'regression': [ # 84
122
+ # {
123
+ # 'class': LinearRegression,
124
+ # },
125
+ # {
126
+ # 'class': MLPRegressor, # 12
127
+ # 'kwargs': {
128
+ # 'hidden_layer_sizes': [(100, ), (200, ), (100, 100)],
129
+ # 'max_iter': [50, 100],
130
+ # 'alpha': [0.0001, 0.001]
131
+ # }
132
+ #},
133
+ {
134
+ 'class': XGBRegressor, # 36
135
+ 'kwargs': {
136
+ 'n_estimators': [10, 50, 100],
137
+ 'min_child_weight': [1, 10],
138
+ 'max_depth': [5, 10, 20],
139
+ 'gamma': [0.0, 1.0],
140
+ 'objective': ['reg:linear'],
141
+ 'nthread': [-1],
142
+ 'tree_method': ['gpu_hist']
143
+ }
144
+ },
145
+ # {
146
+ # 'class': RandomForestRegressor, # 36
147
+ # 'kwargs': {
148
+ # 'max_depth': [8, 16, None],
149
+ # 'min_samples_split': [2, 4, 8],
150
+ # 'min_samples_leaf': [1, 2, 4, 8],
151
+ # 'n_jobs': [-1]
152
+ # }
153
+ # }
154
+ ]
155
+ }
156
+
157
+ def feat_transform(data, info, label_encoder = None, encoders = None, cmax = None, cmin = None):
158
+ num_col_idx = info['num_col_idx']
159
+ cat_col_idx = info['cat_col_idx']
160
+ target_col_idx = info['target_col_idx']
161
+
162
+ num_cols = len(num_col_idx + cat_col_idx + target_col_idx)
163
+ features = []
164
+
165
+ if not encoders:
166
+ encoders = dict()
167
+ for idx in range(num_cols):
168
+ col = data[:, idx]
169
+
170
+ if idx in target_col_idx:
171
+
172
+ if info['task_type'] != 'regression':
173
+
174
+ if not label_encoder:
175
+ label_encoder = LabelEncoder()
176
+ label_encoder.fit(col)
177
+
178
+ encoded_labels = label_encoder.transform(col)
179
+ labels = encoded_labels
180
+ else:
181
+ col = col.astype(np.float32)
182
+ labels = col.astype(np.float32)
183
+
184
+ continue
185
+
186
+ if idx in num_col_idx:
187
+ col = col.astype(np.float32)
188
+
189
+ if not cmin:
190
+ cmin = col.min()
191
+
192
+ if not cmax:
193
+ cmax = col.max()
194
+
195
+ if cmin >= 0 and cmax >= 1e3:
196
+ feature = np.log(np.maximum(col, 1e-2))
197
+
198
+ else:
199
+ feature = (col - cmin) / (cmax - cmin) * 5
200
+
201
+ elif idx in cat_col_idx:
202
+ encoder = encoders.get(idx)
203
+ col = col.reshape(-1, 1)
204
+ if encoder:
205
+ feature = encoder.transform(col)
206
+ else:
207
+ # encoder = OneHotEncoder(sparse=False, handle_unknown='ignore')
208
+ encoder = OneHotEncoder(sparse_output=False, handle_unknown='ignore') # New in version 1.2: sparse was renamed to sparse_output
209
+ encoders[idx] = encoder
210
+ feature = encoder.fit_transform(col)
211
+
212
+
213
+ features.append(feature)
214
+ features = np.column_stack(features)
215
+ return features, labels, label_encoder, encoders, cmax, cmin
216
+
217
+
218
+ def prepare_ml_problem(train, test, info, val=None):
219
+ # test_X, test_y, label_encoder, encoders = feat_transform(test, info)
220
+ # train_X, train_y, _, _ = feat_transform(train, info, label_encoder, encoders)
221
+
222
+ train_X, train_y, label_encoder, encoders, cmax, cmin = feat_transform(train, info)
223
+ test_X, test_y, _, _ , _, _ = feat_transform(test, info, label_encoder, encoders, cmax, cmin)
224
+
225
+ if val is not None:
226
+ val_X, val_y, _, _, _, _ = feat_transform(val, info, label_encoder, encoders, cmax, cmin)
227
+ else:
228
+ total_train_num = train_X.shape[0]
229
+ val_num = int(total_train_num / 9)
230
+
231
+ total_train_idx = np.arange(total_train_num)
232
+ np.random.shuffle(total_train_idx)
233
+ train_idx = total_train_idx[val_num:]
234
+ val_idx = total_train_idx[:val_num]
235
+
236
+
237
+
238
+ # val_X, val_y = train_X[val_idx], train_y[val_idx]
239
+ # train_X, train_y = train_X[train_idx], train_y[train_idx]
240
+
241
+ # model = _MODELS[info['task_type']]
242
+
243
+ # return train_X, train_y, train_X, train_y, test_X, test_y, model
244
+
245
+
246
+
247
+ val_X, val_y = train_X[val_idx], train_y[val_idx]
248
+ train_X, train_y = train_X[train_idx], train_y[train_idx]
249
+
250
+ model = _MODELS[info['task_type']]
251
+
252
+ return train_X, train_y, val_X, val_y, test_X, test_y, model
253
+
254
+ class FeatureMaker:
255
+
256
+ def __init__(self, metadata, label_column='label', label_type='int', sample=50000):
257
+ self.columns = metadata['columns']
258
+ self.label_column = label_column
259
+ self.label_type = label_type
260
+ self.sample = sample
261
+ self.encoders = dict()
262
+
263
+ def make_features(self, data):
264
+ data = data.copy()
265
+ np.random.shuffle(data)
266
+ data = data[:self.sample]
267
+
268
+ features = []
269
+ labels = []
270
+
271
+ for index, cinfo in enumerate(self.columns):
272
+ col = data[:, index]
273
+ if cinfo['name'] == self.label_column:
274
+ if self.label_type == 'int':
275
+ labels = col.astype(int)
276
+ elif self.label_type == 'float':
277
+ labels = col.astype(float)
278
+ else:
279
+ assert 0, 'unkown label type'
280
+ continue
281
+
282
+ if cinfo['type'] == CONTINUOUS:
283
+ cmin = cinfo['min']
284
+ cmax = cinfo['max']
285
+ if cmin >= 0 and cmax >= 1e3:
286
+ feature = np.log(np.maximum(col, 1e-2))
287
+
288
+ else:
289
+ feature = (col - cmin) / (cmax - cmin) * 5
290
+
291
+ else:
292
+ if cinfo['size'] <= 2:
293
+ feature = col
294
+
295
+ else:
296
+ encoder = self.encoders.get(index)
297
+ col = col.reshape(-1, 1)
298
+ if encoder:
299
+ feature = encoder.transform(col)
300
+ else:
301
+ encoder = OneHotEncoder(sparse=False, handle_unknown='ignore')
302
+ self.encoders[index] = encoder
303
+ feature = encoder.fit_transform(col)
304
+
305
+ features.append(feature)
306
+
307
+ features = np.column_stack(features)
308
+
309
+ return features, labels
310
+
311
+
312
+ def _prepare_ml_problem(train, val, test, metadata, eval):
313
+ fm = FeatureMaker(metadata)
314
+ x_trains, y_trains = [], []
315
+
316
+ for i in train:
317
+ x_train, y_train = fm.make_features(i)
318
+ x_trains.append(x_train)
319
+ y_trains.append(y_train)
320
+
321
+ x_val, y_val = fm.make_features(val)
322
+ if eval is None:
323
+ x_test = None
324
+ y_test = None
325
+ else:
326
+ x_test, y_test = fm.make_features(test)
327
+ model = _MODELS[metadata['problem_type']]
328
+
329
+ return x_trains, y_trains, x_val, y_val, x_test, y_test, model
330
+
331
+
332
+ def _weighted_f1(y_test, pred):
333
+ report = classification_report(y_test, pred, output_dict=True)
334
+ classes = list(report.keys())[:-3]
335
+ proportion = [ report[i]['support'] / len(y_test) for i in classes]
336
+ weighted_f1 = np.sum(list(map(lambda i, prop: report[i]['f1-score']* (1-prop)/(len(classes)-1), classes, proportion)))
337
+ return weighted_f1
338
+
339
+
340
+ @ignore_warnings(category=ConvergenceWarning)
341
+ def _evaluate_multi_classification(train, test, info, val=None):
342
+ x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val)
343
+ best_f1_scores = []
344
+ unique_labels = np.unique(y_trains)
345
+
346
+
347
+ best_f1_scores = []
348
+ best_weighted_scores = []
349
+ best_auroc_scores = []
350
+ best_acc_scores = []
351
+ best_avg_scores = []
352
+
353
+ for model_spec in classifiers:
354
+ model_class = model_spec['class']
355
+ model_kwargs = model_spec.get('kwargs', dict())
356
+ model_repr = model_class.__name__
357
+
358
+ unique_labels = np.unique(y_trains)
359
+
360
+ param_set = list(ParameterGrid(model_kwargs))
361
+
362
+ results = []
363
+ for param in tqdm(param_set):
364
+ model = model_class(**param)
365
+
366
+ try:
367
+ model.fit(x_trains, y_trains)
368
+ except:
369
+ pass
370
+
371
+ if len(unique_labels) != len(np.unique(y_valid)):
372
+ pred = [unique_labels[0]] * len(x_valid)
373
+ pred_prob = np.array([1.] * len(x_valid))
374
+ else:
375
+ pred = model.predict(x_valid)
376
+ pred_prob = model.predict_proba(x_valid)
377
+
378
+ macro_f1 = f1_score(y_valid, pred, average='macro')
379
+ weighted_f1 = _weighted_f1(y_valid, pred)
380
+ acc = accuracy_score(y_valid, pred)
381
+
382
+ # 3. auroc
383
+ # size = [a["size"] for a in metadata["columns"] if a["name"] == "label"][0]
384
+ size = len(set(unique_labels))
385
+ rest_label = set(range(size)) - set(unique_labels)
386
+ tmp = []
387
+ j = 0
388
+ for i in range(size):
389
+ if i in rest_label:
390
+ tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis])
391
+ else:
392
+ try:
393
+ tmp.append(pred_prob[:,[j]])
394
+ except:
395
+ tmp.append(pred_prob[:, np.newaxis])
396
+ j += 1
397
+
398
+ roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp), multi_class='ovr')
399
+
400
+ results.append(
401
+ {
402
+ "name": model_repr,
403
+ "param": param,
404
+ "macro_f1": macro_f1,
405
+ "weighted_f1": weighted_f1,
406
+ "roc_auc": roc_auc,
407
+ "accuracy": acc
408
+ }
409
+ )
410
+
411
+ results = pd.DataFrame(results)
412
+ results['avg'] = results.loc[:, ['macro_f1', 'weighted_f1', 'roc_auc']].mean(axis=1)
413
+ best_f1_param = results.param[results.macro_f1.idxmax()]
414
+ best_weighted_param = results.param[results.weighted_f1.idxmax()]
415
+ best_auroc_param = results.param[results.roc_auc.idxmax()]
416
+ best_acc_param = results.param[results.accuracy.idxmax()]
417
+ best_avg_param = results.param[results.avg.idxmax()]
418
+
419
+
420
+ # test the best model
421
+ results = pd.DataFrame(results)
422
+ # best_param = results.param[results.macro_f1.idxmax()]
423
+
424
+ def _calc(best_model):
425
+ best_scores = []
426
+
427
+ x_train = x_trains
428
+ y_train = y_trains
429
+
430
+ try:
431
+ best_model.fit(x_train, y_train)
432
+ except:
433
+ pass
434
+
435
+ if len(unique_labels) != len(np.unique(y_test)):
436
+ pred = [unique_labels[0]] * len(x_test)
437
+ pred_prob = np.array([1.] * len(x_test))
438
+ else:
439
+ pred = best_model.predict(x_test)
440
+ pred_prob = best_model.predict_proba(x_test)
441
+
442
+ macro_f1 = f1_score(y_test, pred, average='macro')
443
+ weighted_f1 = _weighted_f1(y_test, pred)
444
+ acc = accuracy_score(y_test, pred)
445
+
446
+ # 3. auroc
447
+ size = len(set(unique_labels))
448
+ rest_label = set(range(size)) - set(unique_labels)
449
+ tmp = []
450
+ j = 0
451
+ for i in range(size):
452
+ if i in rest_label:
453
+ tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis])
454
+ else:
455
+ try:
456
+ tmp.append(pred_prob[:,[j]])
457
+ except:
458
+ tmp.append(pred_prob[:, np.newaxis])
459
+ j += 1
460
+ roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp), multi_class='ovr')
461
+
462
+ best_scores.append(
463
+ {
464
+ "name": model_repr,
465
+ "macro_f1": macro_f1,
466
+ "weighted_f1": weighted_f1,
467
+ "roc_auc": roc_auc,
468
+ "accuracy": acc
469
+ }
470
+ )
471
+ return pd.DataFrame(best_scores)
472
+
473
+ def _df(dataframe):
474
+ return {
475
+ "name": model_repr,
476
+ "macro_f1": dataframe.macro_f1.values[0],
477
+ "roc_auc": dataframe.roc_auc.values[0],
478
+ "weighted_f1": dataframe.weighted_f1.values[0],
479
+ "accuracy": dataframe.accuracy.values[0],
480
+ }
481
+
482
+ best_f1_scores.append(_df(_calc(model_class(**best_f1_param))))
483
+ best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param))))
484
+ best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param))))
485
+ best_acc_scores.append(_df(_calc(model_class(**best_acc_param))))
486
+ best_avg_scores.append(_df(_calc(model_class(**best_avg_param))))
487
+
488
+ return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores
489
+
490
+ @ignore_warnings(category=ConvergenceWarning)
491
+ def _evaluate_binary_classification(train, test, info, val=None):
492
+ x_trains, y_trains, x_valid, y_valid, x_test, y_test, classifiers = prepare_ml_problem(train, test, info, val=val)
493
+
494
+ unique_labels = np.unique(y_trains)
495
+
496
+ best_f1_scores = []
497
+ best_weighted_scores = []
498
+ best_auroc_scores = []
499
+ best_acc_scores = []
500
+ best_avg_scores = []
501
+
502
+ for model_spec in classifiers:
503
+
504
+ model_class = model_spec['class']
505
+ model_kwargs = model_spec.get('kwargs', dict())
506
+ model_repr = model_class.__name__
507
+
508
+ unique_labels = np.unique(y_trains)
509
+
510
+ param_set = list(ParameterGrid(model_kwargs))
511
+
512
+ results = []
513
+ for param in tqdm(param_set):
514
+ model = model_class(**param)
515
+
516
+ try:
517
+ model.fit(x_trains, y_trains)
518
+ except ValueError:
519
+ pass
520
+
521
+ if len(unique_labels) == 1:
522
+ pred = [unique_labels[0]] * len(x_valid)
523
+ pred_prob = np.array([1.] * len(x_valid))
524
+ else:
525
+ pred = model.predict(x_valid)
526
+ pred_prob = model.predict_proba(x_valid)
527
+
528
+ binary_f1 = f1_score(y_valid, pred, average='binary')
529
+ weighted_f1 = _weighted_f1(y_valid, pred)
530
+ acc = accuracy_score(y_valid, pred)
531
+ precision = precision_score(y_valid, pred, average='binary')
532
+ recall = recall_score(y_valid, pred, average='binary')
533
+ macro_f1 = f1_score(y_valid, pred, average='macro')
534
+
535
+ # auroc
536
+ size = 2
537
+ rest_label = set(range(size)) - set(unique_labels)
538
+ tmp = []
539
+ j = 0
540
+ for i in range(size):
541
+ if i in rest_label:
542
+ tmp.append(np.array([0] * y_valid.shape[0])[:,np.newaxis])
543
+ else:
544
+ try:
545
+ tmp.append(pred_prob[:,[j]])
546
+ except:
547
+ tmp.append(pred_prob[:, np.newaxis])
548
+ j += 1
549
+ roc_auc = roc_auc_score(np.eye(size)[y_valid], np.hstack(tmp))
550
+
551
+ results.append(
552
+ {
553
+ "name": model_repr,
554
+ "param": param,
555
+ "binary_f1": binary_f1,
556
+ "weighted_f1": weighted_f1,
557
+ "roc_auc": roc_auc,
558
+ "accuracy": acc,
559
+ "precision": precision,
560
+ "recall": recall,
561
+ "macro_f1": macro_f1
562
+ }
563
+ )
564
+
565
+
566
+ # test the best model
567
+ results = pd.DataFrame(results)
568
+ results['avg'] = results.loc[:, ['binary_f1', 'weighted_f1', 'roc_auc']].mean(axis=1)
569
+ best_f1_param = results.param[results.binary_f1.idxmax()]
570
+ best_weighted_param = results.param[results.weighted_f1.idxmax()]
571
+ best_auroc_param = results.param[results.roc_auc.idxmax()]
572
+ best_acc_param = results.param[results.accuracy.idxmax()]
573
+ best_avg_param = results.param[results.avg.idxmax()]
574
+
575
+
576
+ def _calc(best_model):
577
+ best_scores = []
578
+
579
+ best_model.fit(x_trains, y_trains)
580
+
581
+ if len(unique_labels) == 1:
582
+ pred = [unique_labels[0]] * len(x_test)
583
+ pred_prob = np.array([1.] * len(x_test))
584
+ else:
585
+ pred = best_model.predict(x_test)
586
+ pred_prob = best_model.predict_proba(x_test)
587
+
588
+ binary_f1 = f1_score(y_test, pred, average='binary')
589
+ weighted_f1 = _weighted_f1(y_test, pred)
590
+ acc = accuracy_score(y_test, pred)
591
+ precision = precision_score(y_test, pred, average='binary')
592
+ recall = recall_score(y_test, pred, average='binary')
593
+ macro_f1 = f1_score(y_test, pred, average='macro')
594
+
595
+ # auroc
596
+ size = 2
597
+ rest_label = set(range(size)) - set(unique_labels)
598
+ tmp = []
599
+ j = 0
600
+ for i in range(size):
601
+ if i in rest_label:
602
+ tmp.append(np.array([0] * y_test.shape[0])[:,np.newaxis])
603
+ else:
604
+ try:
605
+ tmp.append(pred_prob[:,[j]])
606
+ except:
607
+ tmp.append(pred_prob[:, np.newaxis])
608
+ j += 1
609
+ try:
610
+ roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp))
611
+ except ValueError:
612
+ tmp[1] = tmp[1].reshape(20000, 1)
613
+ roc_auc = roc_auc_score(np.eye(size)[y_test], np.hstack(tmp))
614
+
615
+ best_scores.append(
616
+ {
617
+ "name": model_repr,
618
+ # "param": param,
619
+ "binary_f1": binary_f1,
620
+ "weighted_f1": weighted_f1,
621
+ "roc_auc": roc_auc,
622
+ "accuracy": acc,
623
+ "precision": precision,
624
+ "recall": recall,
625
+ "macro_f1": macro_f1
626
+ }
627
+ )
628
+
629
+ return pd.DataFrame(best_scores)
630
+ def _df(dataframe):
631
+ return {
632
+ "name": model_repr,
633
+ "binary_f1": dataframe.binary_f1.values[0],
634
+ "roc_auc": dataframe.roc_auc.values[0],
635
+ "weighted_f1": dataframe.weighted_f1.values[0],
636
+ "accuracy": dataframe.accuracy.values[0],
637
+ }
638
+
639
+ best_f1_scores.append(_df(_calc(model_class(**best_f1_param))))
640
+ best_weighted_scores.append(_df(_calc(model_class(**best_weighted_param))))
641
+ best_auroc_scores.append(_df(_calc(model_class(**best_auroc_param))))
642
+ best_acc_scores.append(_df(_calc(model_class(**best_acc_param))))
643
+ best_avg_scores.append(_df(_calc(model_class(**best_avg_param))))
644
+
645
+ return best_f1_scores, best_weighted_scores, best_auroc_scores, best_acc_scores, best_avg_scores
646
+
647
+ @ignore_warnings(category=ConvergenceWarning)
648
+ def _evaluate_regression(train, test, info, val=None):
649
+
650
+ x_trains, y_trains, x_valid, y_valid, x_test, y_test, regressors = prepare_ml_problem(train, test, info, val=val)
651
+
652
+
653
+ best_r2_scores = []
654
+ best_ev_scores = []
655
+ best_mae_scores = []
656
+ best_rmse_scores = []
657
+ best_avg_scores = []
658
+
659
+ y_trains = np.log(np.clip(y_trains, 1, 20000))
660
+ y_test = np.log(np.clip(y_test, 1, 20000))
661
+
662
+ for model_spec in regressors:
663
+ model_class = model_spec['class']
664
+ model_kwargs = model_spec.get('kwargs', dict())
665
+ model_repr = model_class.__name__
666
+
667
+ param_set = list(ParameterGrid(model_kwargs))
668
+
669
+ results = []
670
+ for param in tqdm(param_set):
671
+ model = model_class(**param)
672
+ model.fit(x_trains, y_trains)
673
+ pred = model.predict(x_valid)
674
+
675
+ r2 = r2_score(y_valid, pred)
676
+ explained_variance = explained_variance_score(y_valid, pred)
677
+ mean_squared = mean_squared_error(y_valid, pred)
678
+ root_mean_squared = mean_squared_error(y_valid, pred, squared=False)
679
+ mean_absolute = mean_absolute_error(y_valid, pred)
680
+
681
+ results.append(
682
+ {
683
+ "name": model_repr,
684
+ "param": param,
685
+ "r2": r2,
686
+ "explained_variance": explained_variance,
687
+ "mean_squared": mean_squared,
688
+ "mean_absolute": mean_absolute,
689
+ "rmse": root_mean_squared
690
+ }
691
+ )
692
+
693
+ results = pd.DataFrame(results)
694
+ # results['avg'] = results.loc[:, ['r2', 'rmse']].mean(axis=1)
695
+ best_r2_param = results.param[results.r2.idxmax()]
696
+ best_ev_param = results.param[results.explained_variance.idxmax()]
697
+ best_mae_param = results.param[results.mean_absolute.idxmin()]
698
+ best_rmse_param = results.param[results.rmse.idxmin()]
699
+ # best_avg_param = results.param[results.avg.idxmax()]
700
+
701
+ def _calc(best_model):
702
+ best_scores = []
703
+ x_train, y_train = x_trains, y_trains
704
+
705
+ best_model.fit(x_train, y_train)
706
+ pred = best_model.predict(x_test)
707
+
708
+ r2 = r2_score(y_test, pred)
709
+ explained_variance = explained_variance_score(y_test, pred)
710
+ mean_squared = mean_squared_error(y_test, pred)
711
+ root_mean_squared = mean_squared_error(y_test, pred, squared=False)
712
+ mean_absolute = mean_absolute_error(y_test, pred)
713
+
714
+ best_scores.append(
715
+ {
716
+ "name": model_repr,
717
+ "param": param,
718
+ "r2": r2,
719
+ "explained_variance": explained_variance,
720
+ "mean_squared": mean_squared,
721
+ "mean_absolute": mean_absolute,
722
+ "rmse": root_mean_squared
723
+ }
724
+ )
725
+
726
+ return pd.DataFrame(best_scores)
727
+
728
+ def _df(dataframe):
729
+ return {
730
+ "name": model_repr,
731
+ "r2": dataframe.r2.values[0].astype(float),
732
+ "explained_variance": dataframe.explained_variance.values[0].astype(float),
733
+ "MAE": dataframe.mean_absolute.values[0].astype(float),
734
+ "RMSE": dataframe.rmse.values[0].astype(float),
735
+ }
736
+
737
+ best_r2_scores.append(_df(_calc(model_class(**best_r2_param))))
738
+ best_ev_scores.append(_df(_calc(model_class(**best_ev_param))))
739
+ best_mae_scores.append(_df(_calc(model_class(**best_mae_param))))
740
+ best_rmse_scores.append(_df(_calc(model_class(**best_rmse_param))))
741
+
742
+ return best_r2_scores, best_rmse_scores
743
+
744
+ @ignore_warnings(category=ConvergenceWarning)
745
+ def compute_diversity(train, fake):
746
+ nearest_k = 5
747
+ if train.shape[0] >= 50000:
748
+ num = np.random.randint(0, train.shape[0], 50000)
749
+ real_features = train[num]
750
+ fake_features_lst = [i[num] for i in fake]
751
+ else:
752
+ num = train.shape[0]
753
+ real_features = train[:num]
754
+ fake_features_lst = [i[:num] for i in fake]
755
+ scores = []
756
+ for i, data in enumerate(fake_features_lst):
757
+ fake_features = data
758
+ metrics = compute_prdc(real_features=real_features,
759
+ fake_features=fake_features,
760
+ nearest_k=nearest_k)
761
+ metrics['i'] = i
762
+ scores.append(metrics)
763
+ return pd.DataFrame(scores).mean(axis=0), pd.DataFrame(scores).std(axis=0)
764
+
765
+ _EVALUATORS = {
766
+ 'binclass': _evaluate_binary_classification,
767
+ 'multiclass': _evaluate_multi_classification,
768
+ 'regression': _evaluate_regression
769
+ }
770
+
771
+ def get_evaluator(problem_type):
772
+ return _EVALUATORS[problem_type]
773
+
774
+
775
+ def compute_scores(train, test, synthesized_data, metadata, eval):
776
+ a, b, c = _EVALUATORS[metadata['problem_type']](train=train, test=test, fake=synthesized_data, metadata=metadata, eval=eval)
777
+ if eval is None:
778
+ return a.mean(axis=0), a.std(axis=0), a[['name','param']]
779
+ else:
780
+ return a.mean(axis=0), a.std(axis=0)
781
+
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/mle/tabular_dataload.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The Google Research Authors.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ # pylint: skip-file
17
+ """Return training and evaluation/test datasets from config files."""
18
+ import torch
19
+ import numpy as np
20
+ import pandas as pd
21
+ from tabular_transformer import GeneralTransformer
22
+ import json
23
+ import logging
24
+ import os
25
+
26
+ CATEGORICAL = "categorical"
27
+ CONTINUOUS = "continuous"
28
+
29
+ LOGGER = logging.getLogger(__name__)
30
+
31
+ DATA_PATH = os.path.join(os.path.dirname(__file__), 'tabular_datasets')
32
+
33
+ def _load_json(path):
34
+ with open(path) as json_file:
35
+ return json.load(json_file)
36
+
37
+
38
+ def _load_file(filename, loader):
39
+ local_path = os.path.join(DATA_PATH, filename)
40
+
41
+ if loader == np.load:
42
+ return loader(local_path, allow_pickle=True)
43
+ return loader(local_path)
44
+
45
+
46
+ def _get_columns(metadata):
47
+ categorical_columns = list()
48
+
49
+ for column_idx, column in enumerate(metadata['columns']):
50
+ if column['type'] == CATEGORICAL:
51
+ categorical_columns.append(column_idx)
52
+
53
+ return categorical_columns
54
+
55
+
56
+ def load_data(name):
57
+ data_dir = f'data/{name}'
58
+ info_path = f'{data_dir}/info.json'
59
+
60
+ train = pd.read_csv(f'{data_dir}/train.csv').to_numpy()
61
+ test = pd.read_csv(f'{data_dir}/test.csv').to_numpy()
62
+
63
+ with open(f'{data_dir}/info.json', 'r') as f:
64
+ info = json.load(f)
65
+
66
+ task_type = info['task_type']
67
+
68
+ num_cols = info['num_col_idx']
69
+ cat_cols = info['cat_col_idx']
70
+ target_cols = info['target_col_idx']
71
+
72
+ if task_type != 'regression':
73
+ cat_cols = cat_cols + target_cols
74
+
75
+ return train, test, (cat_cols, info)
76
+
77
+
78
+ def get_dataset(FLAGS, evaluation=False):
79
+
80
+ batch_size = FLAGS.training_batch_size if not evaluation else FLAGS.eval_batch_size
81
+
82
+ if batch_size % torch.cuda.device_count() != 0:
83
+ raise ValueError(f'Batch sizes ({batch_size} must be divided by'
84
+ f'the number of devices ({torch.cuda.device_count()})')
85
+
86
+
87
+ # Create dataset builders for tabular data.
88
+ train, test, cols = load_data(FLAGS.dataname)
89
+ cols_idx = list(np.arange(train.shape[1]))
90
+ dis_idx = cols[0]
91
+ con_idx = [x for x in cols_idx if x not in dis_idx]
92
+
93
+ #split continuous and categorical
94
+ train_con = train[:,con_idx]
95
+ train_dis = train[:,dis_idx]
96
+
97
+ #new index
98
+ cat_idx_ = list(np.arange(train_dis.shape[1]))[:len(cols[0])]
99
+
100
+ transformer_con = GeneralTransformer()
101
+ transformer_dis = GeneralTransformer()
102
+
103
+ transformer_con.fit(train_con, [])
104
+ transformer_dis.fit(train_dis, cat_idx_)
105
+
106
+ train_con_data = transformer_con.transform(train_con)
107
+ train_dis_data = transformer_dis.transform(train_dis)
108
+
109
+
110
+ return train, train_con_data, train_dis_data, test, (transformer_con, transformer_dis, cols[1]), con_idx, dis_idx
111
+
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/mle/tabular_transformer.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+
4
+ CATEGORICAL = "categorical"
5
+ CONTINUOUS = "continuous"
6
+
7
+ class Transformer:
8
+
9
+ @staticmethod
10
+ def get_metadata(data, categorical_columns=tuple()):
11
+ meta = []
12
+
13
+ df = pd.DataFrame(data)
14
+ for index in df:
15
+ column = df[index]
16
+
17
+ if index in categorical_columns:
18
+ mapper = column.value_counts().index.tolist()
19
+ meta.append({
20
+ "name": index,
21
+ "type": CATEGORICAL,
22
+ "size": len(mapper),
23
+ "i2s": mapper
24
+ })
25
+ else:
26
+ meta.append({
27
+ "name": index,
28
+ "type": CONTINUOUS,
29
+ "min": column.min(),
30
+ "max": column.max(),
31
+ })
32
+
33
+ return meta
34
+
35
+ def fit(self, data, categorical_columns=tuple()):
36
+ raise NotImplementedError
37
+
38
+ def transform(self, data):
39
+ raise NotImplementedError
40
+
41
+ def inverse_transform(self, data):
42
+ raise NotImplementedError
43
+
44
+
45
+ class GeneralTransformer(Transformer):
46
+
47
+ def __init__(self, act='tanh'):
48
+ self.act = act
49
+ self.meta = None
50
+ self.output_dim = None
51
+
52
+ def fit(self, data, categorical_columns=tuple()):
53
+ self.meta = self.get_metadata(data, categorical_columns)
54
+ self.output_dim = 0
55
+ for info in self.meta:
56
+ if info['type'] in [CONTINUOUS]:
57
+ self.output_dim += 1
58
+ else:
59
+ self.output_dim += info['size']
60
+
61
+ def transform(self, data):
62
+ data_t = []
63
+ self.output_info = []
64
+ for id_, info in enumerate(self.meta):
65
+ col = data[:, id_]
66
+ if info['type'] == CONTINUOUS:
67
+ col = (col - (info['min'])) / (info['max'] - info['min'])
68
+ if self.act == 'tanh':
69
+ col = col * 2 - 1
70
+ data_t.append(col.reshape([-1, 1]))
71
+ self.output_info.append((1, self.act))
72
+
73
+ else:
74
+ col_t = np.zeros([len(data), info['size']])
75
+ idx = list(map(info['i2s'].index, col))
76
+ col_t[np.arange(len(data)), idx] = 1
77
+ data_t.append(col_t)
78
+ self.output_info.append((info['size'], 'softmax'))
79
+
80
+ return np.concatenate(data_t, axis=1)
81
+
82
+ def inverse_transform(self, data):
83
+ if self.meta[1]['type'] == CONTINUOUS:
84
+ data_t = np.zeros([len(data), len(self.meta)])
85
+ else:
86
+ dtype = np.dtype('U50')
87
+ data_t = np.empty([len(data), len(self.meta)], dtype=dtype)
88
+
89
+
90
+ data = data.copy()
91
+ for id_, info in enumerate(self.meta):
92
+
93
+ if info['type'] == CONTINUOUS:
94
+ current = data[:, 0]
95
+ data = data[:, 1:]
96
+
97
+ if self.act == 'tanh':
98
+ current = (current + 1) / 2
99
+
100
+ current = np.clip(current, 0, 1)
101
+ data_t[:, id_] = current * (info['max'] - info['min']) + info['min']
102
+
103
+ else:
104
+ current = data[:, :info['size']]
105
+ data = data[:, info['size']:]
106
+ idx = np.argmax(current, axis=1)
107
+ recovered = list(map(info['i2s'].__getitem__, idx))
108
+
109
+ data_t[:, id_] = recovered
110
+ return data_t
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval/visualize_density.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # %%
2
+ import numpy as np
3
+ import pandas as pd
4
+ import torch
5
+ import os
6
+
7
+ import json
8
+
9
+ # Metrics
10
+ from sdmetrics.visualization import get_column_plot
11
+
12
+ import plotly.io as pio
13
+ from PIL import Image
14
+ from io import BytesIO
15
+
16
+ from tqdm import tqdm
17
+ import argparse
18
+
19
+ def main(args):
20
+ dataname = args.dataname
21
+ sample_file_name = args.sample_file_name
22
+
23
+ syn_path = f'synthetic/{dataname}/{sample_file_name}'
24
+ real_path = f'synthetic/{dataname}/real.csv'
25
+
26
+ syn_data = pd.read_csv(syn_path)
27
+ real_data = pd.read_csv(real_path)
28
+
29
+ print((real_data[:2]))
30
+
31
+ data_dir = f'data/{dataname}'
32
+ with open(f'{data_dir}/info.json', 'r') as f:
33
+ info = json.load(f)
34
+
35
+ big_img = plot_density(syn_data, real_data, info)
36
+
37
+ save_dir = f"eval/density_graphs/{dataname}"
38
+ if not os.path.exists(save_dir):
39
+ os.makedirs(save_dir)
40
+ save_path = os.path.join(save_dir, sample_file_name.replace('.csv', '.png'))
41
+ big_img.save(save_path)
42
+ print(f"Saved density graph to {save_path}")
43
+
44
+ def plot_density(syn_data, real_data, info, num_per_row=3):
45
+ column_names = info['column_names']
46
+ num_cat = len(column_names)
47
+ num_col = num_per_row
48
+ num_row = (num_cat-1)//num_col+1
49
+
50
+ imgs = []
51
+ for i, col in tqdm(enumerate(column_names), total = len(column_names)):
52
+ # plot_type = 'bar' if i in info['cat_col_idx'] else 'distplot'
53
+ plot_type = 'bar' if info['metadata']['columns'][str(i)]['sdtype'] == 'categorical' else 'distplot'
54
+ if plot_type == 'distplot' and (syn_data[col][0] == syn_data[col]).all(): # to tackle a very weird bug
55
+ # If the continuous data all aggregate at a single value, get_column_plot() cannot plot a density curve for it.
56
+ # So, we perturb one entry of the cont data by a small amount
57
+ print(f"\n ALERT: the generated samples column_{i} with name '{col}' all has the same value of {syn_data[col][0]} \n")
58
+ syn_data[col][0] += 1e-5
59
+ fig = get_column_plot(
60
+ real_data=real_data,
61
+ synthetic_data=syn_data,
62
+ column_name=col,
63
+ plot_type=plot_type
64
+ )
65
+
66
+ img_bytes = pio.to_image(fig, format='png')
67
+ img = Image.open(BytesIO(img_bytes))
68
+ imgs.append(img)
69
+
70
+ width, height = imgs[0].size
71
+ big_img = Image.new('RGB', (width * num_col, height * num_row))
72
+ for i, img in enumerate(imgs):
73
+ coordinate = (i%num_col * width, i//num_col * height)
74
+ big_img.paste(img, coordinate)
75
+ return big_img
76
+
77
+ if __name__ == '__main__':
78
+ parser = argparse.ArgumentParser()
79
+
80
+ parser.add_argument('--dataname', type=str, default='adult')
81
+ parser.add_argument('--sample_file_name', type=str, default='tabsyn.csv')
82
+
83
+ args = parser.parse_args()
84
+
85
+ main(args)
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/eval_impute.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn.preprocessing import OneHotEncoder
4
+ from sklearn.metrics import f1_score, roc_auc_score
5
+ from sklearn.metrics import root_mean_squared_error
6
+ import argparse
7
+ import json
8
+
9
+
10
+ parser = argparse.ArgumentParser(description='Missing Value Imputation')
11
+
12
+ parser.add_argument('--dataname', type=str, default='adult', help='Name of dataset.')
13
+ parser.add_argument('--exp_name', type=str, default=None)
14
+ parser.add_argument('--col', type=int, default=0, help='Numerical Column to Impute')
15
+ parser.add_argument('--non_learnable_schedule', action='store_true')
16
+
17
+ args = parser.parse_args()
18
+
19
+ dataname = args.dataname
20
+ exp_name = args.exp_name
21
+ if exp_name is None:
22
+ exp_name = "non_learnable_schedule" if args.non_learnable_schedule else "learnable_schedule"
23
+ col = args.col
24
+
25
+ dataname = args.dataname
26
+
27
+ data_dir = f'data/{dataname}'
28
+
29
+ real_path = f'{data_dir}/test.csv'
30
+
31
+ info_path = f'data/{dataname}/info.json'
32
+ with open(info_path, 'r') as f:
33
+ info = json.load(f)
34
+ task_type = info['task_type']
35
+
36
+
37
+ encoder = OneHotEncoder()
38
+
39
+ real_data = pd.read_csv(real_path)
40
+ target_col = real_data.columns[info['target_col_idx'][0]]
41
+
42
+ if task_type == "binclass":
43
+ real_target = real_data[target_col].to_numpy().reshape(-1,1)
44
+ real_y = encoder.fit_transform(real_target).toarray()
45
+
46
+ syn_y = []
47
+ for i in range(50):
48
+ syn_path = f'impute/{dataname}/{exp_name}/{i}.csv'
49
+ syn_data = pd.read_csv(syn_path)
50
+ target = syn_data[target_col].to_numpy().reshape(-1, 1)
51
+ syn_y.append(encoder.transform(target).toarray())
52
+
53
+ syn_y_prob = np.stack(syn_y).mean(0)
54
+ syn_y_oh = np.argmax(syn_y_prob, axis=1)
55
+ num_classes = np.max(syn_y_oh) + 1
56
+ syn_y_oh = np.eye(num_classes)[syn_y_oh]
57
+
58
+
59
+
60
+
61
+ micro_f1 = f1_score(real_y.argmax(axis=1), syn_y_prob.argmax(axis=1), average='micro')
62
+ auc = roc_auc_score(real_y, syn_y_prob, average='micro')
63
+ auc_argmaxed = roc_auc_score(real_y, syn_y_oh, average='micro')
64
+ print("AUC: ", round(auc*100, 3))
65
+ else:
66
+ y_test = real_data[target_col].to_numpy()
67
+ y_test = np.log(np.clip(y_test, 1, 20000))
68
+
69
+ syn_y_ = []
70
+ error = []
71
+ for i in range(50):
72
+ syn_path = f'impute/{dataname}/{exp_name}/{i}.csv'
73
+ syn_data = pd.read_csv(syn_path)
74
+ syn_y = syn_data[target_col].to_numpy()
75
+ syn_y = np.log(np.clip(syn_y, 1, 20000))
76
+ syn_y_.append(syn_y)
77
+
78
+ pred = np.stack(syn_y_).mean(0)
79
+ root_mean_squared = root_mean_squared_error(y_test, pred) # mean_squared_error with squared=False is deprecated
80
+
81
+ print("RMSE:", round(root_mean_squared, 4))
82
+
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/images/tabdiff_demo.gif ADDED

Git LFS Details

  • SHA256: 8b3f9c4819c4ef4abf8ade862da25915b826212f3d3ef9e4774ddde19db88bf2
  • Pointer size: 132 Bytes
  • Size of remote file: 3.26 MB
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/images/tabdiff_demo.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:90c8072ab9a7dcc73d7bc3ea32b0e961cae5fcd7d73b6ffc2ffb44e6c291962f
3
+ size 1108599
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/images/tabdiff_flowchart.jpg ADDED

Git LFS Details

  • SHA256: 34e4115e21b32199dd6cc0a0664f924907fcf1f66e2063616c50025f597b7409
  • Pointer size: 131 Bytes
  • Size of remote file: 383 kB
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/main.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from tabdiff.main import main as tabdiff_main
3
+ import argparse
4
+
5
+ if __name__ == '__main__':
6
+ parser = argparse.ArgumentParser(description='Training of TabDiff')
7
+
8
+ # General configs
9
+ parser.add_argument('--dataname', type=str, default='adult', help='Name dataset, one of those in data/ dir')
10
+ parser.add_argument('--mode', type=str, default='train', help='train or test')
11
+ parser.add_argument('--method', type=str, default='tabdiff', help='Currently we only release our model TabDiff. Baselines will be released soon.')
12
+ parser.add_argument('--gpu', type=int, default=0, help='GPU index')
13
+ parser.add_argument('--debug', action='store_true', help='Enable debug mode')
14
+ parser.add_argument('--no_wandb', action='store_true', help='disable wandb')
15
+ parser.add_argument('--exp_name', type=str, default=None, help='Experiment name, used to name log directories and the wandb run name')
16
+ parser.add_argument('--deterministic', action='store_true', help='Whether to make the entire process deterministic, i.e., fix global random seeds')
17
+
18
+ # Configs for tabdiff
19
+ parser.add_argument('--y_only', action='store_true', help='Train guidance model that only model the target column')
20
+ parser.add_argument('--non_learnable_schedule', action='store_true', help='disable learnable noise schedule')
21
+
22
+ # Configs for testing tabdiff
23
+ parser.add_argument('--num_samples_to_generate', type=int, default=None, help='Number of samples to be generated while testing')
24
+ parser.add_argument('--ckpt_path', type=str, default=None, help='Path to the model checkpoint to be tested')
25
+ parser.add_argument('--report', action='store_true', help="Report testing mode: this mode sequentially runs <num_runs> test runs and report the avg and std")
26
+ parser.add_argument('--num_runs', type=int, default=20, help="Number of runs to be averaged in the report testing mode")
27
+
28
+ # Configs for imputation
29
+ parser.add_argument('--impute', action='store_true')
30
+ parser.add_argument('--trial_start', type=int, default=0)
31
+ parser.add_argument('--trial_size', type=int, default=50)
32
+ parser.add_argument('--resample_rounds', type=int, default=1)
33
+ parser.add_argument('--impute_condition', type=str, default="x_t")
34
+ parser.add_argument('--y_only_model_path', type=str, default=None, help="Path to the y_only model checkpoint that will be used as the unconditional guidance model")
35
+ parser.add_argument('--w_num', type=float, default=0.6)
36
+ parser.add_argument('--w_cat', type=float, default=0.6)
37
+
38
+ args = parser.parse_args()
39
+
40
+ # check cuda
41
+ if args.gpu != -1 and torch.cuda.is_available():
42
+ args.device = f'cuda:{args.gpu}'
43
+ else:
44
+ args.device = 'cpu'
45
+
46
+ tabdiff_main(args)
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/process_dataset.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import os
4
+ import sys
5
+ import json
6
+ import argparse
7
+
8
+ from sklearn.preprocessing import OrdinalEncoder
9
+ from sklearn import model_selection
10
+
11
+ TYPE_TRANSFORM ={
12
+ 'float', np.float32,
13
+ 'str', str,
14
+ 'int', int
15
+ }
16
+
17
+ INFO_PATH = 'data/Info'
18
+
19
+ parser = argparse.ArgumentParser(description='process dataset')
20
+
21
+ # General configs
22
+ parser.add_argument('--dataname', type=str, default=None, help='Name of dataset.')
23
+ args = parser.parse_args()
24
+
25
+ def preprocess_beijing():
26
+ with open(f'{INFO_PATH}/beijing.json', 'r') as f:
27
+ info = json.load(f)
28
+
29
+ data_path = info['raw_data_path']
30
+
31
+ data_df = pd.read_csv(data_path)
32
+ columns = data_df.columns
33
+
34
+ data_df = data_df[columns[1:]]
35
+
36
+
37
+ df_cleaned = data_df.dropna()
38
+ df_cleaned.to_csv(info['data_path'], index = False)
39
+
40
+ def preprocess_beijing_dcr():
41
+ with open(f'{INFO_PATH}/beijing_dcr.json', 'r') as f:
42
+ info = json.load(f)
43
+
44
+ data_path = info['raw_data_path']
45
+
46
+ data_df = pd.read_csv(data_path)
47
+ columns = data_df.columns
48
+
49
+ data_df = data_df[columns[1:]]
50
+
51
+
52
+ df_cleaned = data_df.dropna()
53
+ df_cleaned.to_csv(info['data_path'], index = False)
54
+
55
+ def preprocess_news(remove_cat=False):
56
+ name = 'news' if not remove_cat else 'news_nocat'
57
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
58
+ info = json.load(f)
59
+
60
+ data_path = info['raw_data_path']
61
+ data_df = pd.read_csv(data_path)
62
+ data_df = data_df.drop('url', axis=1)
63
+
64
+ columns = np.array(data_df.columns.tolist())
65
+
66
+ cat_columns1 = columns[list(range(12,18))]
67
+ cat_columns2 = columns[list(range(30,38))]
68
+
69
+ if not remove_cat:
70
+ cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1)
71
+ cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1)
72
+
73
+ data_df = data_df.drop(cat_columns2, axis=1)
74
+ data_df = data_df.drop(cat_columns1, axis=1)
75
+
76
+ if not remove_cat:
77
+ data_df['data_channel'] = cat_col1
78
+ data_df['weekday'] = cat_col2
79
+
80
+ data_save_path = f'data/{name}/{name}.csv'
81
+ data_df.to_csv(f'{data_save_path}', index = False)
82
+
83
+ columns = np.array(data_df.columns.tolist())
84
+ num_columns = columns[list(range(45))]
85
+ cat_columns = ['data_channel', 'weekday'] if not remove_cat else []
86
+ target_columns = columns[[45]]
87
+
88
+ info['num_col_idx'] = list(range(45))
89
+ info['cat_col_idx'] = [46, 47] if not remove_cat else []
90
+ info['target_col_idx'] = [45]
91
+ info['data_path'] = data_save_path
92
+
93
+ with open(f'{INFO_PATH}/{name}.json', 'w') as file:
94
+ json.dump(info, file, indent=4)
95
+
96
+ def preprocess_news_dcr(remove_cat=False):
97
+ name = 'news_dcr' if not remove_cat else 'news_nocat_dcr'
98
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
99
+ info = json.load(f)
100
+
101
+ data_path = info['raw_data_path']
102
+ data_df = pd.read_csv(data_path)
103
+ data_df = data_df.drop('url', axis=1)
104
+
105
+ columns = np.array(data_df.columns.tolist())
106
+
107
+ cat_columns1 = columns[list(range(12,18))]
108
+ cat_columns2 = columns[list(range(30,38))]
109
+
110
+ if not remove_cat:
111
+ cat_col1 = data_df[cat_columns1].astype(int).to_numpy().argmax(axis = 1)
112
+ cat_col2 = data_df[cat_columns2].astype(int).to_numpy().argmax(axis = 1)
113
+
114
+ data_df = data_df.drop(cat_columns2, axis=1)
115
+ data_df = data_df.drop(cat_columns1, axis=1)
116
+
117
+ if not remove_cat:
118
+ data_df['data_channel'] = cat_col1
119
+ data_df['weekday'] = cat_col2
120
+
121
+ data_save_path = f'data/{name}/{name}.csv'
122
+ data_df.to_csv(f'{data_save_path}', index = False)
123
+
124
+ columns = np.array(data_df.columns.tolist())
125
+ num_columns = columns[list(range(45))]
126
+ cat_columns = ['data_channel', 'weekday'] if not remove_cat else []
127
+ target_columns = columns[[45]]
128
+
129
+ info['num_col_idx'] = list(range(45))
130
+ info['cat_col_idx'] = [46, 47] if not remove_cat else []
131
+ info['target_col_idx'] = [45]
132
+ info['data_path'] = data_save_path
133
+
134
+ with open(f'{INFO_PATH}/{name}.json', 'w') as file:
135
+ json.dump(info, file, indent=4)
136
+
137
+ def preprocess_diabetes():
138
+ """
139
+ Preprocesses the diabetes dataset is aligned with the concurrent work
140
+ Continuous Diffusion for Mixed-Type Tabular Data (CDTD):
141
+ https://github.com/muellermarkus/cdtd
142
+ """
143
+ with open(f'{INFO_PATH}/diabetes.json', 'r') as f:
144
+ info = json.load(f)
145
+
146
+ info['num_col_idx'] = list(range(9))
147
+ info['cat_col_idx'] = list(range(9, 36))
148
+ info['target_col_idx'] = [36]
149
+
150
+ data_path = info['raw_data_path']
151
+ df = pd.read_csv(data_path, sep=',')
152
+ df = df[info['column_names']]
153
+ df = df.replace(r' ', np.nan)
154
+ df = df.replace(r'?', np.nan)
155
+ df = df.replace(r'', np.nan)
156
+
157
+ num_features = [info['column_names'][idx] for idx in info['num_col_idx']]
158
+ cat_features = [info['column_names'][idx] for idx in info['cat_col_idx']]
159
+ target = info['column_names'][info['target_col_idx'][0]]
160
+ df[target] = np.where(df[target] == 'NO', 0, 1)
161
+ enc = OrdinalEncoder()
162
+ df['age'] = enc.fit_transform(df['age'].to_numpy().reshape(-1,1))
163
+
164
+ # remove rows with missings in targets
165
+ idx_target_nan = df[target].isna().to_numpy().nonzero()[0]
166
+ df.drop(labels = idx_target_nan, axis = 0, inplace = True)
167
+
168
+ # for categorical features, replace missings with 'empty', which will be counted as a new category
169
+ df[cat_features] = df[cat_features].fillna('empty')
170
+
171
+ # for continuous data, drop missing
172
+ df.dropna(inplace = True)
173
+
174
+ # ensure correct types
175
+ X_cat = df[cat_features].to_numpy().astype('str')
176
+ X_cont = df[num_features].to_numpy().astype('float')
177
+ y = df[[target]].to_numpy()
178
+
179
+ val_prop, test_prop = 0.2, 0.2
180
+ prop = val_prop / (1 - test_prop)
181
+
182
+ stratify = None if info['task_type'] == 'regression' else y
183
+ X_cat_train, X_cat_test, X_cont_train, X_cont_test, y_train, y_test = \
184
+ model_selection.train_test_split(X_cat, X_cont, y, test_size = test_prop,
185
+ stratify = stratify, random_state = 42)
186
+ if val_prop > 0:
187
+ stratify = None if info['task_type'] == 'regression' else y_train
188
+ X_cat_train, X_cat_val, X_cont_train, X_cont_val, y_train, y_val = \
189
+ model_selection.train_test_split(X_cat_train, X_cont_train, y_train,
190
+ stratify = stratify, test_size = prop,
191
+ random_state = 42)
192
+
193
+ train_df = pd.DataFrame(np.concatenate([X_cont_train, X_cat_train, y_train], axis = 1), columns = num_features + cat_features + [target])
194
+ val_df = pd.DataFrame(np.concatenate([X_cont_val, X_cat_val, y_val], axis = 1), columns = num_features + cat_features + [target])
195
+ test_df = pd.DataFrame(np.concatenate([X_cont_test, X_cat_test, y_test], axis = 1), columns = num_features + cat_features + [target])
196
+
197
+ # Save the splited data
198
+ train_df.to_csv(info['data_path'], index = False)
199
+ val_df.to_csv(info['val_path'], index = False)
200
+ test_df.to_csv(info['test_path'], index = False)
201
+ # Save updated info
202
+ with open(f'{INFO_PATH}/diabetes.json', 'w') as file:
203
+ json.dump(info, file, indent=4)
204
+
205
+ def preprocess_diabetes_dcr():
206
+ """
207
+ Preprocesses the diabetes dataset is aligned with the concurrent work
208
+ Continuous Diffusion for Mixed-Type Tabular Data (CDTD):
209
+ https://github.com/muellermarkus/cdtd
210
+ """
211
+ with open(f'{INFO_PATH}/diabetes_dcr.json', 'r') as f:
212
+ info = json.load(f)
213
+
214
+ info['num_col_idx'] = list(range(9))
215
+ info['cat_col_idx'] = list(range(9, 36))
216
+ info['target_col_idx'] = [36]
217
+
218
+ data_path = info['raw_data_path']
219
+ df = pd.read_csv(data_path, sep=',')
220
+ df = df[info['column_names']]
221
+ df = df.replace(r' ', np.nan)
222
+ df = df.replace(r'?', np.nan)
223
+ df = df.replace(r'', np.nan)
224
+
225
+ num_features = [info['column_names'][idx] for idx in info['num_col_idx']]
226
+ cat_features = [info['column_names'][idx] for idx in info['cat_col_idx']]
227
+ target = info['column_names'][info['target_col_idx'][0]]
228
+ df[target] = np.where(df[target] == 'NO', 0, 1)
229
+ enc = OrdinalEncoder()
230
+ df['age'] = enc.fit_transform(df['age'].to_numpy().reshape(-1,1))
231
+
232
+ # remove rows with missings in targets
233
+ idx_target_nan = df[target].isna().to_numpy().nonzero()[0]
234
+ df.drop(labels = idx_target_nan, axis = 0, inplace = True)
235
+
236
+ # for categorical features, replace missings with 'empty', which will be counted as a new category
237
+ df[cat_features] = df[cat_features].fillna('empty')
238
+
239
+ # for continuous data, drop missing
240
+ df.dropna(inplace = True)
241
+
242
+ # ensure correct types
243
+ X_cat = df[cat_features].to_numpy().astype('str')
244
+ X_cont = df[num_features].to_numpy().astype('float')
245
+ y = df[[target]].to_numpy()
246
+
247
+ val_prop, test_prop = 0.0, 0.5 # 50-50 split for dcr eval
248
+ prop = val_prop / (1 - test_prop)
249
+
250
+ stratify = None if info['task_type'] == 'regression' else y
251
+ X_cat_train, X_cat_test, X_cont_train, X_cont_test, y_train, y_test = \
252
+ model_selection.train_test_split(X_cat, X_cont, y, test_size = test_prop,
253
+ stratify = stratify, random_state = 42)
254
+ if val_prop > 0:
255
+ stratify = None if info['task_type'] == 'regression' else y_train
256
+ X_cat_train, X_cat_val, X_cont_train, X_cont_val, y_train, y_val = \
257
+ model_selection.train_test_split(X_cat_train, X_cont_train, y_train,
258
+ stratify = stratify, test_size = prop,
259
+ random_state = 42)
260
+
261
+ train_df = pd.DataFrame(np.concatenate([X_cont_train, X_cat_train, y_train], axis = 1), columns = num_features + cat_features + [target])
262
+ if val_prop > 0:
263
+ val_df = pd.DataFrame(np.concatenate([X_cont_val, X_cat_val, y_val], axis = 1), columns = num_features + cat_features + [target])
264
+ else:
265
+ val_df = pd.DataFrame(columns = num_features + cat_features + [target]).astype(train_df.dtypes)
266
+ test_df = pd.DataFrame(np.concatenate([X_cont_test, X_cat_test, y_test], axis = 1), columns = num_features + cat_features + [target])
267
+
268
+ # Save the splited data
269
+ train_df.to_csv(info['data_path'], index = False)
270
+ val_df.to_csv(info['val_path'], index = False)
271
+ test_df.to_csv(info['test_path'], index = False)
272
+ # Save updated info
273
+ with open(f'{INFO_PATH}/diabetes_dcr.json', 'w') as file:
274
+ json.dump(info, file, indent=4)
275
+
276
+
277
+
278
+ def get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names = None):
279
+
280
+ if not column_names:
281
+ column_names = np.array(data_df.columns.tolist())
282
+
283
+
284
+ idx_mapping = {}
285
+
286
+ curr_num_idx = 0
287
+ curr_cat_idx = len(num_col_idx)
288
+ curr_target_idx = curr_cat_idx + len(cat_col_idx)
289
+
290
+ for idx in range(len(column_names)):
291
+
292
+ if idx in num_col_idx:
293
+ idx_mapping[int(idx)] = curr_num_idx
294
+ curr_num_idx += 1
295
+ elif idx in cat_col_idx:
296
+ idx_mapping[int(idx)] = curr_cat_idx
297
+ curr_cat_idx += 1
298
+ else:
299
+ idx_mapping[int(idx)] = curr_target_idx
300
+ curr_target_idx += 1
301
+
302
+
303
+ inverse_idx_mapping = {}
304
+ for k, v in idx_mapping.items():
305
+ inverse_idx_mapping[int(v)] = k
306
+
307
+ idx_name_mapping = {}
308
+
309
+ for i in range(len(column_names)):
310
+ idx_name_mapping[int(i)] = column_names[i]
311
+
312
+ return idx_mapping, inverse_idx_mapping, idx_name_mapping
313
+
314
+
315
+ def train_val_test_split(data_df, cat_columns, num_train = 0, num_test = 0):
316
+ total_num = data_df.shape[0]
317
+ idx = np.arange(total_num)
318
+
319
+
320
+ seed = 1234
321
+
322
+ while True:
323
+ np.random.seed(seed)
324
+ np.random.shuffle(idx)
325
+
326
+ train_idx = idx[:num_train]
327
+ test_idx = idx[-num_test:]
328
+
329
+
330
+ train_df = data_df.loc[train_idx]
331
+ test_df = data_df.loc[test_idx]
332
+
333
+
334
+
335
+ flag = 0
336
+ for i in cat_columns:
337
+ if len(set(train_df[i])) != len(set(data_df[i])):
338
+ flag = 1
339
+ break
340
+
341
+ if flag == 0:
342
+ break
343
+ else:
344
+ seed += 1
345
+
346
+ return train_df, test_df, seed
347
+
348
+
349
+ def process_data(name):
350
+
351
+ if name == 'news':
352
+ preprocess_news()
353
+ elif name == 'news_nocat':
354
+ preprocess_news(remove_cat=True)
355
+ elif name == 'news_dcr':
356
+ preprocess_news_dcr()
357
+ elif name == 'beijing':
358
+ preprocess_beijing()
359
+ elif name == 'beijing_dcr':
360
+ preprocess_beijing_dcr()
361
+ elif name == 'diabetes':
362
+ preprocess_diabetes()
363
+ elif name == 'diabetes_dcr':
364
+ preprocess_diabetes_dcr()
365
+
366
+ with open(f'{INFO_PATH}/{name}.json', 'r') as f:
367
+ info = json.load(f)
368
+
369
+ data_path = info['data_path']
370
+ if info['file_type'] == 'csv':
371
+ data_df = pd.read_csv(data_path, header = info['header'])
372
+
373
+ elif info['file_type'] == 'xls':
374
+ data_df = pd.read_excel(data_path, sheet_name='Data', header=1)
375
+ data_df = data_df.drop('ID', axis=1)
376
+
377
+ num_data = data_df.shape[0]
378
+
379
+ column_names = info['column_names'] if info['column_names'] else data_df.columns.tolist()
380
+
381
+ num_col_idx = info['num_col_idx']
382
+ cat_col_idx = info['cat_col_idx']
383
+ target_col_idx = info['target_col_idx']
384
+
385
+ num_columns = [column_names[i] for i in num_col_idx]
386
+ cat_columns = [column_names[i] for i in cat_col_idx]
387
+ target_columns = [column_names[i] for i in target_col_idx]
388
+
389
+ idx_mapping, inverse_idx_mapping, idx_name_mapping = get_column_name_mapping(data_df, num_col_idx, cat_col_idx, target_col_idx, column_names)
390
+
391
+ has_val = bool(info['val_path'])
392
+ val_df = pd.DataFrame(columns=data_df.columns).astype(data_df.dtypes) # by default (val_path is not provided), set val_Df to be empty
393
+ if info['test_path']:
394
+
395
+ # if testing data is given
396
+ test_path = info['test_path']
397
+
398
+ if "adult" in name: # BUG: currently data saved at adult's test_path cannot be directly loaded. Consider integrate the following code to a preprocesing function for adult
399
+ with open(test_path, 'r') as f:
400
+ lines = f.readlines()[1:]
401
+ test_save_path = f'data/{name}/test.data'
402
+ if not os.path.exists(test_save_path):
403
+ with open(test_save_path, 'a') as f1:
404
+ for line in lines:
405
+ save_line = line.strip('\n').strip('.')
406
+ f1.write(f'{save_line}\n')
407
+
408
+ test_df = pd.read_csv(test_save_path, header = None)
409
+ else:
410
+ test_df = pd.read_csv(test_path, header = info['header'])
411
+
412
+ if has_val: # currently you cannot have a val path without a test path
413
+ val_path = info['val_path']
414
+ val_df = pd.read_csv(val_path, header = info['header'])
415
+
416
+ train_df = data_df
417
+
418
+ if "dcr" in name and "diabetes" not in name: # create 50/50 splits for dcr datasets; no need for this for diabetes dataset as it's done in preprocessing
419
+ complete_df = pd.concat([train_df, test_df, val_df], axis = 0, ignore_index=True)
420
+ num_data = complete_df.shape[0]
421
+ num_train = int(num_data*0.5)
422
+ num_test = num_data - num_train
423
+ complete_df.rename(columns = idx_name_mapping, inplace=True)
424
+ train_df, test_df, seed = train_val_test_split(complete_df, cat_columns, num_train, num_test)
425
+
426
+ else:
427
+ # Train/ Test Split, 90% Training (50% for dcr eval exclusively), 10% Testing (Validation set will be selected from Training set)
428
+ if "dcr" in name:
429
+ num_train = int(num_data*0.5)
430
+ else:
431
+ num_train = int(num_data*0.9)
432
+ num_test = num_data - num_train
433
+
434
+ train_df, test_df, seed = train_val_test_split(data_df, cat_columns, num_train, num_test)
435
+
436
+ complete_df = pd.concat([train_df, test_df, val_df], axis = 0)
437
+ name_idx_mapping = {val: key for key, val in idx_name_mapping.items()}
438
+ int_columns = []
439
+ int_col_idx = []
440
+ int_col_idx_wrt_num = []
441
+ for i, col_idx in enumerate(num_col_idx):
442
+ col = column_names[col_idx]
443
+ col_data = complete_df.iloc[:,col_idx]
444
+ is_int = (col_data%1 == 0).all()
445
+ if is_int:
446
+ int_columns.append(col)
447
+ int_col_idx.append(name_idx_mapping[col])
448
+ int_col_idx_wrt_num.append(i)
449
+ info['int_col_idx'] = int_col_idx
450
+ info['int_columns'] = int_columns
451
+ info['int_col_idx_wrt_num'] = int_col_idx_wrt_num
452
+
453
+ train_df.columns = range(len(train_df.columns))
454
+ test_df.columns = range(len(test_df.columns))
455
+ val_df.columns = range(len(val_df.columns))
456
+
457
+ print(name, train_df.shape, val_df.shape, test_df.shape, data_df.shape)
458
+
459
+ col_info = {}
460
+
461
+ for col_idx in num_col_idx:
462
+ col_info[col_idx] = {}
463
+ col_info['type'] = 'numerical'
464
+ col_info['max'] = float(train_df[col_idx].max())
465
+ col_info['min'] = float(train_df[col_idx].min())
466
+
467
+ for col_idx in cat_col_idx:
468
+ col_info[col_idx] = {}
469
+ col_info['type'] = 'categorical'
470
+ col_info['categorizes'] = list(set(train_df[col_idx]))
471
+
472
+ for col_idx in target_col_idx:
473
+ if info['task_type'] == 'regression':
474
+ col_info[col_idx] = {}
475
+ col_info['type'] = 'numerical'
476
+ col_info['max'] = float(train_df[col_idx].max())
477
+ col_info['min'] = float(train_df[col_idx].min())
478
+ else:
479
+ col_info[col_idx] = {}
480
+ col_info['type'] = 'categorical'
481
+ col_info['categorizes'] = list(set(train_df[col_idx]))
482
+
483
+ info['column_info'] = col_info
484
+
485
+ train_df.rename(columns = idx_name_mapping, inplace=True)
486
+ test_df.rename(columns = idx_name_mapping, inplace=True)
487
+ val_df.rename(columns = idx_name_mapping, inplace=True)
488
+
489
+ for col in num_columns:
490
+ if (train_df[col] == ' ?').sum() > 0:
491
+ print(col)
492
+ import pdb; pdb.set_trace()
493
+ if (train_df[col] == '?').sum() > 0:
494
+ print(col)
495
+ import pdb; pdb.set_trace()
496
+ train_df.loc[train_df[col] == '?', col] = np.nan
497
+ for col in cat_columns:
498
+ train_df.loc[train_df[col] == '?', col] = 'nan'
499
+ for col in num_columns:
500
+ if (test_df[col] == ' ?').sum() > 0:
501
+ print(col)
502
+ import pdb; pdb.set_trace()
503
+ if (test_df[col] == '?').sum() > 0:
504
+ print(col)
505
+ import pdb; pdb.set_trace()
506
+ test_df.loc[test_df[col] == '?', col] = np.nan
507
+ for col in cat_columns:
508
+ test_df.loc[test_df[col] == '?', col] = 'nan'
509
+ for col in num_columns:
510
+ val_df.loc[val_df[col] == '?', col] = np.nan
511
+ for col in cat_columns:
512
+ val_df.loc[val_df[col] == '?', col] = 'nan'
513
+
514
+ if train_df.isna().any().any():
515
+ print("Training data contains nan in the numerical cols")
516
+ import pdb; pdb.set_trace()
517
+
518
+
519
+
520
+ X_num_train = train_df[num_columns].to_numpy().astype(np.float32)
521
+ X_cat_train = train_df[cat_columns].to_numpy()
522
+ y_train = train_df[target_columns].to_numpy()
523
+
524
+
525
+ X_num_test = test_df[num_columns].to_numpy().astype(np.float32)
526
+ X_cat_test = test_df[cat_columns].to_numpy()
527
+ y_test = test_df[target_columns].to_numpy()
528
+
529
+ X_num_val = val_df[num_columns].to_numpy().astype(np.float32)
530
+ X_cat_val = val_df[cat_columns].to_numpy()
531
+ y_val = val_df[target_columns].to_numpy()
532
+
533
+ save_dir = f'data/{name}'
534
+ np.save(f'{save_dir}/X_num_train.npy', X_num_train)
535
+ np.save(f'{save_dir}/X_cat_train.npy', X_cat_train)
536
+ np.save(f'{save_dir}/y_train.npy', y_train)
537
+
538
+ np.save(f'{save_dir}/X_num_test.npy', X_num_test)
539
+ np.save(f'{save_dir}/X_cat_test.npy', X_cat_test)
540
+ np.save(f'{save_dir}/y_test.npy', y_test)
541
+
542
+ if has_val:
543
+ np.save(f'{save_dir}/X_num_val.npy', X_num_val)
544
+ np.save(f'{save_dir}/X_cat_val.npy', X_cat_val)
545
+ np.save(f'{save_dir}/y_val.npy', y_val)
546
+
547
+ train_df[num_columns] = train_df[num_columns].astype(np.float32)
548
+ test_df[num_columns] = test_df[num_columns].astype(np.float32)
549
+ val_df[num_columns] = val_df[num_columns].astype(np.float32)
550
+
551
+
552
+ train_df.to_csv(f'{save_dir}/train.csv', index = False)
553
+ test_df.to_csv(f'{save_dir}/test.csv', index = False)
554
+ if has_val:
555
+ val_df.to_csv(f'{save_dir}/val.csv', index = False)
556
+
557
+ if not os.path.exists(f'synthetic/{name}'):
558
+ os.makedirs(f'synthetic/{name}')
559
+
560
+ train_df.to_csv(f'synthetic/{name}/real.csv', index = False)
561
+ test_df.to_csv(f'synthetic/{name}/test.csv', index = False)
562
+
563
+ if has_val:
564
+ val_df.to_csv(f'synthetic/{name}/val.csv', index = False)
565
+
566
+ print('Numerical', X_num_train.shape)
567
+ print('Categorical', X_cat_train.shape)
568
+
569
+ info['column_names'] = column_names
570
+ info['train_num'] = train_df.shape[0]
571
+ info['test_num'] = test_df.shape[0]
572
+ info['val_num'] = val_df.shape[0]
573
+
574
+ info['idx_mapping'] = idx_mapping
575
+ info['inverse_idx_mapping'] = inverse_idx_mapping
576
+ info['idx_name_mapping'] = idx_name_mapping
577
+
578
+ metadata = {'columns': {}}
579
+ task_type = info['task_type']
580
+ num_col_idx = info['num_col_idx']
581
+ cat_col_idx = info['cat_col_idx']
582
+ target_col_idx = info['target_col_idx']
583
+
584
+ for i in num_col_idx:
585
+ metadata['columns'][i] = {}
586
+ metadata['columns'][i]['sdtype'] = 'numerical'
587
+ metadata['columns'][i]['computer_representation'] = 'Float'
588
+
589
+ for i in cat_col_idx:
590
+ metadata['columns'][i] = {}
591
+ metadata['columns'][i]['sdtype'] = 'categorical'
592
+
593
+
594
+ if task_type == 'regression':
595
+
596
+ for i in target_col_idx:
597
+ metadata['columns'][i] = {}
598
+ metadata['columns'][i]['sdtype'] = 'numerical'
599
+ metadata['columns'][i]['computer_representation'] = 'Float'
600
+
601
+ else:
602
+ for i in target_col_idx:
603
+ metadata['columns'][i] = {}
604
+ metadata['columns'][i]['sdtype'] = 'categorical'
605
+
606
+ info['metadata'] = metadata
607
+
608
+ with open(f'{save_dir}/info.json', 'w') as file:
609
+ json.dump(info, file, indent=4)
610
+
611
+ print(f'Processing and Saving {name} Successfully!')
612
+
613
+ print(name)
614
+ print('Total', info['train_num'] + info['test_num'])
615
+ print('Train', info['train_num'])
616
+ print('Val', info['val_num'])
617
+ print('Test', info['test_num'])
618
+ if info['task_type'] == 'regression':
619
+ num = len(info['num_col_idx'] + info['target_col_idx'])
620
+ cat = len(info['cat_col_idx'])
621
+ else:
622
+ cat = len(info['cat_col_idx'] + info['target_col_idx'])
623
+ num = len(info['num_col_idx'])
624
+ print('Num', num)
625
+ print('Int', len(info['int_col_idx']))
626
+ print('Cat', cat)
627
+
628
+
629
+ if __name__ == "__main__":
630
+
631
+ if args.dataname:
632
+ process_data(args.dataname)
633
+ else:
634
+ for name in [
635
+ 'adult', 'default', 'shoppers', 'magic', 'beijing', 'news', 'news_nocat', 'diabetes',
636
+ 'adult_dcr',
637
+ 'default_dcr',
638
+ 'shoppers_dcr',
639
+ 'beijing_dcr',
640
+ 'news_dcr',
641
+ 'diabetes_dcr'
642
+ ]:
643
+ process_data(name)
644
+
645
+
646
+
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from icecream import install
3
+
4
+ torch.set_num_threads(1)
5
+ install()
6
+
7
+ from . import env # noqa
8
+ from .data import * # noqa
9
+ from .env import * # noqa
10
+ from .metrics import * # noqa
11
+ from .util import * # noqa
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/data.py ADDED
@@ -0,0 +1,780 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ from collections import Counter
3
+ from copy import deepcopy
4
+ from dataclasses import astuple, dataclass, replace
5
+ from importlib.resources import path
6
+ from pathlib import Path
7
+ from typing import Any, Literal, Optional, Union, cast, Tuple, Dict, List
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+ from sklearn.model_selection import train_test_split
12
+ from sklearn.pipeline import make_pipeline
13
+ import sklearn.preprocessing
14
+ import torch
15
+ import os
16
+ from category_encoders import LeaveOneOutEncoder
17
+ from sklearn.impute import SimpleImputer
18
+ from sklearn.preprocessing import StandardScaler
19
+ from scipy.spatial.distance import cdist
20
+
21
+ from . import env, util
22
+ from .metrics import calculate_metrics as calculate_metrics_
23
+ from .util import TaskType, load_json
24
+
25
+ ArrayDict = Dict[str, np.ndarray]
26
+ TensorDict = Dict[str, torch.Tensor]
27
+
28
+
29
+ CAT_MISSING_VALUE = 'nan'
30
+ CAT_RARE_VALUE = '__rare__'
31
+ Normalization = Literal['standard', 'quantile', 'minmax']
32
+ NumNanPolicy = Literal['drop-rows', 'mean']
33
+ CatNanPolicy = Literal['most_frequent']
34
+ CatEncoding = Literal['one-hot', 'counter']
35
+ YPolicy = Literal['default']
36
+ DEQUANT_DIST = Literal['uniform', 'beta', 'round', 'none']
37
+
38
+
39
+ class StandardScaler1d(StandardScaler):
40
+ def partial_fit(self, X, *args, **kwargs):
41
+ assert X.ndim == 1
42
+ return super().partial_fit(X[:, None], *args, **kwargs)
43
+
44
+ def transform(self, X, *args, **kwargs):
45
+ assert X.ndim == 1
46
+ return super().transform(X[:, None], *args, **kwargs).squeeze(1)
47
+
48
+ def inverse_transform(self, X, *args, **kwargs):
49
+ assert X.ndim == 1
50
+ return super().inverse_transform(X[:, None], *args, **kwargs).squeeze(1)
51
+
52
+
53
+ def get_category_sizes(X: Union[torch.Tensor, np.ndarray]) -> List[int]:
54
+ XT = X.T.cpu().tolist() if isinstance(X, torch.Tensor) else X.T.tolist()
55
+ return [len(set(x)) for x in XT]
56
+
57
+
58
+ @dataclass(frozen=False)
59
+ class Dataset:
60
+ X_num: Optional[ArrayDict]
61
+ X_cat: Optional[ArrayDict]
62
+ y: ArrayDict
63
+ int_col_idx_wrt_num: list
64
+ y_info: Dict[str, Any]
65
+ task_type: TaskType
66
+ n_classes: Optional[int]
67
+
68
+ @classmethod
69
+ def from_dir(cls, dir_: Union[Path, str]) -> 'Dataset':
70
+ dir_ = Path(dir_)
71
+ splits = [k for k in ['train', 'test'] if dir_.joinpath(f'y_{k}.npy').exists()]
72
+
73
+ def load(item) -> ArrayDict:
74
+ return {
75
+ x: cast(np.ndarray, np.load(dir_ / f'{item}_{x}.npy', allow_pickle=True)) # type: ignore[code]
76
+ for x in splits
77
+ }
78
+
79
+ if Path(dir_ / 'info.json').exists():
80
+ info = util.load_json(dir_ / 'info.json')
81
+ else:
82
+ info = None
83
+ return Dataset(
84
+ load('X_num') if dir_.joinpath('X_num_train.npy').exists() else None,
85
+ load('X_cat') if dir_.joinpath('X_cat_train.npy').exists() else None,
86
+ load('y'),
87
+ {},
88
+ TaskType(info['task_type']),
89
+ info.get('n_classes'),
90
+ )
91
+
92
+ @property
93
+ def is_binclass(self) -> bool:
94
+ return self.task_type == TaskType.BINCLASS
95
+
96
+ @property
97
+ def is_multiclass(self) -> bool:
98
+ return self.task_type == TaskType.MULTICLASS
99
+
100
+ @property
101
+ def is_regression(self) -> bool:
102
+ return self.task_type == TaskType.REGRESSION
103
+
104
+ @property
105
+ def n_num_features(self) -> int:
106
+ return 0 if self.X_num is None else self.X_num['train'].shape[1]
107
+
108
+ @property
109
+ def n_cat_features(self) -> int:
110
+ return 0 if self.X_cat is None else self.X_cat['train'].shape[1]
111
+
112
+ @property
113
+ def n_features(self) -> int:
114
+ return self.n_num_features + self.n_cat_features
115
+
116
+ def size(self, part: Optional[str]) -> int:
117
+ return sum(map(len, self.y.values())) if part is None else len(self.y[part])
118
+
119
+ @property
120
+ def nn_output_dim(self) -> int:
121
+ if self.is_multiclass:
122
+ assert self.n_classes is not None
123
+ return self.n_classes
124
+ else:
125
+ return 1
126
+
127
+ def get_category_sizes(self, part: str) -> List[int]:
128
+ return [] if self.X_cat is None else get_category_sizes(self.X_cat[part])
129
+
130
+ def calculate_metrics(
131
+ self,
132
+ predictions: Dict[str, np.ndarray],
133
+ prediction_type: Optional[str],
134
+ ) -> Dict[str, Any]:
135
+ metrics = {
136
+ x: calculate_metrics_(
137
+ self.y[x], predictions[x], self.task_type, prediction_type, self.y_info
138
+ )
139
+ for x in predictions
140
+ }
141
+ if self.task_type == TaskType.REGRESSION:
142
+ score_key = 'rmse'
143
+ score_sign = -1
144
+ else:
145
+ score_key = 'accuracy'
146
+ score_sign = 1
147
+ for part_metrics in metrics.values():
148
+ part_metrics['score'] = score_sign * part_metrics[score_key]
149
+ return metrics
150
+
151
+ def change_val(dataset: Dataset, val_size: float = 0.2):
152
+ # should be done before transformations
153
+
154
+ y = np.concatenate([dataset.y['train'], dataset.y['val']], axis=0)
155
+
156
+ ixs = np.arange(y.shape[0])
157
+ if dataset.is_regression:
158
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
159
+ else:
160
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
161
+
162
+ dataset.y['train'] = y[train_ixs]
163
+ dataset.y['val'] = y[val_ixs]
164
+
165
+ if dataset.X_num is not None:
166
+ X_num = np.concatenate([dataset.X_num['train'], dataset.X_num['val']], axis=0)
167
+ dataset.X_num['train'] = X_num[train_ixs]
168
+ dataset.X_num['val'] = X_num[val_ixs]
169
+
170
+ if dataset.X_cat is not None:
171
+ X_cat = np.concatenate([dataset.X_cat['train'], dataset.X_cat['val']], axis=0)
172
+ dataset.X_cat['train'] = X_cat[train_ixs]
173
+ dataset.X_cat['val'] = X_cat[val_ixs]
174
+
175
+ return dataset
176
+
177
+ def num_process_nans(dataset: Dataset, policy: Optional[NumNanPolicy]) -> Dataset:
178
+
179
+ assert dataset.X_num is not None
180
+ nan_masks = {k: np.isnan(v) for k, v in dataset.X_num.items()}
181
+ if not any(x.any() for x in nan_masks.values()): # type: ignore[code]
182
+ # assert policy is None
183
+ print('No NaNs in numerical features, skipping')
184
+ return dataset
185
+
186
+ assert policy is not None
187
+ if policy == 'drop-rows':
188
+ valid_masks = {k: ~v.any(1) for k, v in nan_masks.items()}
189
+ assert valid_masks[
190
+ 'test'
191
+ ].all(), 'Cannot drop test rows, since this will affect the final metrics.'
192
+ new_data = {}
193
+ for data_name in ['X_num', 'X_cat', 'y']:
194
+ data_dict = getattr(dataset, data_name)
195
+ if data_dict is not None:
196
+ new_data[data_name] = {
197
+ k: v[valid_masks[k]] for k, v in data_dict.items()
198
+ }
199
+ dataset = replace(dataset, **new_data)
200
+ elif policy == 'mean':
201
+ new_values = np.nanmean(dataset.X_num['train'], axis=0)
202
+ X_num = deepcopy(dataset.X_num)
203
+ for k, v in X_num.items():
204
+ num_nan_indices = np.where(nan_masks[k])
205
+ v[num_nan_indices] = np.take(new_values, num_nan_indices[1])
206
+ dataset = replace(dataset, X_num=X_num)
207
+ else:
208
+ assert util.raise_unknown('policy', policy)
209
+ return dataset
210
+
211
+
212
+ # Inspired by: https://github.com/yandex-research/rtdl/blob/a4c93a32b334ef55d2a0559a4407c8306ffeeaee/lib/data.py#L20
213
+ def normalize(
214
+ X: ArrayDict, normalization: Normalization, seed: Optional[int], return_normalizer : bool = False
215
+ ) -> ArrayDict:
216
+ X_train = X['train']
217
+ if normalization == 'standard':
218
+ normalizer = sklearn.preprocessing.StandardScaler()
219
+ elif normalization == 'minmax':
220
+ normalizer = sklearn.preprocessing.MinMaxScaler()
221
+ elif normalization == 'quantile':
222
+ normalizer = sklearn.preprocessing.QuantileTransformer(
223
+ output_distribution='normal',
224
+ n_quantiles=max(min(X['train'].shape[0] // 30, 1000), 10),
225
+ subsample=int(1e9),
226
+ random_state=seed,
227
+ )
228
+ # noise = 1e-3
229
+ # if noise > 0:
230
+ # assert seed is not None
231
+ # stds = np.std(X_train, axis=0, keepdims=True)
232
+ # noise_std = noise / np.maximum(stds, noise) # type: ignore[code]
233
+ # X_train = X_train + noise_std * np.random.default_rng(seed).standard_normal(
234
+ # X_train.shape
235
+ # )
236
+ else:
237
+ util.raise_unknown('normalization', normalization)
238
+
239
+ normalizer.fit(X_train)
240
+ if return_normalizer:
241
+ return {k: normalizer.transform(v) for k, v in X.items()}, normalizer
242
+ return {k: normalizer.transform(v) for k, v in X.items()}
243
+
244
+ class dequantizer:
245
+ def __init__(
246
+ self,
247
+ dequant_dist: DEQUANT_DIST,
248
+ int_col_idx_wrt_num: list,
249
+ int_dequant_factor: float,
250
+ # return_dequantizer: bool = False
251
+ ):
252
+ self.dequant_dist = dequant_dist
253
+ self.int_col_idx_wrt_num = int_col_idx_wrt_num
254
+ self.int_dequant_factor = int_dequant_factor
255
+ def transform(self, X):
256
+ X_int = X[:, self.int_col_idx_wrt_num]
257
+ if self.dequant_dist == 'uniform':
258
+ X[:, self.int_col_idx_wrt_num] = X_int+ np.random.uniform(size=X_int.shape) * self.int_dequant_factor
259
+ elif self.dequant_dist == 'beta':
260
+ X[:, self.int_col_idx_wrt_num] = X_int + np.random.beta(self.int_dequant_factor, self.int_dequant_factor, size=X_int.shape) - 0.5
261
+ elif self.dequant_dist in ['round', 'none']:
262
+ pass
263
+ return X
264
+ def inverse_transform(self, X):
265
+ X_int = X[:, self.int_col_idx_wrt_num]
266
+ if self.dequant_dist == 'uniform':
267
+ X[:, self.int_col_idx_wrt_num] = np.floor(X_int)
268
+ elif self.dequant_dist == 'beta':
269
+ X[:, self.int_col_idx_wrt_num] = np.rint(X_int)
270
+ elif self.dequant_dist == 'round':
271
+ X[:, self.int_col_idx_wrt_num] = np.rint(X_int)
272
+ elif self.dequant_dist == 'none':
273
+ pass
274
+ return X
275
+
276
+
277
+ # if return_dequantizer:
278
+ # return {k: transform(v) for k, v in X.items()}, inverse_transform
279
+ # return {k: transform(v) for k, v in X.items()}
280
+
281
+ def cat_process_nans(X: ArrayDict, policy: Optional[CatNanPolicy]) -> ArrayDict:
282
+ assert X is not None
283
+ nan_masks = {k: v == CAT_MISSING_VALUE for k, v in X.items()}
284
+ if any(x.any() for x in nan_masks.values()): # type: ignore[code]
285
+ if policy is None:
286
+ X_new = X
287
+ elif policy == 'most_frequent':
288
+ imputer = SimpleImputer(missing_values=CAT_MISSING_VALUE, strategy=policy) # type: ignore[code]
289
+ imputer.fit(X['train'])
290
+ X_new = {k: cast(np.ndarray, imputer.transform(v)) for k, v in X.items()}
291
+ else:
292
+ util.raise_unknown('categorical NaN policy', policy)
293
+ else:
294
+ assert policy is None
295
+ X_new = X
296
+ return X_new
297
+
298
+
299
+ def cat_drop_rare(X: ArrayDict, min_frequency: float) -> ArrayDict:
300
+ assert 0.0 < min_frequency < 1.0
301
+ min_count = round(len(X['train']) * min_frequency)
302
+ X_new = {x: [] for x in X}
303
+ for column_idx in range(X['train'].shape[1]):
304
+ counter = Counter(X['train'][:, column_idx].tolist())
305
+ popular_categories = {k for k, v in counter.items() if v >= min_count}
306
+ for part in X_new:
307
+ X_new[part].append(
308
+ [
309
+ (x if x in popular_categories else CAT_RARE_VALUE)
310
+ for x in X[part][:, column_idx].tolist()
311
+ ]
312
+ )
313
+ return {k: np.array(v).T for k, v in X_new.items()}
314
+
315
+
316
+ def cat_encode(
317
+ X: ArrayDict,
318
+ encoding: Optional[CatEncoding],
319
+ y_train: Optional[np.ndarray],
320
+ seed: Optional[int],
321
+ return_encoder : bool = False
322
+ ) -> Tuple[ArrayDict, bool, Optional[Any]]: # (X, is_converted_to_numerical)
323
+ if encoding != 'counter':
324
+ y_train = None
325
+
326
+ # Step 1. Map strings to 0-based ranges
327
+
328
+ if encoding is None:
329
+ unknown_value = np.iinfo('int64').max - 3
330
+ oe = sklearn.preprocessing.OrdinalEncoder(
331
+ handle_unknown='use_encoded_value', # type: ignore[code]
332
+ unknown_value=unknown_value, # type: ignore[code]
333
+ dtype='int64', # type: ignore[code]
334
+ ).fit(X['train'])
335
+ encoder = make_pipeline(oe)
336
+ encoder.fit(X['train'])
337
+ X = {k: encoder.transform(v) for k, v in X.items()}
338
+ max_values = X['train'].max(axis=0)
339
+ for part in X.keys():
340
+ if part == 'train': continue
341
+ for column_idx in range(X[part].shape[1]):
342
+ X[part][X[part][:, column_idx] == unknown_value, column_idx] = (
343
+ max_values[column_idx] + 1
344
+ )
345
+ if return_encoder:
346
+ return (X, False, encoder)
347
+ return (X, False)
348
+
349
+ # Step 2. Encode.
350
+
351
+ elif encoding == 'one-hot':
352
+ ohe = sklearn.preprocessing.OneHotEncoder(
353
+ handle_unknown='ignore', sparse_output=False, dtype=np.float32 # type: ignore[code]
354
+ )
355
+ encoder = make_pipeline(ohe)
356
+
357
+ # encoder.steps.append(('ohe', ohe))
358
+ encoder.fit(X['train'])
359
+ X = {k: encoder.transform(v) for k, v in X.items()}
360
+
361
+ elif encoding == 'counter':
362
+ assert y_train is not None
363
+ assert seed is not None
364
+ loe = LeaveOneOutEncoder(sigma=0.1, random_state=seed, return_df=False)
365
+ encoder.steps.append(('loe', loe))
366
+ encoder.fit(X['train'], y_train)
367
+ X = {k: encoder.transform(v).astype('float32') for k, v in X.items()} # type: ignore[code]
368
+ if not isinstance(X['train'], pd.DataFrame):
369
+ X = {k: v.values for k, v in X.items()} # type: ignore[code]
370
+ else:
371
+ util.raise_unknown('encoding', encoding)
372
+
373
+ if return_encoder:
374
+ return X, True, encoder # type: ignore[code]
375
+ return (X, True)
376
+
377
+
378
+ def build_target(
379
+ y: ArrayDict, policy: Optional[YPolicy], task_type: TaskType
380
+ ) -> Tuple[ArrayDict, Dict[str, Any]]:
381
+ info: Dict[str, Any] = {'policy': policy}
382
+ if policy is None:
383
+ pass
384
+ elif policy == 'default':
385
+ if task_type == TaskType.REGRESSION:
386
+ mean, std = float(y['train'].mean()), float(y['train'].std())
387
+ y = {k: (v - mean) / std for k, v in y.items()}
388
+ info['mean'] = mean
389
+ info['std'] = std
390
+ else:
391
+ util.raise_unknown('policy', policy)
392
+ return y, info
393
+
394
+
395
+ @dataclass(frozen=True)
396
+ class Transformations:
397
+ seed: int = 0
398
+ normalization: Optional[Normalization] = None
399
+ num_nan_policy: Optional[NumNanPolicy] = None
400
+ cat_nan_policy: Optional[CatNanPolicy] = None
401
+ cat_min_frequency: Optional[float] = None
402
+ cat_encoding: Optional[CatEncoding] = None
403
+ y_policy: Optional[YPolicy] = 'default'
404
+ dequant_dist: Optional[DEQUANT_DIST] = None
405
+ int_dequant_factor: Optional[float] = 0.0
406
+
407
+
408
+ def transform_dataset(
409
+ dataset: Dataset,
410
+ transformations: Transformations,
411
+ cache_dir: Optional[Path],
412
+ return_transforms: bool = False
413
+ ) -> Dataset:
414
+ # WARNING: the order of transformations matters. Moreover, the current
415
+ # implementation is not ideal in that sense.
416
+ if cache_dir is not None:
417
+ transformations_md5 = hashlib.md5(
418
+ str(transformations).encode('utf-8')
419
+ ).hexdigest()
420
+ transformations_str = '__'.join(map(str, astuple(transformations)))
421
+ cache_path = (
422
+ cache_dir / f'cache__{transformations_str}__{transformations_md5}.pickle'
423
+ )
424
+ if cache_path.exists():
425
+ cache_transformations, value = util.load_pickle(cache_path)
426
+ if transformations == cache_transformations:
427
+ print(
428
+ f"Using cached features: {cache_dir.name + '/' + cache_path.name}"
429
+ )
430
+ return value
431
+ else:
432
+ raise RuntimeError(f'Hash collision for {cache_path}')
433
+ else:
434
+ cache_path = None
435
+
436
+ if dataset.X_num is not None:
437
+ dataset = num_process_nans(dataset, transformations.num_nan_policy)
438
+
439
+ num_transform = None
440
+ int_transform = None
441
+ cat_transform = None
442
+ X_num = dataset.X_num
443
+
444
+ int_col_idx_wrt_num = dataset.int_col_idx_wrt_num
445
+ if X_num is not None and int_col_idx_wrt_num and transformations.dequant_dist is not None:
446
+ int_transform = dequantizer(
447
+ transformations.dequant_dist,
448
+ int_col_idx_wrt_num,
449
+ transformations.int_dequant_factor,
450
+ )
451
+ X_num = {k: int_transform.transform(v) for k, v in X_num.items()}
452
+
453
+ if X_num is not None and transformations.normalization is not None:
454
+ has_num = all([x.shape[1]>0 for x in dataset.X_num.values()])
455
+ if has_num:
456
+ X_num, num_transform = normalize(
457
+ X_num,
458
+ transformations.normalization,
459
+ transformations.seed,
460
+ return_normalizer=True
461
+ )
462
+ num_transform = num_transform
463
+
464
+ if dataset.X_cat is None:
465
+ assert transformations.cat_nan_policy is None
466
+ assert transformations.cat_min_frequency is None
467
+ # assert transformations.cat_encoding is None
468
+ X_cat = None
469
+ else:
470
+ has_cat = all([x.shape[1]>0 for x in dataset.X_cat.values()])
471
+ if not has_cat:
472
+ assert transformations.cat_nan_policy is None
473
+ assert transformations.cat_min_frequency is None
474
+ X_cat = dataset.X_cat
475
+ for split in X_cat.keys(): # a patch to make sure that the empty array is transformed into int dtype
476
+ X_cat[split] = X_cat[split].astype(np.int64)
477
+ else:
478
+ X_cat = cat_process_nans(dataset.X_cat, transformations.cat_nan_policy)
479
+
480
+ if transformations.cat_min_frequency is not None:
481
+ X_cat = cat_drop_rare(X_cat, transformations.cat_min_frequency)
482
+ X_cat, is_num, cat_transform = cat_encode(
483
+ X_cat,
484
+ transformations.cat_encoding,
485
+ dataset.y['train'],
486
+ transformations.seed,
487
+ return_encoder=True
488
+ )
489
+
490
+ if is_num:
491
+ X_num = (
492
+ X_cat
493
+ if X_num is None
494
+ else {x: np.hstack([X_num[x], X_cat[x]]) for x in X_num}
495
+ )
496
+ X_cat = None
497
+
498
+
499
+ y, y_info = build_target(dataset.y, transformations.y_policy, dataset.task_type)
500
+
501
+ dataset = replace(dataset, X_num=X_num, X_cat=X_cat, y=y, y_info=y_info)
502
+ dataset.num_transform = num_transform
503
+ dataset.int_transform = int_transform
504
+ dataset.cat_transform = cat_transform
505
+
506
+ if cache_path is not None:
507
+ util.dump_pickle((transformations, dataset), cache_path)
508
+ # if return_transforms:
509
+ # return dataset, num_transform, cat_transform
510
+ return dataset
511
+
512
+
513
+ def build_dataset(
514
+ path: Union[str, Path],
515
+ transformations: Transformations,
516
+ cache: bool
517
+ ) -> Dataset:
518
+ path = Path(path)
519
+ dataset = Dataset.from_dir(path)
520
+ return transform_dataset(dataset, transformations, path if cache else None)
521
+
522
+
523
+ def prepare_tensors(
524
+ dataset: Dataset, device: Union[str, torch.device]
525
+ ) -> Tuple[Optional[TensorDict], Optional[TensorDict], TensorDict]:
526
+ X_num, X_cat, Y = (
527
+ None if x is None else {k: torch.as_tensor(v) for k, v in x.items()}
528
+ for x in [dataset.X_num, dataset.X_cat, dataset.y]
529
+ )
530
+ if device.type != 'cpu':
531
+ X_num, X_cat, Y = (
532
+ None if x is None else {k: v.to(device) for k, v in x.items()}
533
+ for x in [X_num, X_cat, Y]
534
+ )
535
+ assert X_num is not None
536
+ assert Y is not None
537
+ if not dataset.is_multiclass:
538
+ Y = {k: v.float() for k, v in Y.items()}
539
+ return X_num, X_cat, Y
540
+
541
+ ###############
542
+ ## DataLoader##
543
+ ###############
544
+
545
+ class TabDataset(torch.utils.data.Dataset):
546
+ def __init__(
547
+ self, dataset : Dataset, split : Literal['train', 'val', 'test']
548
+ ):
549
+ super().__init__()
550
+
551
+ self.X_num = torch.from_numpy(dataset.X_num[split]) if dataset.X_num is not None else None
552
+ self.X_cat = torch.from_numpy(dataset.X_cat[split]) if dataset.X_cat is not None else None
553
+ self.y = torch.from_numpy(dataset.y[split])
554
+
555
+ assert self.y is not None
556
+ assert self.X_num is not None or self.X_cat is not None
557
+
558
+ def __len__(self):
559
+ return len(self.y)
560
+
561
+ def __getitem__(self, idx):
562
+ out_dict = {
563
+ 'y': self.y[idx].long() if self.y is not None else None,
564
+ }
565
+
566
+ x = np.empty((0,))
567
+ if self.X_num is not None:
568
+ x = self.X_num[idx]
569
+ if self.X_cat is not None:
570
+ x = torch.cat([x, self.X_cat[idx]], dim=0)
571
+ return x.float(), out_dict
572
+
573
+ def prepare_dataloader(
574
+ dataset : Dataset,
575
+ split : str,
576
+ batch_size: int,
577
+ ):
578
+
579
+ torch_dataset = TabDataset(dataset, split)
580
+ loader = torch.utils.data.DataLoader(
581
+ torch_dataset,
582
+ batch_size=batch_size,
583
+ shuffle=(split == 'train'),
584
+ num_workers=1,
585
+ )
586
+ while True:
587
+ yield from loader
588
+
589
+ def prepare_torch_dataloader(
590
+ dataset : Dataset,
591
+ split : str,
592
+ shuffle : bool,
593
+ batch_size: int,
594
+ ) -> torch.utils.data.DataLoader:
595
+
596
+ torch_dataset = TabDataset(dataset, split)
597
+ loader = torch.utils.data.DataLoader(torch_dataset, batch_size=batch_size, shuffle=shuffle, num_workers=1)
598
+
599
+ return loader
600
+
601
+ def dataset_from_csv(paths : Dict[str, str], cat_features, target, T):
602
+ assert 'train' in paths
603
+ y = {}
604
+ X_num = {}
605
+ X_cat = {} if len(cat_features) else None
606
+ for split in paths.keys():
607
+ df = pd.read_csv(paths[split])
608
+ y[split] = df[target].to_numpy().astype(float)
609
+ if X_cat is not None:
610
+ X_cat[split] = df[cat_features].to_numpy().astype(str)
611
+ X_num[split] = df.drop(cat_features + [target], axis=1).to_numpy().astype(float)
612
+
613
+ dataset = Dataset(X_num, X_cat, y, {}, None, len(np.unique(y['train'])))
614
+ return transform_dataset(dataset, T, None)
615
+
616
+ class FastTensorDataLoader:
617
+ """
618
+ A DataLoader-like object for a set of tensors that can be much faster than
619
+ TensorDataset + DataLoader because dataloader grabs individual indices of
620
+ the dataset and calls cat (slow).
621
+ Source: https://discuss.pytorch.org/t/dataloader-much-slower-than-manual-batching/27014/6
622
+ """
623
+ def __init__(self, *tensors, batch_size=32, shuffle=False):
624
+ """
625
+ Initialize a FastTensorDataLoader.
626
+ :param *tensors: tensors to store. Must have the same length @ dim 0.
627
+ :param batch_size: batch size to load.
628
+ :param shuffle: if True, shuffle the data *in-place* whenever an
629
+ iterator is created out of this object.
630
+ :returns: A FastTensorDataLoader.
631
+ """
632
+ assert all(t.shape[0] == tensors[0].shape[0] for t in tensors)
633
+ self.tensors = tensors
634
+
635
+ self.dataset_len = self.tensors[0].shape[0]
636
+ self.batch_size = batch_size
637
+ self.shuffle = shuffle
638
+
639
+ # Calculate # batches
640
+ n_batches, remainder = divmod(self.dataset_len, self.batch_size)
641
+ if remainder > 0:
642
+ n_batches += 1
643
+ self.n_batches = n_batches
644
+ def __iter__(self):
645
+ if self.shuffle:
646
+ r = torch.randperm(self.dataset_len)
647
+ self.tensors = [t[r] for t in self.tensors]
648
+ self.i = 0
649
+ return self
650
+
651
+ def __next__(self):
652
+ if self.i >= self.dataset_len:
653
+ raise StopIteration
654
+ batch = tuple(t[self.i:self.i+self.batch_size] for t in self.tensors)
655
+ self.i += self.batch_size
656
+ return batch
657
+
658
+ def __len__(self):
659
+ return self.n_batches
660
+
661
+ def prepare_fast_dataloader(
662
+ D : Dataset,
663
+ split : str,
664
+ batch_size: int
665
+ ):
666
+
667
+ X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
668
+ dataloader = FastTensorDataLoader(X, batch_size=batch_size, shuffle=(split=='train'))
669
+ while True:
670
+ yield from dataloader
671
+
672
+ def prepare_fast_torch_dataloader(
673
+ D : Dataset,
674
+ split : str,
675
+ batch_size: int
676
+ ):
677
+ if D.X_cat is not None:
678
+ X = torch.from_numpy(np.concatenate([D.X_num[split], D.X_cat[split]], axis=1)).float()
679
+ else:
680
+ X = torch.from_numpy(D.X_num[split]).float()
681
+ y = torch.from_numpy(D.y[split])
682
+ dataloader = FastTensorDataLoader(X, y, batch_size=batch_size, shuffle=(split=='train'))
683
+ return dataloader
684
+
685
+ def round_columns(X_real, X_synth, columns):
686
+ for col in columns:
687
+ uniq = np.unique(X_real[:,col])
688
+ dist = cdist(X_synth[:, col][:, np.newaxis].astype(float), uniq[:, np.newaxis].astype(float))
689
+ X_synth[:, col] = uniq[dist.argmin(axis=1)]
690
+ return X_synth
691
+
692
+ def concat_features(D : Dataset):
693
+ if D.X_num is None:
694
+ assert D.X_cat is not None
695
+ X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_cat.items()}
696
+ elif D.X_cat is None:
697
+ assert D.X_num is not None
698
+ X = {k: pd.DataFrame(v, columns=range(D.n_features)) for k, v in D.X_num.items()}
699
+ else:
700
+ X = {
701
+ part: pd.concat(
702
+ [
703
+ pd.DataFrame(D.X_num[part], columns=range(D.n_num_features)),
704
+ pd.DataFrame(
705
+ D.X_cat[part],
706
+ columns=range(D.n_num_features, D.n_features),
707
+ ),
708
+ ],
709
+ axis=1,
710
+ )
711
+ for part in D.y.keys()
712
+ }
713
+
714
+ return X
715
+
716
+ def concat_to_pd(X_num, X_cat, y):
717
+ if X_num is None:
718
+ return pd.concat([
719
+ pd.DataFrame(X_cat, columns=list(range(X_cat.shape[1]))),
720
+ pd.DataFrame(y, columns=['y'])
721
+ ], axis=1)
722
+ if X_cat is not None:
723
+ return pd.concat([
724
+ pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
725
+ pd.DataFrame(X_cat, columns=list(range(X_num.shape[1], X_num.shape[1] + X_cat.shape[1]))),
726
+ pd.DataFrame(y, columns=['y'])
727
+ ], axis=1)
728
+ return pd.concat([
729
+ pd.DataFrame(X_num, columns=list(range(X_num.shape[1]))),
730
+ pd.DataFrame(y, columns=['y'])
731
+ ], axis=1)
732
+
733
+ def read_pure_data(path, split='train'):
734
+ y = np.load(os.path.join(path, f'y_{split}.npy'), allow_pickle=True)
735
+ X_num = None
736
+ X_cat = None
737
+ if os.path.exists(os.path.join(path, f'X_num_{split}.npy')):
738
+ X_num = np.load(os.path.join(path, f'X_num_{split}.npy'), allow_pickle=True)
739
+ if os.path.exists(os.path.join(path, f'X_cat_{split}.npy')):
740
+ X_cat = np.load(os.path.join(path, f'X_cat_{split}.npy'), allow_pickle=True)
741
+
742
+ return X_num, X_cat, y
743
+
744
+ def read_changed_val(path, val_size=0.2):
745
+ path = Path(path)
746
+ X_num_train, X_cat_train, y_train = read_pure_data(path, 'train')
747
+ X_num_val, X_cat_val, y_val = read_pure_data(path, 'val')
748
+ is_regression = load_json(path / 'info.json')['task_type'] == 'regression'
749
+
750
+ y = np.concatenate([y_train, y_val], axis=0)
751
+
752
+ ixs = np.arange(y.shape[0])
753
+ if is_regression:
754
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777)
755
+ else:
756
+ train_ixs, val_ixs = train_test_split(ixs, test_size=val_size, random_state=777, stratify=y)
757
+ y_train = y[train_ixs]
758
+ y_val = y[val_ixs]
759
+
760
+ if X_num_train is not None:
761
+ X_num = np.concatenate([X_num_train, X_num_val], axis=0)
762
+ X_num_train = X_num[train_ixs]
763
+ X_num_val = X_num[val_ixs]
764
+
765
+ if X_cat_train is not None:
766
+ X_cat = np.concatenate([X_cat_train, X_cat_val], axis=0)
767
+ X_cat_train = X_cat[train_ixs]
768
+ X_cat_val = X_cat[val_ixs]
769
+
770
+ return X_num_train, X_cat_train, y_train, X_num_val, X_cat_val, y_val
771
+
772
+ #############
773
+
774
+ def load_dataset_info(dataset_dir_name: str) -> Dict[str, Any]:
775
+ path = Path("data/" + dataset_dir_name)
776
+ info = util.load_json(path / 'info.json')
777
+ info['size'] = info['train_size'] + info['val_size'] + info['test_size']
778
+ info['n_features'] = info['n_num_features'] + info['n_cat_features']
779
+ info['path'] = path
780
+ return info
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/env.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Have not used in TabDDPM project.
3
+ """
4
+
5
+ import datetime
6
+ import os
7
+ import shutil
8
+ import typing as ty
9
+ from pathlib import Path
10
+
11
+ PROJ = Path('tab-ddpm/').absolute().resolve()
12
+ EXP = PROJ / 'exp'
13
+ DATA = PROJ / 'data'
14
+
15
+
16
+ def get_path(path: ty.Union[str, Path]) -> Path:
17
+ if isinstance(path, str):
18
+ path = Path(path)
19
+ if not path.is_absolute():
20
+ path = PROJ / path
21
+ return path.resolve()
22
+
23
+
24
+ def get_relative_path(path: ty.Union[str, Path]) -> Path:
25
+ return get_path(path).relative_to(PROJ)
26
+
27
+
28
+ def duplicate_path(
29
+ src: ty.Union[str, Path], alternative_project_dir: ty.Union[str, Path]
30
+ ) -> None:
31
+ src = get_path(src)
32
+ alternative_project_dir = get_path(alternative_project_dir)
33
+ dst = alternative_project_dir / src.relative_to(PROJ)
34
+ dst.parent.mkdir(parents=True, exist_ok=True)
35
+ if dst.exists():
36
+ dst = dst.with_name(
37
+ dst.name + '_' + datetime.datetime.now().strftime('%Y%m%dT%H%M%S')
38
+ )
39
+ (shutil.copytree if src.is_dir() else shutil.copyfile)(src, dst)
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/metrics.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ from typing import Any, Optional, Tuple, Dict, Union, cast
3
+ from functools import partial
4
+
5
+ import numpy as np
6
+ import scipy.special
7
+ import sklearn.metrics as skm
8
+
9
+ from . import util
10
+ from .util import TaskType
11
+
12
+
13
+ class PredictionType(enum.Enum):
14
+ LOGITS = 'logits'
15
+ PROBS = 'probs'
16
+
17
+ class MetricsReport:
18
+ def __init__(self, report: dict, task_type: TaskType):
19
+ self._res = {k: {} for k in report.keys()}
20
+ if task_type in (TaskType.BINCLASS, TaskType.MULTICLASS):
21
+ self._metrics_names = ["acc", "f1"]
22
+ for k in report.keys():
23
+ self._res[k]["acc"] = report[k]["accuracy"]
24
+ self._res[k]["f1"] = report[k]["macro avg"]["f1-score"]
25
+ if task_type == TaskType.BINCLASS:
26
+ self._res[k]["roc_auc"] = report[k]["roc_auc"]
27
+ self._metrics_names.append("roc_auc")
28
+
29
+ elif task_type == TaskType.REGRESSION:
30
+ self._metrics_names = ["r2", "rmse"]
31
+ for k in report.keys():
32
+ self._res[k]["r2"] = report[k]["r2"]
33
+ self._res[k]["rmse"] = report[k]["rmse"]
34
+ else:
35
+ raise "Unknown TaskType!"
36
+
37
+ def get_splits_names(self) -> list[str]:
38
+ return self._res.keys()
39
+
40
+ def get_metrics_names(self) -> list[str]:
41
+ return self._metrics_names
42
+
43
+ def get_metric(self, split: str, metric: str) -> float:
44
+ return self._res[split][metric]
45
+
46
+ def get_val_score(self) -> float:
47
+ return self._res["val"]["r2"] if "r2" in self._res["val"] else self._res["val"]["f1"]
48
+
49
+ def get_test_score(self) -> float:
50
+ return self._res["test"]["r2"] if "r2" in self._res["test"] else self._res["test"]["f1"]
51
+
52
+ def print_metrics(self) -> None:
53
+ res = {
54
+ "val": {k: np.around(self._res["val"][k], 4) for k in self._res["val"]},
55
+ "test": {k: np.around(self._res["test"][k], 4) for k in self._res["test"]}
56
+ }
57
+
58
+ print("*"*100)
59
+ print("[val]")
60
+ print(res["val"])
61
+ print("[test]")
62
+ print(res["test"])
63
+
64
+ return res
65
+
66
+ class SeedsMetricsReport:
67
+ def __init__(self):
68
+ self._reports = []
69
+
70
+ def add_report(self, report: MetricsReport) -> None:
71
+ self._reports.append(report)
72
+
73
+ def get_mean_std(self) -> dict:
74
+ res = {k: {} for k in ["train", "val", "test"]}
75
+ for split in self._reports[0].get_splits_names():
76
+ for metric in self._reports[0].get_metrics_names():
77
+ res[split][metric] = [x.get_metric(split, metric) for x in self._reports]
78
+
79
+ agg_res = {k: {} for k in ["train", "val", "test"]}
80
+ for split in self._reports[0].get_splits_names():
81
+ for metric in self._reports[0].get_metrics_names():
82
+ for k, f in [("count", len), ("mean", np.mean), ("std", np.std)]:
83
+ agg_res[split][f"{metric}-{k}"] = f(res[split][metric])
84
+ self._res = res
85
+ self._agg_res = agg_res
86
+
87
+ return agg_res
88
+
89
+ def print_result(self) -> dict:
90
+ res = {split: {k: float(np.around(self._agg_res[split][k], 4)) for k in self._agg_res[split]} for split in ["val", "test"]}
91
+ print("="*100)
92
+ print("EVAL RESULTS:")
93
+ print("[val]")
94
+ print(res["val"])
95
+ print("[test]")
96
+ print(res["test"])
97
+ print("="*100)
98
+ return res
99
+
100
+ def calculate_rmse(
101
+ y_true: np.ndarray, y_pred: np.ndarray, std = None) -> float:
102
+ rmse = skm.mean_squared_error(y_true, y_pred) ** 0.5
103
+ if std is not None:
104
+ rmse *= std
105
+ return rmse
106
+
107
+
108
+ def _get_labels_and_probs(
109
+ y_pred: np.ndarray, task_type: TaskType, prediction_type: Optional[PredictionType]
110
+ ) -> Tuple[np.ndarray, Optional[np.ndarray]]:
111
+ assert task_type in (TaskType.BINCLASS, TaskType.MULTICLASS)
112
+
113
+ if prediction_type is None:
114
+ return y_pred, None
115
+
116
+ if prediction_type == PredictionType.LOGITS:
117
+ probs = (
118
+ scipy.special.expit(y_pred)
119
+ if task_type == TaskType.BINCLASS
120
+ else scipy.special.softmax(y_pred, axis=1)
121
+ )
122
+ elif prediction_type == PredictionType.PROBS:
123
+ probs = y_pred
124
+ else:
125
+ util.raise_unknown('prediction_type', prediction_type)
126
+
127
+ assert probs is not None
128
+ labels = np.round(probs) if task_type == TaskType.BINCLASS else probs.argmax(axis=1)
129
+ return labels.astype('int64'), probs
130
+
131
+
132
+ def calculate_metrics(
133
+ y_true: np.ndarray,
134
+ y_pred: np.ndarray,
135
+ task_type: Union[str, TaskType],
136
+ prediction_type: Optional[Union[str, PredictionType]],
137
+ y_info: Dict[str, Any],
138
+ ) -> Dict[str, Any]:
139
+ # Example: calculate_metrics(y_true, y_pred, 'binclass', 'logits', {})
140
+ task_type = TaskType(task_type)
141
+ if prediction_type is not None:
142
+ prediction_type = PredictionType(prediction_type)
143
+
144
+ if task_type == TaskType.REGRESSION:
145
+ assert prediction_type is None
146
+ assert 'std' in y_info
147
+ rmse = calculate_rmse(y_true, y_pred, y_info['std'])
148
+ r2 = skm.r2_score(y_true, y_pred)
149
+ result = {'rmse': rmse, 'r2': r2}
150
+ else:
151
+ labels, probs = _get_labels_and_probs(y_pred, task_type, prediction_type)
152
+ result = cast(
153
+ Dict[str, Any], skm.classification_report(y_true, labels, output_dict=True)
154
+ )
155
+ if task_type == TaskType.BINCLASS:
156
+ result['roc_auc'] = skm.roc_auc_score(y_true, probs)
157
+ return result
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/src/util.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import atexit
3
+ import enum
4
+ import json
5
+ import os
6
+ import pickle
7
+ import shutil
8
+ import sys
9
+ import time
10
+ import uuid
11
+ from copy import deepcopy
12
+ from dataclasses import asdict, fields, is_dataclass
13
+ from pathlib import Path
14
+ from pprint import pprint
15
+ from typing import Any, Callable, List, Dict, Type, Optional, Tuple, TypeVar, Union, cast, get_args, get_origin
16
+
17
+ import __main__
18
+ import numpy as np
19
+ import tomli
20
+ import tomli_w
21
+ import torch
22
+ import typing as ty
23
+
24
+ from . import env
25
+
26
+ RawConfig = Dict[str, Any]
27
+ Report = Dict[str, Any]
28
+ T = TypeVar('T')
29
+
30
+
31
+ class Part(enum.Enum):
32
+ TRAIN = 'train'
33
+ VAL = 'val'
34
+ TEST = 'test'
35
+
36
+ def __str__(self) -> str:
37
+ return self.value
38
+
39
+
40
+ class TaskType(enum.Enum):
41
+ BINCLASS = 'binclass'
42
+ MULTICLASS = 'multiclass'
43
+ REGRESSION = 'regression'
44
+
45
+ def __str__(self) -> str:
46
+ return self.value
47
+
48
+
49
+
50
+ def update_training_log(training_log, data, metrics):
51
+ def _update(log_part, data_part):
52
+ for k, v in data_part.items():
53
+ if isinstance(v, dict):
54
+ _update(log_part.setdefault(k, {}), v)
55
+ elif isinstance(v, list):
56
+ log_part.setdefault(k, []).extend(v)
57
+ else:
58
+ log_part.setdefault(k, []).append(v)
59
+
60
+ _update(training_log, data)
61
+ transposed_metrics = {}
62
+ for part, part_metrics in metrics.items():
63
+ for metric_name, value in part_metrics.items():
64
+ transposed_metrics.setdefault(metric_name, {})[part] = value
65
+ _update(training_log, transposed_metrics)
66
+
67
+
68
+ def raise_unknown(unknown_what: str, unknown_value: Any):
69
+ raise ValueError(f'Unknown {unknown_what}: {unknown_value}')
70
+
71
+
72
+ def _replace(data, condition, value):
73
+ def do(x):
74
+ if isinstance(x, dict):
75
+ return {k: do(v) for k, v in x.items()}
76
+ elif isinstance(x, list):
77
+ return [do(y) for y in x]
78
+ else:
79
+ return value if condition(x) else x
80
+
81
+ return do(data)
82
+
83
+
84
+ _CONFIG_NONE = '__none__'
85
+
86
+
87
+ def unpack_config(config: RawConfig) -> RawConfig:
88
+ config = cast(RawConfig, _replace(config, lambda x: x == _CONFIG_NONE, None))
89
+ return config
90
+
91
+
92
+ def pack_config(config: RawConfig) -> RawConfig:
93
+ config = cast(RawConfig, _replace(config, lambda x: x is None, _CONFIG_NONE))
94
+ return config
95
+
96
+
97
+ def load_config(path: Union[Path, str]) -> Any:
98
+ with open(path, 'rb') as f:
99
+ return unpack_config(tomli.load(f))
100
+
101
+
102
+ def dump_config(config: Any, path: Union[Path, str]) -> None:
103
+ with open(path, 'wb') as f:
104
+ tomli_w.dump(pack_config(config), f)
105
+ # check that there are no bugs in all these "pack/unpack" things
106
+ assert config == load_config(path)
107
+
108
+
109
+ def load_json(path: Union[Path, str], **kwargs) -> Any:
110
+ return json.loads(Path(path).read_text(), **kwargs)
111
+
112
+
113
+ def dump_json(x: Any, path: Union[Path, str], **kwargs) -> None:
114
+ kwargs.setdefault('indent', 4)
115
+ Path(path).write_text(json.dumps(x, **kwargs) + '\n')
116
+
117
+
118
+ def load_pickle(path: Union[Path, str], **kwargs) -> Any:
119
+ return pickle.loads(Path(path).read_bytes(), **kwargs)
120
+
121
+
122
+ def dump_pickle(x: Any, path: Union[Path, str], **kwargs) -> None:
123
+ Path(path).write_bytes(pickle.dumps(x, **kwargs))
124
+
125
+
126
+ def load(path: Union[Path, str], **kwargs) -> Any:
127
+ return globals()[f'load_{Path(path).suffix[1:]}'](Path(path), **kwargs)
128
+
129
+
130
+ def dump(x: Any, path: Union[Path, str], **kwargs) -> Any:
131
+ return globals()[f'dump_{Path(path).suffix[1:]}'](x, Path(path), **kwargs)
132
+
133
+
134
+ def _get_output_item_path(
135
+ path: Union[str, Path], filename: str, must_exist: bool
136
+ ) -> Path:
137
+ path = env.get_path(path)
138
+ if path.suffix == '.toml':
139
+ path = path.with_suffix('')
140
+ if path.is_dir():
141
+ path = path / filename
142
+ else:
143
+ assert path.name == filename
144
+ assert path.parent.exists()
145
+ if must_exist:
146
+ assert path.exists()
147
+ return path
148
+
149
+
150
+ def load_report(path: Path) -> Report:
151
+ return load_json(_get_output_item_path(path, 'report.json', True))
152
+
153
+
154
+ def dump_report(report: dict, path: Path) -> None:
155
+ dump_json(report, _get_output_item_path(path, 'report.json', False))
156
+
157
+
158
+ def load_predictions(path: Path) -> Dict[str, np.ndarray]:
159
+ with np.load(_get_output_item_path(path, 'predictions.npz', True)) as predictions:
160
+ return {x: predictions[x] for x in predictions}
161
+
162
+
163
+ def dump_predictions(predictions: Dict[str, np.ndarray], path: Path) -> None:
164
+ np.savez(_get_output_item_path(path, 'predictions.npz', False), **predictions)
165
+
166
+
167
+ def dump_metrics(metrics: Dict[str, Any], path: Path) -> None:
168
+ dump_json(metrics, _get_output_item_path(path, 'metrics.json', False))
169
+
170
+
171
+ def load_checkpoint(path: Path, *args, **kwargs) -> Dict[str, np.ndarray]:
172
+ return torch.load(
173
+ _get_output_item_path(path, 'checkpoint.pt', True), *args, **kwargs
174
+ )
175
+
176
+
177
+ def get_device() -> torch.device:
178
+ if torch.cuda.is_available():
179
+ assert os.environ.get('CUDA_VISIBLE_DEVICES') is not None
180
+ return torch.device('cuda:0')
181
+ else:
182
+ return torch.device('cpu')
183
+
184
+
185
+ def _print_sep(c, size=100):
186
+ print(c * size)
187
+
188
+
189
+ _LAST_SNAPSHOT_TIME = None
190
+
191
+
192
+ def backup_output(output_dir: Path) -> None:
193
+ backup_dir = os.environ.get('TMP_OUTPUT_PATH')
194
+ snapshot_dir = os.environ.get('SNAPSHOT_PATH')
195
+ if backup_dir is None:
196
+ assert snapshot_dir is None
197
+ return
198
+ assert snapshot_dir is not None
199
+
200
+ try:
201
+ relative_output_dir = output_dir.relative_to(env.PROJ)
202
+ except ValueError:
203
+ return
204
+
205
+ for dir_ in [backup_dir, snapshot_dir]:
206
+ new_output_dir = dir_ / relative_output_dir
207
+ prev_backup_output_dir = new_output_dir.with_name(new_output_dir.name + '_prev')
208
+ new_output_dir.parent.mkdir(exist_ok=True, parents=True)
209
+ if new_output_dir.exists():
210
+ new_output_dir.rename(prev_backup_output_dir)
211
+ shutil.copytree(output_dir, new_output_dir)
212
+ # the case for evaluate.py which automatically creates configs
213
+ if output_dir.with_suffix('.toml').exists():
214
+ shutil.copyfile(
215
+ output_dir.with_suffix('.toml'), new_output_dir.with_suffix('.toml')
216
+ )
217
+ if prev_backup_output_dir.exists():
218
+ shutil.rmtree(prev_backup_output_dir)
219
+
220
+ global _LAST_SNAPSHOT_TIME
221
+ if _LAST_SNAPSHOT_TIME is None or time.time() - _LAST_SNAPSHOT_TIME > 10 * 60:
222
+ import nirvana_dl.snapshot # type: ignore[code]
223
+
224
+ nirvana_dl.snapshot.dump_snapshot()
225
+ _LAST_SNAPSHOT_TIME = time.time()
226
+ print('The snapshot was saved!')
227
+
228
+
229
+ def _get_scores(metrics: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, float]]:
230
+ return (
231
+ {k: v['score'] for k, v in metrics.items()}
232
+ if 'score' in next(iter(metrics.values()))
233
+ else None
234
+ )
235
+
236
+
237
+ def format_scores(metrics: Dict[str, Dict[str, Any]]) -> str:
238
+ return ' '.join(
239
+ f"[{x}] {metrics[x]['score']:.3f}"
240
+ for x in ['test', 'val', 'train']
241
+ if x in metrics
242
+ )
243
+
244
+
245
+ def finish(output_dir: Path, report: dict) -> None:
246
+ print()
247
+ _print_sep('=')
248
+
249
+ metrics = report.get('metrics')
250
+ if metrics is not None:
251
+ scores = _get_scores(metrics)
252
+ if scores is not None:
253
+ dump_json(scores, output_dir / 'scores.json')
254
+ print(format_scores(metrics))
255
+ _print_sep('-')
256
+
257
+ dump_report(report, output_dir)
258
+ json_output_path = os.environ.get('JSON_OUTPUT_FILE')
259
+ if json_output_path:
260
+ try:
261
+ key = str(output_dir.relative_to(env.PROJ))
262
+ except ValueError:
263
+ pass
264
+ else:
265
+ json_output_path = Path(json_output_path)
266
+ try:
267
+ json_data = json.loads(json_output_path.read_text())
268
+ except (FileNotFoundError, json.decoder.JSONDecodeError):
269
+ json_data = {}
270
+ json_data[key] = load_json(output_dir / 'report.json')
271
+ json_output_path.write_text(json.dumps(json_data, indent=4))
272
+ shutil.copyfile(
273
+ json_output_path,
274
+ os.path.join(os.environ['SNAPSHOT_PATH'], 'json_output.json'),
275
+ )
276
+
277
+ output_dir.joinpath('DONE').touch()
278
+ backup_output(output_dir)
279
+ print(f'Done! | {report.get("time")} | {output_dir}')
280
+ _print_sep('=')
281
+ print()
282
+
283
+
284
+ def from_dict(datacls: Type[T], data: dict) -> T:
285
+ assert is_dataclass(datacls)
286
+ data = deepcopy(data)
287
+ for field in fields(datacls):
288
+ if field.name not in data:
289
+ continue
290
+ if is_dataclass(field.type):
291
+ data[field.name] = from_dict(field.type, data[field.name])
292
+ elif (
293
+ get_origin(field.type) is Union
294
+ and len(get_args(field.type)) == 2
295
+ and get_args(field.type)[1] is type(None)
296
+ and is_dataclass(get_args(field.type)[0])
297
+ ):
298
+ if data[field.name] is not None:
299
+ data[field.name] = from_dict(get_args(field.type)[0], data[field.name])
300
+ return datacls(**data)
301
+
302
+
303
+ def replace_factor_with_value(
304
+ config: RawConfig,
305
+ key: str,
306
+ reference_value: int,
307
+ bounds: Tuple[float, float],
308
+ ) -> None:
309
+ factor_key = key + '_factor'
310
+ if factor_key not in config:
311
+ assert key in config
312
+ else:
313
+ assert key not in config
314
+ factor = config.pop(factor_key)
315
+ assert bounds[0] <= factor <= bounds[1]
316
+ config[key] = int(factor * reference_value)
317
+
318
+
319
+ def get_temporary_copy(path: Union[str, Path]) -> Path:
320
+ path = env.get_path(path)
321
+ assert not path.is_dir() and not path.is_symlink()
322
+ tmp_path = path.with_name(
323
+ path.stem + '___' + str(uuid.uuid4()).replace('-', '') + path.suffix
324
+ )
325
+ shutil.copyfile(path, tmp_path)
326
+ atexit.register(lambda: tmp_path.unlink())
327
+ return tmp_path
328
+
329
+
330
+ def get_python():
331
+ python = Path('python3.9')
332
+ return str(python) if python.exists() else 'python'
333
+
334
+ def get_catboost_config(real_data_path, is_cv=False):
335
+ ds_name = Path(real_data_path).name
336
+ C = load_json(f'tuned_models/catboost/{ds_name}_cv.json')
337
+ return C
338
+
339
+ def get_categories(X_train_cat):
340
+ return (
341
+ None
342
+ if X_train_cat is None
343
+ else [
344
+ len(set(X_train_cat[:, i]))
345
+ for i in range(X_train_cat.shape[1])
346
+ ]
347
+ )
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthcity.yaml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: synthcity
2
+ channels:
3
+ - pytorch
4
+ - nvidia
5
+ - defaults
6
+ dependencies:
7
+ - python=3.10
8
+ - pip
9
+ - pip:
10
+ - synthcity
11
+ - category_encoders
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthetic/pipeline_c19/real.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:092346325db7f445db2c00d2f5dd9a8397ecc33eaba7b2b14d9d48d92659fcfc
3
+ size 51459027
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthetic/pipeline_c19/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fd9c98343a92c7b1afe63b402f07b9a55013adbfcc60ec1e17d5e026385eeec8
3
+ size 6304860
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/synthetic/pipeline_c19/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69c75639e81916d3b4f2a28db38d7e15c78e442748aa5bf9fed2eb3784912a70
3
+ size 6331589
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff.yaml ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: tabdiff
2
+ channels:
3
+ - pytorch
4
+ - nvidia
5
+ - defaults
6
+ dependencies:
7
+ - python=3.10
8
+ - pytorch=2.0.1
9
+ - torchvision==0.15.2
10
+ - torchaudio==2.0.2
11
+ - pytorch-cuda=11.7
12
+ - numpy<2
13
+ - pip
14
+ - pip:
15
+ - pandas
16
+ - scikit-learn
17
+ - scipy
18
+ - icecream
19
+ - xlrd
20
+ - tomli-w
21
+ - tomli==2.0.1
22
+ - category_encoders
23
+ - imbalanced-learn
24
+ - kaggle
25
+ - transformers
26
+ - datasets
27
+ - peft==0.9.0
28
+ - ml_collections
29
+ - sdmetrics
30
+ - prdc
31
+ - rdt
32
+ - openpyxl
33
+ - xgboost
34
+ - wandb==0.17.3
35
+ - kaleido
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/config.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0c2187811b2ca3b6157a99c23d4030ba5acfae5e78a8b37010dc2108fdde8b58
3
+ size 1447
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/ema_model_200.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1036982df1bab02f1ce920a737ffbca53f92c8d4fb99bbafa007707400696793
3
+ size 44012991
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/ckpt/pipeline_c19/adapter_learnable/model_200.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:293c33dfcf0042cd083ef5e0f4a5737bda8e4f4027d7fe7b67103e0314d28f17
3
+ size 44013323
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/configs/tabdiff_configs.toml ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:38eff74ecb572c9baafc5e912f8b5421cae686ddb4df6e3bc2a9b69c6ec69cd6
3
+ size 1234
SynthData0523/main/c19/tabdiff/tabdiff-c19-20260512_231303/_tabdiff_runtime/tabdiff/main.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import json
3
+ import os
4
+ import pickle
5
+ import random
6
+
7
+ import numpy as np
8
+ from tabdiff.metrics import TabMetrics
9
+ from tabdiff.modules.main_modules import UniModMLP
10
+ from tabdiff.modules.main_modules import Model
11
+ from tabdiff.models.unified_ctime_diffusion import UnifiedCtimeDiffusion
12
+ from tabdiff.trainer import Trainer
13
+ import src
14
+ import torch
15
+
16
+ from torch.utils.data import DataLoader
17
+ import argparse
18
+ import warnings
19
+
20
+ import wandb
21
+
22
+ from copy import deepcopy
23
+
24
+ from utils_train import TabDiffDataset
25
+
26
+ warnings.filterwarnings('ignore')
27
+
28
+
29
+ def main(args):
30
+ device = args.device
31
+
32
+ ## Disable scientific numerical format
33
+ np.set_printoptions(suppress=True)
34
+ torch.set_printoptions(sci_mode=False)
35
+
36
+ ## Get data info
37
+ dataname = args.dataname
38
+ data_dir = f'data/{dataname}'
39
+ info_path = f'data/{dataname}/info.json'
40
+ with open(info_path, 'r') as f:
41
+ info = json.load(f)
42
+
43
+ ## Set up flags
44
+ is_dcr = 'dcr' in dataname
45
+
46
+ ## Set experiment name
47
+ exp_name = args.exp_name
48
+ if args.exp_name is None:
49
+ exp_name = 'non_learnable_schedule' if args.non_learnable_schedule else 'learnable_schedule'
50
+ exp_name += '_y_only' if args.y_only else ''
51
+
52
+ ## Load configs
53
+ curr_dir = os.path.dirname(os.path.abspath(__file__))
54
+ config_path = f'{curr_dir}/configs/tabdiff_configs.toml'
55
+ raw_config = src.load_config(config_path)
56
+
57
+ print(f"{args.mode.capitalize()} Mode is Enabled")
58
+ num_samples_to_generate = None
59
+ ckpt_path = None
60
+ if args.mode == 'train':
61
+ print("NEW training is started")
62
+ elif args.mode == 'test':
63
+ num_samples_to_generate = args.num_samples_to_generate
64
+ ckpt_path = args.ckpt_path
65
+ if ckpt_path is None:
66
+ ckpt_parent_path = f"{curr_dir}/ckpt/{dataname}/{exp_name}"
67
+ ckpt_path_arr = glob.glob(f"{ckpt_parent_path}/best_ema_model*")
68
+ assert ckpt_path_arr, f"Cannot not infer ckpt_path from {ckpt_parent_path}, please make sure that you first train a model before testing!"
69
+ ckpt_path = ckpt_path_arr[0]
70
+ config_path = os.path.join(os.path.dirname(ckpt_path), 'config.pkl')
71
+ if os.path.exists(config_path):
72
+ with open(config_path, 'rb') as f:
73
+ cached_raw_config = pickle.load(f)
74
+ print(f"Found cached config at {config_path}")
75
+ raw_config = cached_raw_config
76
+
77
+
78
+ ## Creat model_save and result paths
79
+ model_save_path, result_save_path = None, None
80
+ if args.mode == 'train':
81
+ model_save_path = 'debug/ckpt' if args.debug else f'{curr_dir}/ckpt/{dataname}/{exp_name}'
82
+ result_save_path = model_save_path.replace('ckpt', 'result') #i.e., f'{curr_dir}/results/{dataname}/{exp_name}'
83
+ elif args.mode == 'test':
84
+ if args.report:
85
+ result_save_path = f"eval/report_runs/{exp_name}/{dataname}"
86
+ else:
87
+ result_save_path = os.path.dirname(ckpt_path).replace('ckpt', 'result') # infer the exp_name from the ckpt_name
88
+ raw_config['model_save_path'] = model_save_path
89
+ raw_config['result_save_path'] = result_save_path
90
+ if model_save_path is not None:
91
+ if not os.path.exists(model_save_path):
92
+ os.makedirs(model_save_path)
93
+ if result_save_path is not None:
94
+ if not os.path.exists(result_save_path):
95
+ os.makedirs(result_save_path)
96
+
97
+ ## Make everything determinstic if needed
98
+ raw_config['deterministic'] = args.deterministic
99
+ if args.deterministic:
100
+ print("DETERMINISTIC MODE is enabled!!!")
101
+ ## Set global random seeds
102
+ torch.manual_seed(0)
103
+ random.seed(0)
104
+ np.random.seed(0)
105
+
106
+ ## Ensure deterministic CUDA operations
107
+ os.environ['PYTHONHASHSEED'] = '0'
108
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' # or ':16:8'
109
+ torch.use_deterministic_algorithms(True)
110
+ if torch.cuda.is_available():
111
+ torch.cuda.manual_seed(0)
112
+ torch.cuda.manual_seed_all(0)
113
+ torch.backends.cudnn.deterministic = True
114
+ torch.backends.cudnn.benchmark = False
115
+
116
+ ## Set debug mode parameters
117
+ if args.debug: # fast eval for DEBUG mode
118
+ raw_config['train']['main']['check_val_every'] = 2
119
+ raw_config['diffusion_params']['num_timesteps'] = 4
120
+ raw_config['train']['main']['batch_size'] = 4096
121
+ raw_config['sample']['batch_size'] = 10000
122
+
123
+ # CI /镜像冒烟:覆盖训练步数(默认不设置)
124
+ _smoke_steps = os.environ.get("TABDIFF_SMOKE_STEPS", "").strip()
125
+ if _smoke_steps and args.mode == "train":
126
+ n = max(1, int(_smoke_steps))
127
+ raw_config["train"]["main"]["steps"] = n
128
+ raw_config["train"]["main"]["check_val_every"] = max(1, min(n, raw_config["train"]["main"]["check_val_every"]))
129
+ # Pipeline 适配器:避免小步数训练时在中途频繁做生成评测;仅在最后一轮 checkpoint
130
+ if os.environ.get("TABDIFF_ADAPTER_TRAIN", "").strip() and args.mode == "train":
131
+ raw_config["train"]["main"]["check_val_every"] = int(raw_config["train"]["main"]["steps"])
132
+
133
+ ## Load training data
134
+ batch_size = raw_config['train']['main']['batch_size']
135
+
136
+ train_data = TabDiffDataset(dataname, data_dir, info, y_only=args.y_only, isTrain=True, dequant_dist=raw_config['data']['dequant_dist'], int_dequant_factor=raw_config['data']['int_dequant_factor'])
137
+ train_loader = DataLoader(
138
+ train_data,
139
+ batch_size = batch_size,
140
+ shuffle = True,
141
+ num_workers = 4,
142
+ )
143
+ d_numerical, categories = train_data.d_numerical, train_data.categories
144
+
145
+ val_data = TabDiffDataset(dataname, data_dir, info, y_only=args.y_only, isTrain=False, dequant_dist=raw_config['data']['dequant_dist'], int_dequant_factor=raw_config['data']['int_dequant_factor'])
146
+
147
+ ## Load Metrics
148
+ real_data_path = f'synthetic/{dataname}/real.csv'
149
+ test_data_path = f'synthetic/{dataname}/test.csv'
150
+ val_data_path = f'synthetic/{dataname}/val.csv'
151
+ if not os.path.exists(val_data_path):
152
+ print(f"{args.dataname} does not have its validation set. During MLE evaluation, a validation set will be splitted from the training set!")
153
+ val_data_path = None
154
+ if args.mode == 'train':
155
+ metric_list = ["density"]
156
+ else:
157
+ if is_dcr:
158
+ metric_list = ["dcr"]
159
+ else:
160
+ metric_list = [
161
+ "density",
162
+ "mle",
163
+ "c2st",
164
+ ]
165
+ metrics = TabMetrics(real_data_path, test_data_path, val_data_path, info, device, metric_list=metric_list)
166
+
167
+ ## Load the module and models
168
+ raw_config['unimodmlp_params']['d_numerical'] = d_numerical
169
+ raw_config['unimodmlp_params']['categories'] = (categories+1).tolist() # add one for the mask category
170
+ if args.y_only:
171
+ raw_config['unimodmlp_params']['use_mlp'] = False # drop the mlp when training the unconditional model
172
+ raw_config['unimodmlp_params']['dim_t'] = 128 #reduce the size of the mlp
173
+ main_model_path = args.ckpt_path
174
+ if main_model_path is None:
175
+ main_model_parent_path = f"{curr_dir}/ckpt/{dataname}/{exp_name.replace('_y_only', '')}"
176
+ main_model_path_arr = glob.glob(f"{main_model_parent_path}/best_ema_model*")
177
+ assert main_model_path_arr, f"Cannot not infer the main model's ckpt_path from {main_model_parent_path}, please make sure that you first train a main model before training the y_only model!"
178
+ main_model_path = main_model_path_arr[0]
179
+ main_model_configs = pickle.load(open(os.path.join(os.path.dirname(main_model_path), 'config.pkl'), 'rb'))
180
+ if main_model_configs['diffusion_params']['scheduler'] == "power_mean_per_column": # if learnable schedule is enabled in the main model, we need to infer noise params of the target column from the main model ckpt and train the y_only model with those params
181
+ from tabdiff.models.noise_schedule import PowerMeanNoise_PerColumn, LogLinearNoise_PerColumn
182
+ if info['task_type'] == 'regression':
183
+ noise_schedule = PowerMeanNoise_PerColumn(
184
+ num_numerical=main_model_configs['unimodmlp_params']['d_numerical'],
185
+ **main_model_configs['diffusion_params']['noise_schedule_params']
186
+ )
187
+ raw_config['diffusion_params']['noise_schedule_params']['rho'] = noise_schedule.rho()[0].item() # the target col is placed at the first position
188
+ else:
189
+ noise_schedule = LogLinearNoise_PerColumn(
190
+ num_categories=len(main_model_configs['unimodmlp_params']['categories']),
191
+ **main_model_configs['diffusion_params']['noise_schedule_params']
192
+ )
193
+ raw_config['diffusion_params']['noise_schedule_params']['k'] = noise_schedule.k()[0].item() # the target col is placed at the first position
194
+
195
+ backbone = UniModMLP(
196
+ **raw_config['unimodmlp_params']
197
+ )
198
+ model = Model(backbone, **raw_config['diffusion_params']['edm_params'])
199
+ model.to(device)
200
+
201
+ ## Create and load y_only_model for imputation
202
+ y_only_model = None
203
+ if args.impute:
204
+ y_only_model_path = args.y_only_model_path
205
+ if y_only_model_path is None:
206
+ y_only_model_parent_path = f"{curr_dir}/ckpt/{dataname}/{exp_name}_y_only"
207
+ y_only_model_path_arr = glob.glob(f"{y_only_model_parent_path}/best_ema_model*")
208
+ assert y_only_model_path_arr, f"Cannot not infer y_only model's ckpt_path from {y_only_model_parent_path}, please make sure that you first train a y_only model before testing imputation!"
209
+ y_only_model_path = y_only_model_path_arr[0]
210
+ y_only_model_config_path = os.path.join(os.path.dirname(y_only_model_path), 'config.pkl')
211
+ with open(y_only_model_config_path, 'rb') as f:
212
+ y_only_model_config = pickle.load(f)
213
+ y_only_model = UniModMLP(
214
+ **y_only_model_config['unimodmlp_params']
215
+ )
216
+ y_only_model = Model(y_only_model, **y_only_model_config['diffusion_params']['edm_params'])
217
+ y_only_model.to(device)
218
+ # load weights
219
+ state_dicts = torch.load(y_only_model_path, map_location=device)
220
+ y_only_model.load_state_dict(state_dicts['denoise_fn'])
221
+
222
+ if not args.y_only and not args.non_learnable_schedule:
223
+ raw_config['diffusion_params']['scheduler'] = 'power_mean_per_column'
224
+ raw_config['diffusion_params']['cat_scheduler'] = 'log_linear_per_column'
225
+ diffusion = UnifiedCtimeDiffusion(
226
+ num_classes=categories,
227
+ num_numerical_features=d_numerical,
228
+ denoise_fn=model,
229
+ y_only_model=y_only_model,
230
+ **raw_config['diffusion_params'],
231
+ device=device,
232
+ )
233
+ num_params = sum(p.numel() for p in diffusion.parameters())
234
+ print("The number of parameters = ", num_params)
235
+ diffusion.to(device)
236
+ diffusion.train()
237
+
238
+ ## Print the configs
239
+ printed_configs = json.dumps(raw_config, default=lambda x: int(x) if isinstance(x, np.int64) else x, indent=4)
240
+ print(f"The config of the current run is : \n {printed_configs}")
241
+
242
+ ## Enable Wandb
243
+ project_name = f"tabdiff_{dataname}"
244
+ raw_config['project_name'] = project_name
245
+ logger = wandb.init(
246
+ project=raw_config['project_name'],
247
+ name=exp_name,
248
+ config=raw_config,
249
+ mode='disabled' if args.debug or args.no_wandb else 'online',
250
+ )
251
+
252
+ ## Load Trainer
253
+ sample_batch_size = raw_config['sample']['batch_size']
254
+ trainer = Trainer(
255
+ diffusion,
256
+ train_loader,
257
+ train_data,
258
+ val_data,
259
+ metrics,
260
+ logger,
261
+ **raw_config['train']['main'],
262
+ sample_batch_size=sample_batch_size,
263
+ num_samples_to_generate=num_samples_to_generate,
264
+ model_save_path=raw_config['model_save_path'],
265
+ result_save_path=raw_config['result_save_path'],
266
+ device=device,
267
+ ckpt_path=ckpt_path,
268
+ y_only=args.y_only
269
+ )
270
+ if args.mode == 'test':
271
+ if args.report:
272
+ if is_dcr:
273
+ trainer.report_test_dcr(args.num_runs)
274
+ else:
275
+ trainer.report_test(args.num_runs)
276
+ elif args.impute:
277
+ imputed_sample_save_dir = f"impute/{dataname}/{exp_name}"
278
+ trainer.test_impute(
279
+ args.trial_start, args.trial_size,
280
+ args.resample_rounds,
281
+ args.impute_condition,
282
+ imputed_sample_save_dir,
283
+ args.w_num,
284
+ args.w_cat,
285
+ )
286
+ else:
287
+ trainer.test()
288
+ else:
289
+ ## Save config
290
+ config_save_path = raw_config['model_save_path']
291
+ with open (os.path.join(config_save_path, 'config.pkl'), 'wb') as f:
292
+ pickle.dump(raw_config, f)
293
+ trainer.run_loop()
294
+
295
+
296
+
297
+ if __name__ == '__main__':
298
+
299
+ parser = argparse.ArgumentParser(description='Training of TabDiff')
300
+
301
+ parser.add_argument('--dataname', type=str, default='adult', help='Name of dataset.')
302
+ parser.add_argument('--gpu', type=int, default=0, help='GPU index.')
303
+ parser.add_argument('--mode', type=str, default='train', choices=['train', 'test'])
304
+ parser.add_argument('--debug', action='store_true')
305
+ parser.add_argument('--no_wandb', action='store_true')
306
+ parser.add_argument('--deterministic', action='store_true')
307
+ parser.add_argument('--exp_name', type=str, default=None)
308
+ parser.add_argument('--non_learnable_schedule', action='store_true')
309
+ parser.add_argument('--y_only', action='store_true')
310
+ parser.add_argument('--ckpt_path', type=str, default=None)
311
+ parser.add_argument('--num_samples_to_generate', type=int, default=None)
312
+ parser.add_argument('--report', action='store_true')
313
+ parser.add_argument('--num_runs', type=int, default=20)
314
+ parser.add_argument('--impute', action='store_true')
315
+ parser.add_argument('--trial_start', type=int, default=0)
316
+ parser.add_argument('--trial_size', type=int, default=100)
317
+ parser.add_argument('--resample_rounds', type=int, default=1)
318
+ parser.add_argument('--impute_condition', type=str, default='')
319
+ parser.add_argument('--w_num', type=float, default=1.0)
320
+ parser.add_argument('--w_cat', type=float, default=1.0)
321
+ parser.add_argument('--y_only_model_path', type=str, default=None)
322
+
323
+ args = parser.parse_args()
324
+
325
+ # check cuda
326
+ if args.gpu != -1 and torch.cuda.is_available():
327
+ args.device = f'cuda:{args.gpu}'
328
+ else:
329
+ args.device = 'cpu'
330
+
331
+ main(args)