jialinzhang commited on
Commit
ab0c24f
·
1 Parent(s): d5b2872

Add syntheticFail m12

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/_tabddpm_train.py +32 -0
  2. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/config.toml +39 -0
  3. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/data/X_cat_train.npy +3 -0
  4. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/data/X_num_train.npy +3 -0
  5. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/data/info.json +80 -0
  6. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/data/y_train.npy +3 -0
  7. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/input_snapshot.json +36 -0
  8. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/normalized_schema_snapshot.json +670 -0
  9. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/public_gate_report.json +37 -0
  10. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/staged_input_manifest.json +675 -0
  11. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/run_config.json +45 -0
  12. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/runtime_result.json +24 -0
  13. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/staged_features.json +162 -0
  14. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/test.csv +3 -0
  15. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/train.csv +3 -0
  16. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/val.csv +3 -0
  17. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/tabddpm/adapter_report.json +7 -0
  18. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/tabddpm/adapter_transforms_applied.json +1 -0
  19. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/tabddpm/model_input_manifest.json +677 -0
  20. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/train_20260510_215504.log +3 -0
  21. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/._data +0 -0
  22. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/.gitignore +22 -0
  23. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/.gitmodules +9 -0
  24. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CONFIG_DESCRIPTION.md +78 -0
  25. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/.gitignore +1 -0
  26. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/README.md +49 -0
  27. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/columns.json +119 -0
  28. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/ctabgan.py +70 -0
  29. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/eval/evaluation.py +193 -0
  30. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/pipeline/data_preparation.py +130 -0
  31. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/privacy_utils/rdp_accountant.py +280 -0
  32. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/ctabgan_synthesizer.py +601 -0
  33. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/transformer.py +429 -0
  34. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py +72 -0
  35. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/eval/evaluation.py +193 -0
  36. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/pipeline/data_preparation.py +131 -0
  37. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/privacy_utils/rdp_accountant.py +280 -0
  38. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/ctabgan_synthesizer.py +605 -0
  39. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/transformer.py +429 -0
  40. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py +81 -0
  41. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py +110 -0
  42. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py +153 -0
  43. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/.gitignore +1 -0
  44. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/LICENSE +201 -0
  45. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/License.txt +15 -0
  46. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/README.md +50 -0
  47. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/columns.json +74 -0
  48. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/model/__init__.py +0 -0
  49. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py +58 -0
  50. syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py +191 -0
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/_tabddpm_train.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys, subprocess
2
+
3
+ tabddpm_root = "/workspace/tabddpm/code"
4
+ assert os.path.isdir(tabddpm_root), f"TabDDPM source not mounted: {tabddpm_root}"
5
+ env = os.environ.copy()
6
+ env["PYTHONPATH"] = tabddpm_root + (os.pathsep + env.get("PYTHONPATH", ""))
7
+
8
+ # Write a wrapper that patches collections.Sequence (removed in Python 3.10+)
9
+ # before running pipeline.py - needed because skorch uses old API
10
+ wrapper = os.path.join(tabddpm_root, "_compat_run.py")
11
+ with open(wrapper, "w") as f:
12
+ f.write(
13
+ "import collections, collections.abc\n"
14
+ "for _a in ('Sequence','MutableSequence','MutableMapping','Mapping',"
15
+ "'MutableSet','Set','Callable','Iterable','Iterator'):\n"
16
+ " if not hasattr(collections, _a): setattr(collections, _a, getattr(collections.abc, _a, None))\n"
17
+ "import sys, runpy\n"
18
+ "sys.argv = sys.argv[1:]\n"
19
+ "runpy.run_path(sys.argv[0], run_name='__main__')\n"
20
+ )
21
+
22
+ print(f"[TabDDPM] Training, config=/work/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/config.toml")
23
+ ret = subprocess.run(
24
+ [sys.executable, wrapper, "scripts/pipeline.py",
25
+ "--config", "/work/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/config.toml",
26
+ "--train"],
27
+ cwd=tabddpm_root,
28
+ env=env
29
+ )
30
+ if ret.returncode != 0:
31
+ sys.exit(ret.returncode)
32
+ print("[TabDDPM] Training complete")
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/config.toml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ seed = 0
2
+ parent_dir = "/work/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/output"
3
+ real_data_path = "/work/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/data"
4
+ model_type = "mlp"
5
+ num_numerical_features = 14
6
+ device = "cuda:0"
7
+
8
+ [model_params]
9
+ d_in = 31
10
+ num_classes = 4
11
+ is_y_cond = true
12
+
13
+ [model_params.rtdl_params]
14
+ d_layers = [256, 256]
15
+ dropout = 0.0
16
+
17
+ [diffusion_params]
18
+ num_timesteps = 200
19
+ gaussian_loss_type = "mse"
20
+
21
+ [train.main]
22
+ steps = 2000
23
+ lr = 0.001
24
+ weight_decay = 0.0
25
+ batch_size = 256
26
+
27
+ [train.T]
28
+ seed = 0
29
+ normalization = "quantile"
30
+ num_nan_policy = "__none__"
31
+ cat_nan_policy = "__none__"
32
+ cat_min_frequency = "__none__"
33
+ cat_encoding = "__none__"
34
+ y_policy = "default"
35
+
36
+ [sample]
37
+ num_samples = 1000
38
+ batch_size = 256
39
+ seed = 0
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/data/X_cat_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d46a64880509389229c0bd65f5117ecb73e8e2809b3e548a8af185d85737a126
3
+ size 12989760
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/data/X_num_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6858d88008eac5dbfeb9e0068a78aa9698f51aabe0c703bfa50ff77e01144b29
3
+ size 5348800
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/data/info.json ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "benchmark_dataset",
3
+ "task_type": "multiclass",
4
+ "n_num_features": 14,
5
+ "n_cat_features": 17,
6
+ "train_size": 95512,
7
+ "num_col_idx": [
8
+ 0,
9
+ 1,
10
+ 2,
11
+ 3,
12
+ 4,
13
+ 5,
14
+ 6,
15
+ 7,
16
+ 8,
17
+ 9,
18
+ 10,
19
+ 11,
20
+ 12,
21
+ 13
22
+ ],
23
+ "cat_col_idx": [
24
+ 14,
25
+ 15,
26
+ 16,
27
+ 17,
28
+ 18,
29
+ 19,
30
+ 20,
31
+ 21,
32
+ 22,
33
+ 23,
34
+ 24,
35
+ 25,
36
+ 26,
37
+ 27,
38
+ 28,
39
+ 29,
40
+ 30
41
+ ],
42
+ "target_col_idx": [
43
+ 31
44
+ ],
45
+ "column_names": [
46
+ "lead_time",
47
+ "arrival_date_year",
48
+ "arrival_date_week_number",
49
+ "arrival_date_day_of_month",
50
+ "stays_in_weekend_nights",
51
+ "stays_in_week_nights",
52
+ "adults",
53
+ "children",
54
+ "booking_changes",
55
+ "agent",
56
+ "company",
57
+ "days_in_waiting_list",
58
+ "adr",
59
+ "total_of_special_requests",
60
+ "hotel",
61
+ "is_canceled",
62
+ "arrival_date_month",
63
+ "babies",
64
+ "meal",
65
+ "country",
66
+ "market_segment",
67
+ "distribution_channel",
68
+ "is_repeated_guest",
69
+ "previous_cancellations",
70
+ "previous_bookings_not_canceled",
71
+ "reserved_room_type",
72
+ "assigned_room_type",
73
+ "deposit_type",
74
+ "required_car_parking_spaces",
75
+ "reservation_status",
76
+ "reservation_status_date",
77
+ "customer_type"
78
+ ],
79
+ "num_classes": 4
80
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/data/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:585d082372be612634c9472cd98cfd16667c4a2ec082246cbb34339f54abbf1c
3
+ size 764224
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/input_snapshot.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "m12",
3
+ "model": "tabddpm",
4
+ "inputs": {
5
+ "train_csv": {
6
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/m12/m12-train.csv",
7
+ "exists": true,
8
+ "size": 13165359,
9
+ "sha256": "38507849456d473e77f70bde2e03dd69c9694d3640debeb0e1dd3a99b251862e"
10
+ },
11
+ "val_csv": {
12
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/m12/m12-val.csv",
13
+ "exists": true,
14
+ "size": 1646795,
15
+ "sha256": "7efe1eb3cfa68fbb779e8cb8490109c774b8241e5896a77d083544f04ccf6c66"
16
+ },
17
+ "test_csv": {
18
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/m12/m12-test.csv",
19
+ "exists": true,
20
+ "size": 1646190,
21
+ "sha256": "77c539bda6d6db356a6f1eb5d8344449f25d36b5309fa660bec41d855e49cefc"
22
+ },
23
+ "profile_json": {
24
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/artifacts/data_core/tabular/m12/m12-dataset_profile.json",
25
+ "exists": true,
26
+ "size": 12659,
27
+ "sha256": "d8c17ef1f421dc55e8669ecc08ba8b3d6cbb007f953b59ef6014af322c187cc3"
28
+ },
29
+ "contract_json": {
30
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/artifacts/data_core/tabular/m12/m12-dataset_contract_v1.json",
31
+ "exists": true,
32
+ "size": 15493,
33
+ "sha256": "439a5ec1e598498ffc934040b6975f626db2990104def7a6095d2100f5a974ff"
34
+ }
35
+ }
36
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/normalized_schema_snapshot.json ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "m12",
3
+ "target_column": "customer_type",
4
+ "task_type": "classification",
5
+ "columns": [
6
+ {
7
+ "name": "hotel",
8
+ "role": "feature",
9
+ "semantic_type": "text",
10
+ "nullable": false,
11
+ "missing_tokens": [],
12
+ "parse_format": null,
13
+ "impute_strategy": "keep_raw",
14
+ "profile_stats": {
15
+ "missing_rate": 0.0,
16
+ "unique_count": 2,
17
+ "unique_ratio": 2.1e-05,
18
+ "example_values": [
19
+ "City Hotel",
20
+ "Resort Hotel"
21
+ ]
22
+ }
23
+ },
24
+ {
25
+ "name": "is_canceled",
26
+ "role": "feature",
27
+ "semantic_type": "boolean",
28
+ "nullable": false,
29
+ "missing_tokens": [],
30
+ "parse_format": null,
31
+ "impute_strategy": "mode",
32
+ "profile_stats": {
33
+ "missing_rate": 0.0,
34
+ "unique_count": 2,
35
+ "unique_ratio": 2.1e-05,
36
+ "example_values": [
37
+ "0",
38
+ "1"
39
+ ]
40
+ }
41
+ },
42
+ {
43
+ "name": "lead_time",
44
+ "role": "feature",
45
+ "semantic_type": "numeric",
46
+ "nullable": false,
47
+ "missing_tokens": [],
48
+ "parse_format": null,
49
+ "impute_strategy": "median",
50
+ "profile_stats": {
51
+ "missing_rate": 0.0,
52
+ "unique_count": 476,
53
+ "unique_ratio": 0.004984,
54
+ "example_values": [
55
+ "53",
56
+ "1",
57
+ "152",
58
+ "23",
59
+ "7"
60
+ ]
61
+ }
62
+ },
63
+ {
64
+ "name": "arrival_date_year",
65
+ "role": "feature",
66
+ "semantic_type": "numeric",
67
+ "nullable": false,
68
+ "missing_tokens": [],
69
+ "parse_format": null,
70
+ "impute_strategy": "median",
71
+ "profile_stats": {
72
+ "missing_rate": 0.0,
73
+ "unique_count": 3,
74
+ "unique_ratio": 3.1e-05,
75
+ "example_values": [
76
+ "2016",
77
+ "2017",
78
+ "2015"
79
+ ]
80
+ }
81
+ },
82
+ {
83
+ "name": "arrival_date_month",
84
+ "role": "feature",
85
+ "semantic_type": "categorical",
86
+ "nullable": false,
87
+ "missing_tokens": [],
88
+ "parse_format": null,
89
+ "impute_strategy": "mode",
90
+ "profile_stats": {
91
+ "missing_rate": 0.0,
92
+ "unique_count": 12,
93
+ "unique_ratio": 0.000126,
94
+ "example_values": [
95
+ "October",
96
+ "November",
97
+ "May",
98
+ "July",
99
+ "December"
100
+ ]
101
+ }
102
+ },
103
+ {
104
+ "name": "arrival_date_week_number",
105
+ "role": "feature",
106
+ "semantic_type": "numeric",
107
+ "nullable": false,
108
+ "missing_tokens": [],
109
+ "parse_format": null,
110
+ "impute_strategy": "median",
111
+ "profile_stats": {
112
+ "missing_rate": 0.0,
113
+ "unique_count": 53,
114
+ "unique_ratio": 0.000555,
115
+ "example_values": [
116
+ "42",
117
+ "46",
118
+ "18",
119
+ "29",
120
+ "43"
121
+ ]
122
+ }
123
+ },
124
+ {
125
+ "name": "arrival_date_day_of_month",
126
+ "role": "feature",
127
+ "semantic_type": "numeric",
128
+ "nullable": false,
129
+ "missing_tokens": [],
130
+ "parse_format": null,
131
+ "impute_strategy": "median",
132
+ "profile_stats": {
133
+ "missing_rate": 0.0,
134
+ "unique_count": 31,
135
+ "unique_ratio": 0.000325,
136
+ "example_values": [
137
+ "14",
138
+ "8",
139
+ "3",
140
+ "13",
141
+ "21"
142
+ ]
143
+ }
144
+ },
145
+ {
146
+ "name": "stays_in_weekend_nights",
147
+ "role": "feature",
148
+ "semantic_type": "numeric",
149
+ "nullable": false,
150
+ "missing_tokens": [],
151
+ "parse_format": null,
152
+ "impute_strategy": "median",
153
+ "profile_stats": {
154
+ "missing_rate": 0.0,
155
+ "unique_count": 17,
156
+ "unique_ratio": 0.000178,
157
+ "example_values": [
158
+ "0",
159
+ "2",
160
+ "1",
161
+ "4",
162
+ "3"
163
+ ]
164
+ }
165
+ },
166
+ {
167
+ "name": "stays_in_week_nights",
168
+ "role": "feature",
169
+ "semantic_type": "numeric",
170
+ "nullable": false,
171
+ "missing_tokens": [],
172
+ "parse_format": null,
173
+ "impute_strategy": "median",
174
+ "profile_stats": {
175
+ "missing_rate": 0.0,
176
+ "unique_count": 35,
177
+ "unique_ratio": 0.000366,
178
+ "example_values": [
179
+ "1",
180
+ "3",
181
+ "4",
182
+ "2",
183
+ "0"
184
+ ]
185
+ }
186
+ },
187
+ {
188
+ "name": "adults",
189
+ "role": "feature",
190
+ "semantic_type": "numeric",
191
+ "nullable": false,
192
+ "missing_tokens": [],
193
+ "parse_format": null,
194
+ "impute_strategy": "median",
195
+ "profile_stats": {
196
+ "missing_rate": 0.0,
197
+ "unique_count": 14,
198
+ "unique_ratio": 0.000147,
199
+ "example_values": [
200
+ "1",
201
+ "2",
202
+ "3",
203
+ "0",
204
+ "4"
205
+ ]
206
+ }
207
+ },
208
+ {
209
+ "name": "children",
210
+ "role": "feature",
211
+ "semantic_type": "numeric",
212
+ "nullable": true,
213
+ "missing_tokens": [
214
+ "NA"
215
+ ],
216
+ "parse_format": null,
217
+ "impute_strategy": "median",
218
+ "profile_stats": {
219
+ "missing_rate": 1e-05,
220
+ "unique_count": 5,
221
+ "unique_ratio": 5.2e-05,
222
+ "example_values": [
223
+ "0",
224
+ "1",
225
+ "2",
226
+ "3",
227
+ "10"
228
+ ]
229
+ }
230
+ },
231
+ {
232
+ "name": "babies",
233
+ "role": "feature",
234
+ "semantic_type": "boolean",
235
+ "nullable": false,
236
+ "missing_tokens": [],
237
+ "parse_format": null,
238
+ "impute_strategy": "mode",
239
+ "profile_stats": {
240
+ "missing_rate": 0.0,
241
+ "unique_count": 4,
242
+ "unique_ratio": 4.2e-05,
243
+ "example_values": [
244
+ "0",
245
+ "1",
246
+ "2",
247
+ "10"
248
+ ]
249
+ }
250
+ },
251
+ {
252
+ "name": "meal",
253
+ "role": "feature",
254
+ "semantic_type": "categorical",
255
+ "nullable": false,
256
+ "missing_tokens": [],
257
+ "parse_format": null,
258
+ "impute_strategy": "mode",
259
+ "profile_stats": {
260
+ "missing_rate": 0.0,
261
+ "unique_count": 5,
262
+ "unique_ratio": 5.2e-05,
263
+ "example_values": [
264
+ "BB",
265
+ "SC",
266
+ "HB",
267
+ "Undefined",
268
+ "FB"
269
+ ]
270
+ }
271
+ },
272
+ {
273
+ "name": "country",
274
+ "role": "feature",
275
+ "semantic_type": "categorical",
276
+ "nullable": true,
277
+ "missing_tokens": [
278
+ "NULL"
279
+ ],
280
+ "parse_format": null,
281
+ "impute_strategy": "mode",
282
+ "profile_stats": {
283
+ "missing_rate": 0.003958,
284
+ "unique_count": 175,
285
+ "unique_ratio": 0.00184,
286
+ "example_values": [
287
+ "PRT",
288
+ "ESP",
289
+ "USA",
290
+ "ITA",
291
+ "POL"
292
+ ]
293
+ }
294
+ },
295
+ {
296
+ "name": "market_segment",
297
+ "role": "feature",
298
+ "semantic_type": "text",
299
+ "nullable": false,
300
+ "missing_tokens": [],
301
+ "parse_format": null,
302
+ "impute_strategy": "keep_raw",
303
+ "profile_stats": {
304
+ "missing_rate": 0.0,
305
+ "unique_count": 7,
306
+ "unique_ratio": 7.3e-05,
307
+ "example_values": [
308
+ "Offline TA/TO",
309
+ "Corporate",
310
+ "Groups",
311
+ "Direct",
312
+ "Online TA"
313
+ ]
314
+ }
315
+ },
316
+ {
317
+ "name": "distribution_channel",
318
+ "role": "feature",
319
+ "semantic_type": "categorical",
320
+ "nullable": false,
321
+ "missing_tokens": [],
322
+ "parse_format": null,
323
+ "impute_strategy": "mode",
324
+ "profile_stats": {
325
+ "missing_rate": 0.0,
326
+ "unique_count": 5,
327
+ "unique_ratio": 5.2e-05,
328
+ "example_values": [
329
+ "TA/TO",
330
+ "Corporate",
331
+ "Direct",
332
+ "GDS",
333
+ "Undefined"
334
+ ]
335
+ }
336
+ },
337
+ {
338
+ "name": "is_repeated_guest",
339
+ "role": "feature",
340
+ "semantic_type": "boolean",
341
+ "nullable": false,
342
+ "missing_tokens": [],
343
+ "parse_format": null,
344
+ "impute_strategy": "mode",
345
+ "profile_stats": {
346
+ "missing_rate": 0.0,
347
+ "unique_count": 2,
348
+ "unique_ratio": 2.1e-05,
349
+ "example_values": [
350
+ "0",
351
+ "1"
352
+ ]
353
+ }
354
+ },
355
+ {
356
+ "name": "previous_cancellations",
357
+ "role": "feature",
358
+ "semantic_type": "boolean",
359
+ "nullable": false,
360
+ "missing_tokens": [],
361
+ "parse_format": null,
362
+ "impute_strategy": "mode",
363
+ "profile_stats": {
364
+ "missing_rate": 0.0,
365
+ "unique_count": 15,
366
+ "unique_ratio": 0.000157,
367
+ "example_values": [
368
+ "0",
369
+ "1",
370
+ "2",
371
+ "19",
372
+ "24"
373
+ ]
374
+ }
375
+ },
376
+ {
377
+ "name": "previous_bookings_not_canceled",
378
+ "role": "feature",
379
+ "semantic_type": "boolean",
380
+ "nullable": false,
381
+ "missing_tokens": [],
382
+ "parse_format": null,
383
+ "impute_strategy": "mode",
384
+ "profile_stats": {
385
+ "missing_rate": 0.0,
386
+ "unique_count": 66,
387
+ "unique_ratio": 0.000691,
388
+ "example_values": [
389
+ "0",
390
+ "3",
391
+ "4",
392
+ "12",
393
+ "8"
394
+ ]
395
+ }
396
+ },
397
+ {
398
+ "name": "reserved_room_type",
399
+ "role": "feature",
400
+ "semantic_type": "categorical",
401
+ "nullable": false,
402
+ "missing_tokens": [],
403
+ "parse_format": null,
404
+ "impute_strategy": "mode",
405
+ "profile_stats": {
406
+ "missing_rate": 0.0,
407
+ "unique_count": 10,
408
+ "unique_ratio": 0.000105,
409
+ "example_values": [
410
+ "A",
411
+ "D",
412
+ "E",
413
+ "H",
414
+ "B"
415
+ ]
416
+ }
417
+ },
418
+ {
419
+ "name": "assigned_room_type",
420
+ "role": "feature",
421
+ "semantic_type": "categorical",
422
+ "nullable": false,
423
+ "missing_tokens": [],
424
+ "parse_format": null,
425
+ "impute_strategy": "mode",
426
+ "profile_stats": {
427
+ "missing_rate": 0.0,
428
+ "unique_count": 12,
429
+ "unique_ratio": 0.000126,
430
+ "example_values": [
431
+ "D",
432
+ "A",
433
+ "E",
434
+ "H",
435
+ "F"
436
+ ]
437
+ }
438
+ },
439
+ {
440
+ "name": "booking_changes",
441
+ "role": "feature",
442
+ "semantic_type": "numeric",
443
+ "nullable": false,
444
+ "missing_tokens": [],
445
+ "parse_format": null,
446
+ "impute_strategy": "median",
447
+ "profile_stats": {
448
+ "missing_rate": 0.0,
449
+ "unique_count": 21,
450
+ "unique_ratio": 0.00022,
451
+ "example_values": [
452
+ "0",
453
+ "1",
454
+ "5",
455
+ "2",
456
+ "3"
457
+ ]
458
+ }
459
+ },
460
+ {
461
+ "name": "deposit_type",
462
+ "role": "feature",
463
+ "semantic_type": "text",
464
+ "nullable": false,
465
+ "missing_tokens": [],
466
+ "parse_format": null,
467
+ "impute_strategy": "keep_raw",
468
+ "profile_stats": {
469
+ "missing_rate": 0.0,
470
+ "unique_count": 3,
471
+ "unique_ratio": 3.1e-05,
472
+ "example_values": [
473
+ "No Deposit",
474
+ "Non Refund",
475
+ "Refundable"
476
+ ]
477
+ }
478
+ },
479
+ {
480
+ "name": "agent",
481
+ "role": "feature",
482
+ "semantic_type": "numeric",
483
+ "nullable": true,
484
+ "missing_tokens": [
485
+ "NULL"
486
+ ],
487
+ "parse_format": null,
488
+ "impute_strategy": "median",
489
+ "profile_stats": {
490
+ "missing_rate": 0.136559,
491
+ "unique_count": 323,
492
+ "unique_ratio": 0.003917,
493
+ "example_values": [
494
+ "77",
495
+ "286",
496
+ "7",
497
+ "34",
498
+ "170"
499
+ ]
500
+ }
501
+ },
502
+ {
503
+ "name": "company",
504
+ "role": "feature",
505
+ "semantic_type": "numeric",
506
+ "nullable": true,
507
+ "missing_tokens": [
508
+ "NULL"
509
+ ],
510
+ "parse_format": null,
511
+ "impute_strategy": "median",
512
+ "profile_stats": {
513
+ "missing_rate": 0.943578,
514
+ "unique_count": 337,
515
+ "unique_ratio": 0.062535,
516
+ "example_values": [
517
+ "362",
518
+ "94",
519
+ "153",
520
+ "67",
521
+ "223"
522
+ ]
523
+ }
524
+ },
525
+ {
526
+ "name": "days_in_waiting_list",
527
+ "role": "feature",
528
+ "semantic_type": "numeric",
529
+ "nullable": false,
530
+ "missing_tokens": [],
531
+ "parse_format": null,
532
+ "impute_strategy": "median",
533
+ "profile_stats": {
534
+ "missing_rate": 0.0,
535
+ "unique_count": 124,
536
+ "unique_ratio": 0.001298,
537
+ "example_values": [
538
+ "0",
539
+ "39",
540
+ "22",
541
+ "108",
542
+ "101"
543
+ ]
544
+ }
545
+ },
546
+ {
547
+ "name": "customer_type",
548
+ "role": "target",
549
+ "semantic_type": "categorical",
550
+ "nullable": false,
551
+ "missing_tokens": [],
552
+ "parse_format": null,
553
+ "impute_strategy": "mode",
554
+ "profile_stats": {
555
+ "missing_rate": 0.0,
556
+ "unique_count": 4,
557
+ "unique_ratio": 4.2e-05,
558
+ "example_values": [
559
+ "Transient-Party",
560
+ "Transient",
561
+ "Contract",
562
+ "Group"
563
+ ]
564
+ }
565
+ },
566
+ {
567
+ "name": "adr",
568
+ "role": "feature",
569
+ "semantic_type": "numeric",
570
+ "nullable": false,
571
+ "missing_tokens": [],
572
+ "parse_format": null,
573
+ "impute_strategy": "median",
574
+ "profile_stats": {
575
+ "missing_rate": 0.0,
576
+ "unique_count": 8008,
577
+ "unique_ratio": 0.083843,
578
+ "example_values": [
579
+ "120",
580
+ "161.88",
581
+ "100",
582
+ "161.1",
583
+ "116.8"
584
+ ]
585
+ }
586
+ },
587
+ {
588
+ "name": "required_car_parking_spaces",
589
+ "role": "feature",
590
+ "semantic_type": "boolean",
591
+ "nullable": false,
592
+ "missing_tokens": [],
593
+ "parse_format": null,
594
+ "impute_strategy": "mode",
595
+ "profile_stats": {
596
+ "missing_rate": 0.0,
597
+ "unique_count": 5,
598
+ "unique_ratio": 5.2e-05,
599
+ "example_values": [
600
+ "0",
601
+ "1",
602
+ "2",
603
+ "3",
604
+ "8"
605
+ ]
606
+ }
607
+ },
608
+ {
609
+ "name": "total_of_special_requests",
610
+ "role": "feature",
611
+ "semantic_type": "numeric",
612
+ "nullable": false,
613
+ "missing_tokens": [],
614
+ "parse_format": null,
615
+ "impute_strategy": "median",
616
+ "profile_stats": {
617
+ "missing_rate": 0.0,
618
+ "unique_count": 6,
619
+ "unique_ratio": 6.3e-05,
620
+ "example_values": [
621
+ "0",
622
+ "1",
623
+ "2",
624
+ "3",
625
+ "5"
626
+ ]
627
+ }
628
+ },
629
+ {
630
+ "name": "reservation_status",
631
+ "role": "feature",
632
+ "semantic_type": "categorical",
633
+ "nullable": false,
634
+ "missing_tokens": [],
635
+ "parse_format": null,
636
+ "impute_strategy": "mode",
637
+ "profile_stats": {
638
+ "missing_rate": 0.0,
639
+ "unique_count": 3,
640
+ "unique_ratio": 3.1e-05,
641
+ "example_values": [
642
+ "Check-Out",
643
+ "Canceled",
644
+ "No-Show"
645
+ ]
646
+ }
647
+ },
648
+ {
649
+ "name": "reservation_status_date",
650
+ "role": "feature",
651
+ "semantic_type": "datetime",
652
+ "nullable": false,
653
+ "missing_tokens": [],
654
+ "parse_format": "%Y-%m-%d",
655
+ "impute_strategy": "keep_raw",
656
+ "profile_stats": {
657
+ "missing_rate": 0.0,
658
+ "unique_count": 920,
659
+ "unique_ratio": 0.009632,
660
+ "example_values": [
661
+ "2016-10-15",
662
+ "2016-11-09",
663
+ "2016-12-02",
664
+ "2016-06-21",
665
+ "2016-10-23"
666
+ ]
667
+ }
668
+ }
669
+ ]
670
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/public_gate_report.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "m12",
3
+ "status": "pass",
4
+ "checks": [
5
+ {
6
+ "check_id": "PG001_csv_parse_ok",
7
+ "status": "pass"
8
+ },
9
+ {
10
+ "check_id": "PG002_split_header_consistent",
11
+ "status": "pass"
12
+ },
13
+ {
14
+ "check_id": "PG003_profile_header_match",
15
+ "status": "pass"
16
+ },
17
+ {
18
+ "check_id": "PG004_missing_token_normalized",
19
+ "status": "pass"
20
+ },
21
+ {
22
+ "check_id": "PG005_semantic_type_validated",
23
+ "status": "pass"
24
+ },
25
+ {
26
+ "check_id": "PG006_target_defined_and_valid",
27
+ "status": "pass"
28
+ }
29
+ ],
30
+ "target_column": "customer_type",
31
+ "task_type": "classification",
32
+ "input_splits": {
33
+ "train": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/m12/m12-train.csv",
34
+ "val": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/m12/m12-val.csv",
35
+ "test": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/m12/m12-test.csv"
36
+ }
37
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/staged_input_manifest.json ADDED
@@ -0,0 +1,675 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "m12",
3
+ "target_column": "customer_type",
4
+ "task_type": "classification",
5
+ "train_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/train.csv",
6
+ "val_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/val.csv",
7
+ "test_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/test.csv",
8
+ "features_json": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/staged_features.json",
9
+ "public_gate_report": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/public_gate_report.json",
10
+ "column_schema": [
11
+ {
12
+ "name": "hotel",
13
+ "role": "feature",
14
+ "semantic_type": "text",
15
+ "nullable": false,
16
+ "missing_tokens": [],
17
+ "parse_format": null,
18
+ "impute_strategy": "keep_raw",
19
+ "profile_stats": {
20
+ "missing_rate": 0.0,
21
+ "unique_count": 2,
22
+ "unique_ratio": 2.1e-05,
23
+ "example_values": [
24
+ "City Hotel",
25
+ "Resort Hotel"
26
+ ]
27
+ }
28
+ },
29
+ {
30
+ "name": "is_canceled",
31
+ "role": "feature",
32
+ "semantic_type": "boolean",
33
+ "nullable": false,
34
+ "missing_tokens": [],
35
+ "parse_format": null,
36
+ "impute_strategy": "mode",
37
+ "profile_stats": {
38
+ "missing_rate": 0.0,
39
+ "unique_count": 2,
40
+ "unique_ratio": 2.1e-05,
41
+ "example_values": [
42
+ "0",
43
+ "1"
44
+ ]
45
+ }
46
+ },
47
+ {
48
+ "name": "lead_time",
49
+ "role": "feature",
50
+ "semantic_type": "numeric",
51
+ "nullable": false,
52
+ "missing_tokens": [],
53
+ "parse_format": null,
54
+ "impute_strategy": "median",
55
+ "profile_stats": {
56
+ "missing_rate": 0.0,
57
+ "unique_count": 476,
58
+ "unique_ratio": 0.004984,
59
+ "example_values": [
60
+ "53",
61
+ "1",
62
+ "152",
63
+ "23",
64
+ "7"
65
+ ]
66
+ }
67
+ },
68
+ {
69
+ "name": "arrival_date_year",
70
+ "role": "feature",
71
+ "semantic_type": "numeric",
72
+ "nullable": false,
73
+ "missing_tokens": [],
74
+ "parse_format": null,
75
+ "impute_strategy": "median",
76
+ "profile_stats": {
77
+ "missing_rate": 0.0,
78
+ "unique_count": 3,
79
+ "unique_ratio": 3.1e-05,
80
+ "example_values": [
81
+ "2016",
82
+ "2017",
83
+ "2015"
84
+ ]
85
+ }
86
+ },
87
+ {
88
+ "name": "arrival_date_month",
89
+ "role": "feature",
90
+ "semantic_type": "categorical",
91
+ "nullable": false,
92
+ "missing_tokens": [],
93
+ "parse_format": null,
94
+ "impute_strategy": "mode",
95
+ "profile_stats": {
96
+ "missing_rate": 0.0,
97
+ "unique_count": 12,
98
+ "unique_ratio": 0.000126,
99
+ "example_values": [
100
+ "October",
101
+ "November",
102
+ "May",
103
+ "July",
104
+ "December"
105
+ ]
106
+ }
107
+ },
108
+ {
109
+ "name": "arrival_date_week_number",
110
+ "role": "feature",
111
+ "semantic_type": "numeric",
112
+ "nullable": false,
113
+ "missing_tokens": [],
114
+ "parse_format": null,
115
+ "impute_strategy": "median",
116
+ "profile_stats": {
117
+ "missing_rate": 0.0,
118
+ "unique_count": 53,
119
+ "unique_ratio": 0.000555,
120
+ "example_values": [
121
+ "42",
122
+ "46",
123
+ "18",
124
+ "29",
125
+ "43"
126
+ ]
127
+ }
128
+ },
129
+ {
130
+ "name": "arrival_date_day_of_month",
131
+ "role": "feature",
132
+ "semantic_type": "numeric",
133
+ "nullable": false,
134
+ "missing_tokens": [],
135
+ "parse_format": null,
136
+ "impute_strategy": "median",
137
+ "profile_stats": {
138
+ "missing_rate": 0.0,
139
+ "unique_count": 31,
140
+ "unique_ratio": 0.000325,
141
+ "example_values": [
142
+ "14",
143
+ "8",
144
+ "3",
145
+ "13",
146
+ "21"
147
+ ]
148
+ }
149
+ },
150
+ {
151
+ "name": "stays_in_weekend_nights",
152
+ "role": "feature",
153
+ "semantic_type": "numeric",
154
+ "nullable": false,
155
+ "missing_tokens": [],
156
+ "parse_format": null,
157
+ "impute_strategy": "median",
158
+ "profile_stats": {
159
+ "missing_rate": 0.0,
160
+ "unique_count": 17,
161
+ "unique_ratio": 0.000178,
162
+ "example_values": [
163
+ "0",
164
+ "2",
165
+ "1",
166
+ "4",
167
+ "3"
168
+ ]
169
+ }
170
+ },
171
+ {
172
+ "name": "stays_in_week_nights",
173
+ "role": "feature",
174
+ "semantic_type": "numeric",
175
+ "nullable": false,
176
+ "missing_tokens": [],
177
+ "parse_format": null,
178
+ "impute_strategy": "median",
179
+ "profile_stats": {
180
+ "missing_rate": 0.0,
181
+ "unique_count": 35,
182
+ "unique_ratio": 0.000366,
183
+ "example_values": [
184
+ "1",
185
+ "3",
186
+ "4",
187
+ "2",
188
+ "0"
189
+ ]
190
+ }
191
+ },
192
+ {
193
+ "name": "adults",
194
+ "role": "feature",
195
+ "semantic_type": "numeric",
196
+ "nullable": false,
197
+ "missing_tokens": [],
198
+ "parse_format": null,
199
+ "impute_strategy": "median",
200
+ "profile_stats": {
201
+ "missing_rate": 0.0,
202
+ "unique_count": 14,
203
+ "unique_ratio": 0.000147,
204
+ "example_values": [
205
+ "1",
206
+ "2",
207
+ "3",
208
+ "0",
209
+ "4"
210
+ ]
211
+ }
212
+ },
213
+ {
214
+ "name": "children",
215
+ "role": "feature",
216
+ "semantic_type": "numeric",
217
+ "nullable": true,
218
+ "missing_tokens": [
219
+ "NA"
220
+ ],
221
+ "parse_format": null,
222
+ "impute_strategy": "median",
223
+ "profile_stats": {
224
+ "missing_rate": 1e-05,
225
+ "unique_count": 5,
226
+ "unique_ratio": 5.2e-05,
227
+ "example_values": [
228
+ "0",
229
+ "1",
230
+ "2",
231
+ "3",
232
+ "10"
233
+ ]
234
+ }
235
+ },
236
+ {
237
+ "name": "babies",
238
+ "role": "feature",
239
+ "semantic_type": "boolean",
240
+ "nullable": false,
241
+ "missing_tokens": [],
242
+ "parse_format": null,
243
+ "impute_strategy": "mode",
244
+ "profile_stats": {
245
+ "missing_rate": 0.0,
246
+ "unique_count": 4,
247
+ "unique_ratio": 4.2e-05,
248
+ "example_values": [
249
+ "0",
250
+ "1",
251
+ "2",
252
+ "10"
253
+ ]
254
+ }
255
+ },
256
+ {
257
+ "name": "meal",
258
+ "role": "feature",
259
+ "semantic_type": "categorical",
260
+ "nullable": false,
261
+ "missing_tokens": [],
262
+ "parse_format": null,
263
+ "impute_strategy": "mode",
264
+ "profile_stats": {
265
+ "missing_rate": 0.0,
266
+ "unique_count": 5,
267
+ "unique_ratio": 5.2e-05,
268
+ "example_values": [
269
+ "BB",
270
+ "SC",
271
+ "HB",
272
+ "Undefined",
273
+ "FB"
274
+ ]
275
+ }
276
+ },
277
+ {
278
+ "name": "country",
279
+ "role": "feature",
280
+ "semantic_type": "categorical",
281
+ "nullable": true,
282
+ "missing_tokens": [
283
+ "NULL"
284
+ ],
285
+ "parse_format": null,
286
+ "impute_strategy": "mode",
287
+ "profile_stats": {
288
+ "missing_rate": 0.003958,
289
+ "unique_count": 175,
290
+ "unique_ratio": 0.00184,
291
+ "example_values": [
292
+ "PRT",
293
+ "ESP",
294
+ "USA",
295
+ "ITA",
296
+ "POL"
297
+ ]
298
+ }
299
+ },
300
+ {
301
+ "name": "market_segment",
302
+ "role": "feature",
303
+ "semantic_type": "text",
304
+ "nullable": false,
305
+ "missing_tokens": [],
306
+ "parse_format": null,
307
+ "impute_strategy": "keep_raw",
308
+ "profile_stats": {
309
+ "missing_rate": 0.0,
310
+ "unique_count": 7,
311
+ "unique_ratio": 7.3e-05,
312
+ "example_values": [
313
+ "Offline TA/TO",
314
+ "Corporate",
315
+ "Groups",
316
+ "Direct",
317
+ "Online TA"
318
+ ]
319
+ }
320
+ },
321
+ {
322
+ "name": "distribution_channel",
323
+ "role": "feature",
324
+ "semantic_type": "categorical",
325
+ "nullable": false,
326
+ "missing_tokens": [],
327
+ "parse_format": null,
328
+ "impute_strategy": "mode",
329
+ "profile_stats": {
330
+ "missing_rate": 0.0,
331
+ "unique_count": 5,
332
+ "unique_ratio": 5.2e-05,
333
+ "example_values": [
334
+ "TA/TO",
335
+ "Corporate",
336
+ "Direct",
337
+ "GDS",
338
+ "Undefined"
339
+ ]
340
+ }
341
+ },
342
+ {
343
+ "name": "is_repeated_guest",
344
+ "role": "feature",
345
+ "semantic_type": "boolean",
346
+ "nullable": false,
347
+ "missing_tokens": [],
348
+ "parse_format": null,
349
+ "impute_strategy": "mode",
350
+ "profile_stats": {
351
+ "missing_rate": 0.0,
352
+ "unique_count": 2,
353
+ "unique_ratio": 2.1e-05,
354
+ "example_values": [
355
+ "0",
356
+ "1"
357
+ ]
358
+ }
359
+ },
360
+ {
361
+ "name": "previous_cancellations",
362
+ "role": "feature",
363
+ "semantic_type": "boolean",
364
+ "nullable": false,
365
+ "missing_tokens": [],
366
+ "parse_format": null,
367
+ "impute_strategy": "mode",
368
+ "profile_stats": {
369
+ "missing_rate": 0.0,
370
+ "unique_count": 15,
371
+ "unique_ratio": 0.000157,
372
+ "example_values": [
373
+ "0",
374
+ "1",
375
+ "2",
376
+ "19",
377
+ "24"
378
+ ]
379
+ }
380
+ },
381
+ {
382
+ "name": "previous_bookings_not_canceled",
383
+ "role": "feature",
384
+ "semantic_type": "boolean",
385
+ "nullable": false,
386
+ "missing_tokens": [],
387
+ "parse_format": null,
388
+ "impute_strategy": "mode",
389
+ "profile_stats": {
390
+ "missing_rate": 0.0,
391
+ "unique_count": 66,
392
+ "unique_ratio": 0.000691,
393
+ "example_values": [
394
+ "0",
395
+ "3",
396
+ "4",
397
+ "12",
398
+ "8"
399
+ ]
400
+ }
401
+ },
402
+ {
403
+ "name": "reserved_room_type",
404
+ "role": "feature",
405
+ "semantic_type": "categorical",
406
+ "nullable": false,
407
+ "missing_tokens": [],
408
+ "parse_format": null,
409
+ "impute_strategy": "mode",
410
+ "profile_stats": {
411
+ "missing_rate": 0.0,
412
+ "unique_count": 10,
413
+ "unique_ratio": 0.000105,
414
+ "example_values": [
415
+ "A",
416
+ "D",
417
+ "E",
418
+ "H",
419
+ "B"
420
+ ]
421
+ }
422
+ },
423
+ {
424
+ "name": "assigned_room_type",
425
+ "role": "feature",
426
+ "semantic_type": "categorical",
427
+ "nullable": false,
428
+ "missing_tokens": [],
429
+ "parse_format": null,
430
+ "impute_strategy": "mode",
431
+ "profile_stats": {
432
+ "missing_rate": 0.0,
433
+ "unique_count": 12,
434
+ "unique_ratio": 0.000126,
435
+ "example_values": [
436
+ "D",
437
+ "A",
438
+ "E",
439
+ "H",
440
+ "F"
441
+ ]
442
+ }
443
+ },
444
+ {
445
+ "name": "booking_changes",
446
+ "role": "feature",
447
+ "semantic_type": "numeric",
448
+ "nullable": false,
449
+ "missing_tokens": [],
450
+ "parse_format": null,
451
+ "impute_strategy": "median",
452
+ "profile_stats": {
453
+ "missing_rate": 0.0,
454
+ "unique_count": 21,
455
+ "unique_ratio": 0.00022,
456
+ "example_values": [
457
+ "0",
458
+ "1",
459
+ "5",
460
+ "2",
461
+ "3"
462
+ ]
463
+ }
464
+ },
465
+ {
466
+ "name": "deposit_type",
467
+ "role": "feature",
468
+ "semantic_type": "text",
469
+ "nullable": false,
470
+ "missing_tokens": [],
471
+ "parse_format": null,
472
+ "impute_strategy": "keep_raw",
473
+ "profile_stats": {
474
+ "missing_rate": 0.0,
475
+ "unique_count": 3,
476
+ "unique_ratio": 3.1e-05,
477
+ "example_values": [
478
+ "No Deposit",
479
+ "Non Refund",
480
+ "Refundable"
481
+ ]
482
+ }
483
+ },
484
+ {
485
+ "name": "agent",
486
+ "role": "feature",
487
+ "semantic_type": "numeric",
488
+ "nullable": true,
489
+ "missing_tokens": [
490
+ "NULL"
491
+ ],
492
+ "parse_format": null,
493
+ "impute_strategy": "median",
494
+ "profile_stats": {
495
+ "missing_rate": 0.136559,
496
+ "unique_count": 323,
497
+ "unique_ratio": 0.003917,
498
+ "example_values": [
499
+ "77",
500
+ "286",
501
+ "7",
502
+ "34",
503
+ "170"
504
+ ]
505
+ }
506
+ },
507
+ {
508
+ "name": "company",
509
+ "role": "feature",
510
+ "semantic_type": "numeric",
511
+ "nullable": true,
512
+ "missing_tokens": [
513
+ "NULL"
514
+ ],
515
+ "parse_format": null,
516
+ "impute_strategy": "median",
517
+ "profile_stats": {
518
+ "missing_rate": 0.943578,
519
+ "unique_count": 337,
520
+ "unique_ratio": 0.062535,
521
+ "example_values": [
522
+ "362",
523
+ "94",
524
+ "153",
525
+ "67",
526
+ "223"
527
+ ]
528
+ }
529
+ },
530
+ {
531
+ "name": "days_in_waiting_list",
532
+ "role": "feature",
533
+ "semantic_type": "numeric",
534
+ "nullable": false,
535
+ "missing_tokens": [],
536
+ "parse_format": null,
537
+ "impute_strategy": "median",
538
+ "profile_stats": {
539
+ "missing_rate": 0.0,
540
+ "unique_count": 124,
541
+ "unique_ratio": 0.001298,
542
+ "example_values": [
543
+ "0",
544
+ "39",
545
+ "22",
546
+ "108",
547
+ "101"
548
+ ]
549
+ }
550
+ },
551
+ {
552
+ "name": "customer_type",
553
+ "role": "target",
554
+ "semantic_type": "categorical",
555
+ "nullable": false,
556
+ "missing_tokens": [],
557
+ "parse_format": null,
558
+ "impute_strategy": "mode",
559
+ "profile_stats": {
560
+ "missing_rate": 0.0,
561
+ "unique_count": 4,
562
+ "unique_ratio": 4.2e-05,
563
+ "example_values": [
564
+ "Transient-Party",
565
+ "Transient",
566
+ "Contract",
567
+ "Group"
568
+ ]
569
+ }
570
+ },
571
+ {
572
+ "name": "adr",
573
+ "role": "feature",
574
+ "semantic_type": "numeric",
575
+ "nullable": false,
576
+ "missing_tokens": [],
577
+ "parse_format": null,
578
+ "impute_strategy": "median",
579
+ "profile_stats": {
580
+ "missing_rate": 0.0,
581
+ "unique_count": 8008,
582
+ "unique_ratio": 0.083843,
583
+ "example_values": [
584
+ "120",
585
+ "161.88",
586
+ "100",
587
+ "161.1",
588
+ "116.8"
589
+ ]
590
+ }
591
+ },
592
+ {
593
+ "name": "required_car_parking_spaces",
594
+ "role": "feature",
595
+ "semantic_type": "boolean",
596
+ "nullable": false,
597
+ "missing_tokens": [],
598
+ "parse_format": null,
599
+ "impute_strategy": "mode",
600
+ "profile_stats": {
601
+ "missing_rate": 0.0,
602
+ "unique_count": 5,
603
+ "unique_ratio": 5.2e-05,
604
+ "example_values": [
605
+ "0",
606
+ "1",
607
+ "2",
608
+ "3",
609
+ "8"
610
+ ]
611
+ }
612
+ },
613
+ {
614
+ "name": "total_of_special_requests",
615
+ "role": "feature",
616
+ "semantic_type": "numeric",
617
+ "nullable": false,
618
+ "missing_tokens": [],
619
+ "parse_format": null,
620
+ "impute_strategy": "median",
621
+ "profile_stats": {
622
+ "missing_rate": 0.0,
623
+ "unique_count": 6,
624
+ "unique_ratio": 6.3e-05,
625
+ "example_values": [
626
+ "0",
627
+ "1",
628
+ "2",
629
+ "3",
630
+ "5"
631
+ ]
632
+ }
633
+ },
634
+ {
635
+ "name": "reservation_status",
636
+ "role": "feature",
637
+ "semantic_type": "categorical",
638
+ "nullable": false,
639
+ "missing_tokens": [],
640
+ "parse_format": null,
641
+ "impute_strategy": "mode",
642
+ "profile_stats": {
643
+ "missing_rate": 0.0,
644
+ "unique_count": 3,
645
+ "unique_ratio": 3.1e-05,
646
+ "example_values": [
647
+ "Check-Out",
648
+ "Canceled",
649
+ "No-Show"
650
+ ]
651
+ }
652
+ },
653
+ {
654
+ "name": "reservation_status_date",
655
+ "role": "feature",
656
+ "semantic_type": "datetime",
657
+ "nullable": false,
658
+ "missing_tokens": [],
659
+ "parse_format": "%Y-%m-%d",
660
+ "impute_strategy": "keep_raw",
661
+ "profile_stats": {
662
+ "missing_rate": 0.0,
663
+ "unique_count": 920,
664
+ "unique_ratio": 0.009632,
665
+ "example_values": [
666
+ "2016-10-15",
667
+ "2016-11-09",
668
+ "2016-12-02",
669
+ "2016-06-21",
670
+ "2016-10-23"
671
+ ]
672
+ }
673
+ }
674
+ ]
675
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/run_config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "recorded_at": "2026-05-10T21:55:03",
4
+ "dataset_id": "m12",
5
+ "model": "tabddpm",
6
+ "work_dir": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502",
7
+ "dataset_source_requested": "new",
8
+ "dataset_source_resolved": "new",
9
+ "cli_args": {
10
+ "model": "tabddpm",
11
+ "dataset": "m12",
12
+ "dataset_source": "new",
13
+ "train": true,
14
+ "generate": true,
15
+ "num_rows": 0,
16
+ "epochs": null,
17
+ "output_dir": null,
18
+ "model_dir": null,
19
+ "work_dir": null,
20
+ "resume": false,
21
+ "no_stats": false
22
+ },
23
+ "resolved": {
24
+ "num_rows": 95512,
25
+ "model_path": null,
26
+ "output_csv": null
27
+ },
28
+ "input_artifacts": {
29
+ "public_gate_report": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/public_gate_report.json",
30
+ "public_manifest": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/staged_input_manifest.json",
31
+ "model_manifest": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/tabddpm/model_input_manifest.json",
32
+ "train_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/train.csv",
33
+ "features_json": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/staged_features.json",
34
+ "target_column": "customer_type",
35
+ "task_type": "classification"
36
+ },
37
+ "env_overrides": {
38
+ "BENCHMARK_TABDDPM_GPUS": "device=3",
39
+ "TABDDPM_NUM_TIMESTEPS": "200",
40
+ "TABDDPM_SAMPLE_BATCH_SIZE": "256",
41
+ "TABDDPM_STEPS_PER_EPOCH": "40",
42
+ "TABDDPM_TRAIN_BATCH_SIZE": "256",
43
+ "TABDDPM_TRAIN_LR": "0.001"
44
+ }
45
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/runtime_result.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "m12",
3
+ "model": "tabddpm",
4
+ "run_id": "tabddpm-m12-20260510_215502",
5
+ "public_gate_status": "pass",
6
+ "adapter_ready_status": "pass",
7
+ "train_status": "fail",
8
+ "generate_status": "skipped",
9
+ "reason_code": "adapter_runtime_error",
10
+ "reason_detail": "Command '['docker', 'run', '--rm', '--init', '--user', '1005:1005', '-e', 'HOME=/work/.home', '--cidfile', '/tmp/bench_docker_tabddpm_zvau72c4/container.cid', '--gpus', 'device=3', '-v', '/data/jialinzhang/SynthesizePipeline-server:/work', '-w', '/work', '-v', '/data/jialinzhang/synthetic_benchmark/tabddpm/code:/workspace/tabddpm/code', 'benchmark:tabddpm-zjl', 'python', '/work/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/_tabddpm_train.py']' returned non-zero exit status 1.",
11
+ "artifacts": {},
12
+ "timings": {
13
+ "train": {
14
+ "started_at": "2026-05-10T21:55:03",
15
+ "ended_at": "2026-05-10T21:55:04",
16
+ "duration_sec": 1.513
17
+ },
18
+ "generate": {
19
+ "started_at": null,
20
+ "ended_at": null,
21
+ "duration_sec": null
22
+ }
23
+ }
24
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/staged_features.json ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "feature_name": "hotel",
4
+ "data_type": "categorical",
5
+ "is_target": false
6
+ },
7
+ {
8
+ "feature_name": "is_canceled",
9
+ "data_type": "binary",
10
+ "is_target": false
11
+ },
12
+ {
13
+ "feature_name": "lead_time",
14
+ "data_type": "continuous",
15
+ "is_target": false
16
+ },
17
+ {
18
+ "feature_name": "arrival_date_year",
19
+ "data_type": "continuous",
20
+ "is_target": false
21
+ },
22
+ {
23
+ "feature_name": "arrival_date_month",
24
+ "data_type": "categorical",
25
+ "is_target": false
26
+ },
27
+ {
28
+ "feature_name": "arrival_date_week_number",
29
+ "data_type": "continuous",
30
+ "is_target": false
31
+ },
32
+ {
33
+ "feature_name": "arrival_date_day_of_month",
34
+ "data_type": "continuous",
35
+ "is_target": false
36
+ },
37
+ {
38
+ "feature_name": "stays_in_weekend_nights",
39
+ "data_type": "continuous",
40
+ "is_target": false
41
+ },
42
+ {
43
+ "feature_name": "stays_in_week_nights",
44
+ "data_type": "continuous",
45
+ "is_target": false
46
+ },
47
+ {
48
+ "feature_name": "adults",
49
+ "data_type": "continuous",
50
+ "is_target": false
51
+ },
52
+ {
53
+ "feature_name": "children",
54
+ "data_type": "continuous",
55
+ "is_target": false
56
+ },
57
+ {
58
+ "feature_name": "babies",
59
+ "data_type": "binary",
60
+ "is_target": false
61
+ },
62
+ {
63
+ "feature_name": "meal",
64
+ "data_type": "categorical",
65
+ "is_target": false
66
+ },
67
+ {
68
+ "feature_name": "country",
69
+ "data_type": "categorical",
70
+ "is_target": false
71
+ },
72
+ {
73
+ "feature_name": "market_segment",
74
+ "data_type": "categorical",
75
+ "is_target": false
76
+ },
77
+ {
78
+ "feature_name": "distribution_channel",
79
+ "data_type": "categorical",
80
+ "is_target": false
81
+ },
82
+ {
83
+ "feature_name": "is_repeated_guest",
84
+ "data_type": "binary",
85
+ "is_target": false
86
+ },
87
+ {
88
+ "feature_name": "previous_cancellations",
89
+ "data_type": "binary",
90
+ "is_target": false
91
+ },
92
+ {
93
+ "feature_name": "previous_bookings_not_canceled",
94
+ "data_type": "binary",
95
+ "is_target": false
96
+ },
97
+ {
98
+ "feature_name": "reserved_room_type",
99
+ "data_type": "categorical",
100
+ "is_target": false
101
+ },
102
+ {
103
+ "feature_name": "assigned_room_type",
104
+ "data_type": "categorical",
105
+ "is_target": false
106
+ },
107
+ {
108
+ "feature_name": "booking_changes",
109
+ "data_type": "continuous",
110
+ "is_target": false
111
+ },
112
+ {
113
+ "feature_name": "deposit_type",
114
+ "data_type": "categorical",
115
+ "is_target": false
116
+ },
117
+ {
118
+ "feature_name": "agent",
119
+ "data_type": "continuous",
120
+ "is_target": false
121
+ },
122
+ {
123
+ "feature_name": "company",
124
+ "data_type": "continuous",
125
+ "is_target": false
126
+ },
127
+ {
128
+ "feature_name": "days_in_waiting_list",
129
+ "data_type": "continuous",
130
+ "is_target": false
131
+ },
132
+ {
133
+ "feature_name": "customer_type",
134
+ "data_type": "categorical",
135
+ "is_target": true
136
+ },
137
+ {
138
+ "feature_name": "adr",
139
+ "data_type": "continuous",
140
+ "is_target": false
141
+ },
142
+ {
143
+ "feature_name": "required_car_parking_spaces",
144
+ "data_type": "binary",
145
+ "is_target": false
146
+ },
147
+ {
148
+ "feature_name": "total_of_special_requests",
149
+ "data_type": "continuous",
150
+ "is_target": false
151
+ },
152
+ {
153
+ "feature_name": "reservation_status",
154
+ "data_type": "categorical",
155
+ "is_target": false
156
+ },
157
+ {
158
+ "feature_name": "reservation_status_date",
159
+ "data_type": "timestamp",
160
+ "is_target": false
161
+ }
162
+ ]
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a5f493029a41815df91c3b28f521a2264951567318150110e5c27fa757ebc734
3
+ size 1694120
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3e2f868c246063628371ded60d767d155528ace18d424271c7271617a8ef4643
3
+ size 13548268
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce173da72624b2b531e2d913ada1d29b77c0926be15b8d83a75911a1f5e36679
3
+ size 1694777
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/tabddpm/adapter_report.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "adapter_ready_status": "pass",
3
+ "adapter_fail_reason_code": null,
4
+ "adapter_fail_detail": null,
5
+ "adapter_transforms_applied": [],
6
+ "model_input_manifest": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/tabddpm/model_input_manifest.json"
7
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/tabddpm/adapter_transforms_applied.json ADDED
@@ -0,0 +1 @@
 
 
1
+ []
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/staged/tabddpm/model_input_manifest.json ADDED
@@ -0,0 +1,677 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "m12",
3
+ "model": "tabddpm",
4
+ "target_column": "customer_type",
5
+ "task_type": "classification",
6
+ "column_schema": [
7
+ {
8
+ "name": "hotel",
9
+ "role": "feature",
10
+ "semantic_type": "text",
11
+ "nullable": false,
12
+ "missing_tokens": [],
13
+ "parse_format": null,
14
+ "impute_strategy": "keep_raw",
15
+ "profile_stats": {
16
+ "missing_rate": 0.0,
17
+ "unique_count": 2,
18
+ "unique_ratio": 2.1e-05,
19
+ "example_values": [
20
+ "City Hotel",
21
+ "Resort Hotel"
22
+ ]
23
+ }
24
+ },
25
+ {
26
+ "name": "is_canceled",
27
+ "role": "feature",
28
+ "semantic_type": "boolean",
29
+ "nullable": false,
30
+ "missing_tokens": [],
31
+ "parse_format": null,
32
+ "impute_strategy": "mode",
33
+ "profile_stats": {
34
+ "missing_rate": 0.0,
35
+ "unique_count": 2,
36
+ "unique_ratio": 2.1e-05,
37
+ "example_values": [
38
+ "0",
39
+ "1"
40
+ ]
41
+ }
42
+ },
43
+ {
44
+ "name": "lead_time",
45
+ "role": "feature",
46
+ "semantic_type": "numeric",
47
+ "nullable": false,
48
+ "missing_tokens": [],
49
+ "parse_format": null,
50
+ "impute_strategy": "median",
51
+ "profile_stats": {
52
+ "missing_rate": 0.0,
53
+ "unique_count": 476,
54
+ "unique_ratio": 0.004984,
55
+ "example_values": [
56
+ "53",
57
+ "1",
58
+ "152",
59
+ "23",
60
+ "7"
61
+ ]
62
+ }
63
+ },
64
+ {
65
+ "name": "arrival_date_year",
66
+ "role": "feature",
67
+ "semantic_type": "numeric",
68
+ "nullable": false,
69
+ "missing_tokens": [],
70
+ "parse_format": null,
71
+ "impute_strategy": "median",
72
+ "profile_stats": {
73
+ "missing_rate": 0.0,
74
+ "unique_count": 3,
75
+ "unique_ratio": 3.1e-05,
76
+ "example_values": [
77
+ "2016",
78
+ "2017",
79
+ "2015"
80
+ ]
81
+ }
82
+ },
83
+ {
84
+ "name": "arrival_date_month",
85
+ "role": "feature",
86
+ "semantic_type": "categorical",
87
+ "nullable": false,
88
+ "missing_tokens": [],
89
+ "parse_format": null,
90
+ "impute_strategy": "mode",
91
+ "profile_stats": {
92
+ "missing_rate": 0.0,
93
+ "unique_count": 12,
94
+ "unique_ratio": 0.000126,
95
+ "example_values": [
96
+ "October",
97
+ "November",
98
+ "May",
99
+ "July",
100
+ "December"
101
+ ]
102
+ }
103
+ },
104
+ {
105
+ "name": "arrival_date_week_number",
106
+ "role": "feature",
107
+ "semantic_type": "numeric",
108
+ "nullable": false,
109
+ "missing_tokens": [],
110
+ "parse_format": null,
111
+ "impute_strategy": "median",
112
+ "profile_stats": {
113
+ "missing_rate": 0.0,
114
+ "unique_count": 53,
115
+ "unique_ratio": 0.000555,
116
+ "example_values": [
117
+ "42",
118
+ "46",
119
+ "18",
120
+ "29",
121
+ "43"
122
+ ]
123
+ }
124
+ },
125
+ {
126
+ "name": "arrival_date_day_of_month",
127
+ "role": "feature",
128
+ "semantic_type": "numeric",
129
+ "nullable": false,
130
+ "missing_tokens": [],
131
+ "parse_format": null,
132
+ "impute_strategy": "median",
133
+ "profile_stats": {
134
+ "missing_rate": 0.0,
135
+ "unique_count": 31,
136
+ "unique_ratio": 0.000325,
137
+ "example_values": [
138
+ "14",
139
+ "8",
140
+ "3",
141
+ "13",
142
+ "21"
143
+ ]
144
+ }
145
+ },
146
+ {
147
+ "name": "stays_in_weekend_nights",
148
+ "role": "feature",
149
+ "semantic_type": "numeric",
150
+ "nullable": false,
151
+ "missing_tokens": [],
152
+ "parse_format": null,
153
+ "impute_strategy": "median",
154
+ "profile_stats": {
155
+ "missing_rate": 0.0,
156
+ "unique_count": 17,
157
+ "unique_ratio": 0.000178,
158
+ "example_values": [
159
+ "0",
160
+ "2",
161
+ "1",
162
+ "4",
163
+ "3"
164
+ ]
165
+ }
166
+ },
167
+ {
168
+ "name": "stays_in_week_nights",
169
+ "role": "feature",
170
+ "semantic_type": "numeric",
171
+ "nullable": false,
172
+ "missing_tokens": [],
173
+ "parse_format": null,
174
+ "impute_strategy": "median",
175
+ "profile_stats": {
176
+ "missing_rate": 0.0,
177
+ "unique_count": 35,
178
+ "unique_ratio": 0.000366,
179
+ "example_values": [
180
+ "1",
181
+ "3",
182
+ "4",
183
+ "2",
184
+ "0"
185
+ ]
186
+ }
187
+ },
188
+ {
189
+ "name": "adults",
190
+ "role": "feature",
191
+ "semantic_type": "numeric",
192
+ "nullable": false,
193
+ "missing_tokens": [],
194
+ "parse_format": null,
195
+ "impute_strategy": "median",
196
+ "profile_stats": {
197
+ "missing_rate": 0.0,
198
+ "unique_count": 14,
199
+ "unique_ratio": 0.000147,
200
+ "example_values": [
201
+ "1",
202
+ "2",
203
+ "3",
204
+ "0",
205
+ "4"
206
+ ]
207
+ }
208
+ },
209
+ {
210
+ "name": "children",
211
+ "role": "feature",
212
+ "semantic_type": "numeric",
213
+ "nullable": true,
214
+ "missing_tokens": [
215
+ "NA"
216
+ ],
217
+ "parse_format": null,
218
+ "impute_strategy": "median",
219
+ "profile_stats": {
220
+ "missing_rate": 1e-05,
221
+ "unique_count": 5,
222
+ "unique_ratio": 5.2e-05,
223
+ "example_values": [
224
+ "0",
225
+ "1",
226
+ "2",
227
+ "3",
228
+ "10"
229
+ ]
230
+ }
231
+ },
232
+ {
233
+ "name": "babies",
234
+ "role": "feature",
235
+ "semantic_type": "boolean",
236
+ "nullable": false,
237
+ "missing_tokens": [],
238
+ "parse_format": null,
239
+ "impute_strategy": "mode",
240
+ "profile_stats": {
241
+ "missing_rate": 0.0,
242
+ "unique_count": 4,
243
+ "unique_ratio": 4.2e-05,
244
+ "example_values": [
245
+ "0",
246
+ "1",
247
+ "2",
248
+ "10"
249
+ ]
250
+ }
251
+ },
252
+ {
253
+ "name": "meal",
254
+ "role": "feature",
255
+ "semantic_type": "categorical",
256
+ "nullable": false,
257
+ "missing_tokens": [],
258
+ "parse_format": null,
259
+ "impute_strategy": "mode",
260
+ "profile_stats": {
261
+ "missing_rate": 0.0,
262
+ "unique_count": 5,
263
+ "unique_ratio": 5.2e-05,
264
+ "example_values": [
265
+ "BB",
266
+ "SC",
267
+ "HB",
268
+ "Undefined",
269
+ "FB"
270
+ ]
271
+ }
272
+ },
273
+ {
274
+ "name": "country",
275
+ "role": "feature",
276
+ "semantic_type": "categorical",
277
+ "nullable": true,
278
+ "missing_tokens": [
279
+ "NULL"
280
+ ],
281
+ "parse_format": null,
282
+ "impute_strategy": "mode",
283
+ "profile_stats": {
284
+ "missing_rate": 0.003958,
285
+ "unique_count": 175,
286
+ "unique_ratio": 0.00184,
287
+ "example_values": [
288
+ "PRT",
289
+ "ESP",
290
+ "USA",
291
+ "ITA",
292
+ "POL"
293
+ ]
294
+ }
295
+ },
296
+ {
297
+ "name": "market_segment",
298
+ "role": "feature",
299
+ "semantic_type": "text",
300
+ "nullable": false,
301
+ "missing_tokens": [],
302
+ "parse_format": null,
303
+ "impute_strategy": "keep_raw",
304
+ "profile_stats": {
305
+ "missing_rate": 0.0,
306
+ "unique_count": 7,
307
+ "unique_ratio": 7.3e-05,
308
+ "example_values": [
309
+ "Offline TA/TO",
310
+ "Corporate",
311
+ "Groups",
312
+ "Direct",
313
+ "Online TA"
314
+ ]
315
+ }
316
+ },
317
+ {
318
+ "name": "distribution_channel",
319
+ "role": "feature",
320
+ "semantic_type": "categorical",
321
+ "nullable": false,
322
+ "missing_tokens": [],
323
+ "parse_format": null,
324
+ "impute_strategy": "mode",
325
+ "profile_stats": {
326
+ "missing_rate": 0.0,
327
+ "unique_count": 5,
328
+ "unique_ratio": 5.2e-05,
329
+ "example_values": [
330
+ "TA/TO",
331
+ "Corporate",
332
+ "Direct",
333
+ "GDS",
334
+ "Undefined"
335
+ ]
336
+ }
337
+ },
338
+ {
339
+ "name": "is_repeated_guest",
340
+ "role": "feature",
341
+ "semantic_type": "boolean",
342
+ "nullable": false,
343
+ "missing_tokens": [],
344
+ "parse_format": null,
345
+ "impute_strategy": "mode",
346
+ "profile_stats": {
347
+ "missing_rate": 0.0,
348
+ "unique_count": 2,
349
+ "unique_ratio": 2.1e-05,
350
+ "example_values": [
351
+ "0",
352
+ "1"
353
+ ]
354
+ }
355
+ },
356
+ {
357
+ "name": "previous_cancellations",
358
+ "role": "feature",
359
+ "semantic_type": "boolean",
360
+ "nullable": false,
361
+ "missing_tokens": [],
362
+ "parse_format": null,
363
+ "impute_strategy": "mode",
364
+ "profile_stats": {
365
+ "missing_rate": 0.0,
366
+ "unique_count": 15,
367
+ "unique_ratio": 0.000157,
368
+ "example_values": [
369
+ "0",
370
+ "1",
371
+ "2",
372
+ "19",
373
+ "24"
374
+ ]
375
+ }
376
+ },
377
+ {
378
+ "name": "previous_bookings_not_canceled",
379
+ "role": "feature",
380
+ "semantic_type": "boolean",
381
+ "nullable": false,
382
+ "missing_tokens": [],
383
+ "parse_format": null,
384
+ "impute_strategy": "mode",
385
+ "profile_stats": {
386
+ "missing_rate": 0.0,
387
+ "unique_count": 66,
388
+ "unique_ratio": 0.000691,
389
+ "example_values": [
390
+ "0",
391
+ "3",
392
+ "4",
393
+ "12",
394
+ "8"
395
+ ]
396
+ }
397
+ },
398
+ {
399
+ "name": "reserved_room_type",
400
+ "role": "feature",
401
+ "semantic_type": "categorical",
402
+ "nullable": false,
403
+ "missing_tokens": [],
404
+ "parse_format": null,
405
+ "impute_strategy": "mode",
406
+ "profile_stats": {
407
+ "missing_rate": 0.0,
408
+ "unique_count": 10,
409
+ "unique_ratio": 0.000105,
410
+ "example_values": [
411
+ "A",
412
+ "D",
413
+ "E",
414
+ "H",
415
+ "B"
416
+ ]
417
+ }
418
+ },
419
+ {
420
+ "name": "assigned_room_type",
421
+ "role": "feature",
422
+ "semantic_type": "categorical",
423
+ "nullable": false,
424
+ "missing_tokens": [],
425
+ "parse_format": null,
426
+ "impute_strategy": "mode",
427
+ "profile_stats": {
428
+ "missing_rate": 0.0,
429
+ "unique_count": 12,
430
+ "unique_ratio": 0.000126,
431
+ "example_values": [
432
+ "D",
433
+ "A",
434
+ "E",
435
+ "H",
436
+ "F"
437
+ ]
438
+ }
439
+ },
440
+ {
441
+ "name": "booking_changes",
442
+ "role": "feature",
443
+ "semantic_type": "numeric",
444
+ "nullable": false,
445
+ "missing_tokens": [],
446
+ "parse_format": null,
447
+ "impute_strategy": "median",
448
+ "profile_stats": {
449
+ "missing_rate": 0.0,
450
+ "unique_count": 21,
451
+ "unique_ratio": 0.00022,
452
+ "example_values": [
453
+ "0",
454
+ "1",
455
+ "5",
456
+ "2",
457
+ "3"
458
+ ]
459
+ }
460
+ },
461
+ {
462
+ "name": "deposit_type",
463
+ "role": "feature",
464
+ "semantic_type": "text",
465
+ "nullable": false,
466
+ "missing_tokens": [],
467
+ "parse_format": null,
468
+ "impute_strategy": "keep_raw",
469
+ "profile_stats": {
470
+ "missing_rate": 0.0,
471
+ "unique_count": 3,
472
+ "unique_ratio": 3.1e-05,
473
+ "example_values": [
474
+ "No Deposit",
475
+ "Non Refund",
476
+ "Refundable"
477
+ ]
478
+ }
479
+ },
480
+ {
481
+ "name": "agent",
482
+ "role": "feature",
483
+ "semantic_type": "numeric",
484
+ "nullable": true,
485
+ "missing_tokens": [
486
+ "NULL"
487
+ ],
488
+ "parse_format": null,
489
+ "impute_strategy": "median",
490
+ "profile_stats": {
491
+ "missing_rate": 0.136559,
492
+ "unique_count": 323,
493
+ "unique_ratio": 0.003917,
494
+ "example_values": [
495
+ "77",
496
+ "286",
497
+ "7",
498
+ "34",
499
+ "170"
500
+ ]
501
+ }
502
+ },
503
+ {
504
+ "name": "company",
505
+ "role": "feature",
506
+ "semantic_type": "numeric",
507
+ "nullable": true,
508
+ "missing_tokens": [
509
+ "NULL"
510
+ ],
511
+ "parse_format": null,
512
+ "impute_strategy": "median",
513
+ "profile_stats": {
514
+ "missing_rate": 0.943578,
515
+ "unique_count": 337,
516
+ "unique_ratio": 0.062535,
517
+ "example_values": [
518
+ "362",
519
+ "94",
520
+ "153",
521
+ "67",
522
+ "223"
523
+ ]
524
+ }
525
+ },
526
+ {
527
+ "name": "days_in_waiting_list",
528
+ "role": "feature",
529
+ "semantic_type": "numeric",
530
+ "nullable": false,
531
+ "missing_tokens": [],
532
+ "parse_format": null,
533
+ "impute_strategy": "median",
534
+ "profile_stats": {
535
+ "missing_rate": 0.0,
536
+ "unique_count": 124,
537
+ "unique_ratio": 0.001298,
538
+ "example_values": [
539
+ "0",
540
+ "39",
541
+ "22",
542
+ "108",
543
+ "101"
544
+ ]
545
+ }
546
+ },
547
+ {
548
+ "name": "customer_type",
549
+ "role": "target",
550
+ "semantic_type": "categorical",
551
+ "nullable": false,
552
+ "missing_tokens": [],
553
+ "parse_format": null,
554
+ "impute_strategy": "mode",
555
+ "profile_stats": {
556
+ "missing_rate": 0.0,
557
+ "unique_count": 4,
558
+ "unique_ratio": 4.2e-05,
559
+ "example_values": [
560
+ "Transient-Party",
561
+ "Transient",
562
+ "Contract",
563
+ "Group"
564
+ ]
565
+ }
566
+ },
567
+ {
568
+ "name": "adr",
569
+ "role": "feature",
570
+ "semantic_type": "numeric",
571
+ "nullable": false,
572
+ "missing_tokens": [],
573
+ "parse_format": null,
574
+ "impute_strategy": "median",
575
+ "profile_stats": {
576
+ "missing_rate": 0.0,
577
+ "unique_count": 8008,
578
+ "unique_ratio": 0.083843,
579
+ "example_values": [
580
+ "120",
581
+ "161.88",
582
+ "100",
583
+ "161.1",
584
+ "116.8"
585
+ ]
586
+ }
587
+ },
588
+ {
589
+ "name": "required_car_parking_spaces",
590
+ "role": "feature",
591
+ "semantic_type": "boolean",
592
+ "nullable": false,
593
+ "missing_tokens": [],
594
+ "parse_format": null,
595
+ "impute_strategy": "mode",
596
+ "profile_stats": {
597
+ "missing_rate": 0.0,
598
+ "unique_count": 5,
599
+ "unique_ratio": 5.2e-05,
600
+ "example_values": [
601
+ "0",
602
+ "1",
603
+ "2",
604
+ "3",
605
+ "8"
606
+ ]
607
+ }
608
+ },
609
+ {
610
+ "name": "total_of_special_requests",
611
+ "role": "feature",
612
+ "semantic_type": "numeric",
613
+ "nullable": false,
614
+ "missing_tokens": [],
615
+ "parse_format": null,
616
+ "impute_strategy": "median",
617
+ "profile_stats": {
618
+ "missing_rate": 0.0,
619
+ "unique_count": 6,
620
+ "unique_ratio": 6.3e-05,
621
+ "example_values": [
622
+ "0",
623
+ "1",
624
+ "2",
625
+ "3",
626
+ "5"
627
+ ]
628
+ }
629
+ },
630
+ {
631
+ "name": "reservation_status",
632
+ "role": "feature",
633
+ "semantic_type": "categorical",
634
+ "nullable": false,
635
+ "missing_tokens": [],
636
+ "parse_format": null,
637
+ "impute_strategy": "mode",
638
+ "profile_stats": {
639
+ "missing_rate": 0.0,
640
+ "unique_count": 3,
641
+ "unique_ratio": 3.1e-05,
642
+ "example_values": [
643
+ "Check-Out",
644
+ "Canceled",
645
+ "No-Show"
646
+ ]
647
+ }
648
+ },
649
+ {
650
+ "name": "reservation_status_date",
651
+ "role": "feature",
652
+ "semantic_type": "datetime",
653
+ "nullable": false,
654
+ "missing_tokens": [],
655
+ "parse_format": "%Y-%m-%d",
656
+ "impute_strategy": "keep_raw",
657
+ "profile_stats": {
658
+ "missing_rate": 0.0,
659
+ "unique_count": 920,
660
+ "unique_ratio": 0.009632,
661
+ "example_values": [
662
+ "2016-10-15",
663
+ "2016-11-09",
664
+ "2016-12-02",
665
+ "2016-06-21",
666
+ "2016-10-23"
667
+ ]
668
+ }
669
+ }
670
+ ],
671
+ "public_manifest": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/staged_input_manifest.json",
672
+ "train_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/train.csv",
673
+ "val_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/val.csv",
674
+ "test_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/test.csv",
675
+ "features_json": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/staged/public/staged_features.json",
676
+ "public_gate_report": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/m12/tabddpm/tabddpm-m12-20260510_215502/public_gate/public_gate_report.json"
677
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_215502/train_20260510_215504.log ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:329540d3fd34ed5a0511b54e41f3bc60629f21d9a495826579a594129073e10a
3
+ size 577
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/._data ADDED
Binary file (220 Bytes). View file
 
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/.gitignore ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ __pycache__/
3
+ catboost_info/
4
+ **/**.pt
5
+ **/**.ipynb
6
+ !agg_results.ipynb
7
+ **/**.npy
8
+ **/**.gz
9
+ **/**.sh
10
+ **/**.obj
11
+ **/**.png
12
+ **/**.tar
13
+ **/**.code-workspace
14
+ **/**.csv
15
+ exp/**/**/results_catboost.json
16
+ exp/**/**/results_mlp.json
17
+
18
+ configs/
19
+ data/
20
+ junk/
21
+ RF/
22
+ exps/
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/.gitmodules ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [submodule "ctgan"]
2
+ # path = CTGAN/CTGAN
3
+ url = https://github.com/sdv-dev/CTGAN
4
+ [submodule "ctabgan"]
5
+ # path = CTAB-GAN
6
+ url = https://github.com/Team-TUD/CTAB-GAN
7
+ [submodule "ctabgan+"]
8
+ # path = CTAB-GAN-Plus
9
+ url = https://github.com/Team-TUD/CTAB-GAN-Plus
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CONFIG_DESCRIPTION.md ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Description of .toml config for TabDDPM
2
+ First of all, `train.T` and `eval.T` denote preprocessing for training and for evaluation, respectively.
3
+
4
+ Here we list non-obvious parameters.
5
+
6
+ Main part:
7
+ - `seed = 0` -- evaluation seed (and training, but for training it is fixed to 0)
8
+ - `parent_dir = "exp/abalone/check"` -- exp folder
9
+ - `real_data_path = "data/abalone/"`
10
+ - `model_type = "mlp"` -- model type that approximates the reverse process
11
+ - `num_numerical_features ` -- a number of numerical features in dataset
12
+ - `device = "cuda:0"`
13
+
14
+ Model params:
15
+ - `is_y_cond` -- false for regression, true for classification
16
+ - `d_in` -- input dimension (not necessary, since scripts calculate it automatically)
17
+ - `num_calsses` -- zero for regression, a number of classes for classification
18
+ - `rtdl_params` -- MLP parameters
19
+
20
+ ```toml
21
+ seed = 0
22
+ parent_dir = "exp/abalone/check"
23
+ real_data_path = "data/abalone/"
24
+ model_type = "mlp"
25
+ num_numerical_features = 7
26
+ device = "cuda:0"
27
+
28
+ [model_params]
29
+ is_y_cond = false
30
+ d_in = 11
31
+ num_classes = 0
32
+
33
+ [model_params.rtdl_params]
34
+ d_layers = [
35
+ 256,
36
+ 256,
37
+ ]
38
+ dropout = 0.0
39
+
40
+ [diffusion_params]
41
+ num_timesteps = 1000
42
+ gaussian_loss_type = "mse"
43
+ scheduler = "cosine"
44
+
45
+ [train.main]
46
+ steps = 1000
47
+ lr = 0.001
48
+ weight_decay = 1e-05
49
+ batch_size = 4096
50
+
51
+ [train.T]
52
+ seed = 0
53
+ normalization = "quantile"
54
+ num_nan_policy = "__none__"
55
+ cat_nan_policy = "__none__"
56
+ cat_min_frequency = "__none__"
57
+ cat_encoding = "__none__"
58
+ y_policy = "default"
59
+
60
+ [sample]
61
+ num_samples = 20800
62
+ batch_size = 10000
63
+ seed = 0
64
+
65
+ [eval.type]
66
+ eval_model = "catboost"
67
+ eval_type = "synthetic"
68
+
69
+ [eval.T]
70
+ seed = 0
71
+ normalization = "__none__"
72
+ num_nan_policy = "__none__"
73
+ cat_nan_policy = "__none__"
74
+ cat_min_frequency = "__none__"
75
+ cat_encoding = "__none__"
76
+ y_policy = "default"
77
+
78
+ ```
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ **/**.csv
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CTAB-GAN+
2
+ This is the official git paper [CTAB-GAN+: Enhancing Tabular Data Synthesis](https://arxiv.org/abs/2204.00401). Current code is without differential privacy part.
3
+ If you have any question, please contact `z.zhao-8@tudelft.nl` for more information.
4
+
5
+
6
+ ## Prerequisite
7
+
8
+ The required package version
9
+ ```
10
+ numpy==1.21.0
11
+ torch==1.9.1
12
+ pandas==1.2.4
13
+ sklearn==0.24.1
14
+ dython==0.6.4.post1
15
+ scipy==1.4.1
16
+ ```
17
+ The sklean package in newer version has updated its function for `sklearn.mixture.BayesianGaussianMixture`. Therefore, user should use this proposed sklearn version to successfully run the code!
18
+
19
+ ## Example
20
+ `Experiment_Script_Adult.ipynb` `Experiment_Script_king.ipynb` are two example notebooks for training CTAB-GAN+ with Adult (classification) and king (regression) datasets. The datasets are alread under `Real_Datasets` folder.
21
+ The evaluation code is also provided.
22
+
23
+ ## Problem type
24
+
25
+ You can either indicate your dataset problem type as Classification, Regression. If there is no problem type, you can leave the problem type as None as follows:
26
+ ```
27
+ problem_type= {None: None}
28
+ ```
29
+
30
+ ## For large dataset
31
+
32
+ If your dataset has large number of column, you may encounter the problem that our currnet code cannot encode all of your data since CTAB-GAN+ will wrap the encoded data into an image-like format. What you can do is changing the line 378 and 385 in `model/synthesizer/ctabgan_synthesizer.py`. The number in the `slide` list
33
+ ```
34
+ sides = [4, 8, 16, 24, 32]
35
+ ```
36
+ is the side size of image. You can enlarge the list to [4, 8, 16, 24, 32, 64] or [4, 8, 16, 24, 32, 64, 128] for accepting larger dataset.
37
+
38
+ ## Bibtex
39
+
40
+ To cite this paper, you could use this bibtex
41
+
42
+ ```
43
+ @article{zhao2022ctab,
44
+ title={CTAB-GAN+: Enhancing Tabular Data Synthesis},
45
+ author={Zhao, Zilong and Kunar, Aditya and Birke, Robert and Chen, Lydia Y},
46
+ journal={arXiv preprint arXiv:2204.00401},
47
+ year={2022}
48
+ }
49
+ ```
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/columns.json ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "churn2": {
3
+ "categorical_columns": ["7", "8", "9", "10", "y"],
4
+ "mixed_columns": {"0": [850.0], "3": [0.0]},
5
+ "integer_columns": ["2", "4"],
6
+ "general_columns": ["1", "5", "6"],
7
+ "problem_type": {"Classification": "y"}
8
+ },
9
+ "adult": {
10
+ "categorical_columns": ["6", "7", "8", "9", "10", "11", "12", "13", "y"],
11
+ "mixed_columns": {"3": [0.0], "4": [0.0]},
12
+ "integer_columns": ["0", "1", "2", "5"],
13
+ "general_columns": ["0", "1", "7"],
14
+ "problem_type": {"Classification": "y"}
15
+ },
16
+ "california": {
17
+ "categorical_columns": [],
18
+ "mixed_columns": {"1": [52.0]},
19
+ "integer_columns": ["4"],
20
+ "general_columns": ["0"],
21
+ "problem_type": {"Regression": "y"}
22
+ },
23
+ "default": {
24
+ "categorical_columns": ["20", "21", "22", "y"],
25
+ "mixed_columns": {},
26
+ "general_columns": [],
27
+ "integer_columns": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"],
28
+ "problem_type": {"Classification": "y"}
29
+ },
30
+ "buddy": {
31
+ "categorical_columns": ["4", "5", "6", "7", "8", "y"],
32
+ "mixed_columns": {},
33
+ "integer_columns": ["0", "1"],
34
+ "general_columns": ["1", "3", "5"],
35
+ "problem_type": {"Classification": "y"}
36
+ },
37
+ "gesture": {
38
+ "categorical_columns": ["y"],
39
+ "mixed_columns": {},
40
+ "integer_columns": [],
41
+ "general_columns": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"],
42
+ "problem_type": {"Classification": "y"}
43
+ },
44
+ "wilt": {
45
+ "categorical_columns": ["y"],
46
+ "mixed_columns": {},
47
+ "integer_columns": [],
48
+ "general_columns": ["0", "3"],
49
+ "problem_type": {"Classification": "y"}
50
+ },
51
+ "satellite": {
52
+ "categorical_columns": ["y"],
53
+ "mixed_columns": {},
54
+ "integer_columns": [],
55
+ "problem_type": {"Classification": "y"}
56
+ },
57
+ "higgs-small": {
58
+ "categorical_columns": ["y"],
59
+ "mixed_columns": {},
60
+ "integer_columns": [],
61
+ "general_columns": ["1", "2", "4", "6", "10", "11", "14", "15", "18","19"],
62
+ "problem_type": {"Classification": "y"}
63
+ },
64
+ "diabetes": {
65
+ "categorical_columns": ["y"],
66
+ "mixed_columns": {"3": [0.0], "4": [0.0]},
67
+ "general_columns": [],
68
+ "integer_columns": ["0", "1", "2", "5", "7"],
69
+ "problem_type": {"Classification": "y"}
70
+ },
71
+ "abalone": {
72
+ "categorical_columns": ["7"],
73
+ "mixed_columns": {},
74
+ "integer_columns": ["y"],
75
+ "general_columns": [],
76
+ "problem_type": {"Regression": "y"}
77
+ },
78
+ "insurance": {
79
+ "categorical_columns": ["3", "4", "5"],
80
+ "mixed_columns": {},
81
+ "general_columns": [],
82
+ "integer_columns": ["0", "2"],
83
+ "problem_type": {"Regression": "y"}
84
+ },
85
+ "king": {
86
+ "categorical_columns": ["17", "18", "19"],
87
+ "mixed_columns": {"9": [0.0], "11":[0.0]},
88
+ "general_columns": ["2", "6", "7"],
89
+ "integer_columns": ["0", "2", "5", "7", "8", "9", "12"],
90
+ "problem_type": {"Regression": "y"}
91
+ },
92
+ "cardio": {
93
+ "categorical_columns": ["5", "6", "7", "8", "9", "10", "y"],
94
+ "mixed_columns": {},
95
+ "integer_columns": ["0", "1", "3", "4"],
96
+ "problem_type": {"Classification": "y"}
97
+ },
98
+ "house": {
99
+ "categorical_columns": [],
100
+ "mixed_columns": {"2": [0.0], "6": [0.0], "8": [0.0], "11": [0.0], "12": [1.0], "14": [0.0]},
101
+ "general_columns": ["1", "7"],
102
+ "integer_columns": ["0"],
103
+ "problem_type": {"Regression": "y"}
104
+ },
105
+ "miniboone": {
106
+ "categorical_columns": ["y"],
107
+ "mixed_columns": {},
108
+ "integer_columns": [],
109
+ "general_columns": ["8", "9", "10", "19", "20", "21", "28", "29", "35", "39", "45", "49"],
110
+ "problem_type": {"Classification": "y"}
111
+ },
112
+ "fb-comments": {
113
+ "categorical_columns": ["36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50"],
114
+ "mixed_columns": {"1": [0.0], "8": [0.0], "10": [0.0]},
115
+ "general_columns": ["26", "36"],
116
+ "integer_columns": [],
117
+ "problem_type": {"Regression": "y"}
118
+ }
119
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/ctabgan.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generative model training algorithm based on the CTABGANSynthesiser
3
+
4
+ """
5
+ import pandas as pd
6
+ import time
7
+ from model.pipeline.data_preparation import DataPrep
8
+ from model.synthesizer.ctabgan_synthesizer import CTABGANSynthesizer
9
+
10
+ import warnings
11
+
12
+ warnings.filterwarnings("ignore")
13
+
14
+ class CTABGAN():
15
+
16
+ def __init__(self,
17
+ df,
18
+ test_ratio = 0.20,
19
+ categorical_columns = [ 'workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'gender', 'native-country', 'income'],
20
+ log_columns = [],
21
+ mixed_columns= {'capital-loss':[0.0],'capital-gain':[0.0]},
22
+ general_columns = ["age"],
23
+ non_categorical_columns = [],
24
+ integer_columns = ['age', 'fnlwgt','capital-gain', 'capital-loss','hours-per-week'],
25
+ problem_type= {"Classification": "income"},
26
+ class_dim=(256, 256, 256, 256),
27
+ random_dim=100,
28
+ num_channels=64,
29
+ l2scale=1e-5,
30
+ batch_size=500,
31
+ epochs=150,
32
+ device="cpu"):
33
+
34
+ self.__name__ = 'CTABGAN'
35
+
36
+ self.synthesizer = CTABGANSynthesizer(
37
+ class_dim=class_dim,
38
+ random_dim=random_dim,
39
+ num_channels=num_channels,
40
+ l2scale=l2scale,
41
+ batch_size=batch_size,
42
+ epochs=epochs,
43
+ device=device
44
+ )
45
+ self.raw_df = df
46
+ self.test_ratio = test_ratio
47
+ self.categorical_columns = categorical_columns
48
+ self.log_columns = log_columns
49
+ self.mixed_columns = mixed_columns
50
+ self.general_columns = general_columns
51
+ self.non_categorical_columns = non_categorical_columns
52
+ self.integer_columns = integer_columns
53
+ self.problem_type = problem_type
54
+
55
+ def fit(self):
56
+
57
+ start_time = time.time()
58
+ self.data_prep = DataPrep(self.raw_df,self.categorical_columns,self.log_columns,self.mixed_columns,self.general_columns,self.non_categorical_columns,self.integer_columns,self.problem_type,self.test_ratio)
59
+ self.synthesizer.fit(train_data=self.data_prep.df, categorical = self.data_prep.column_types["categorical"], mixed = self.data_prep.column_types["mixed"],
60
+ general = self.data_prep.column_types["general"], non_categorical = self.data_prep.column_types["non_categorical"], type=self.problem_type)
61
+ end_time = time.time()
62
+ print('Finished training in',end_time-start_time," seconds.")
63
+
64
+
65
+ def generate_samples(self, seed=0):
66
+
67
+ sample = self.synthesizer.sample(len(self.raw_df), seed)
68
+ sample_df = self.data_prep.inverse_prep(sample)
69
+
70
+ return sample_df
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/eval/evaluation.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn import metrics
4
+ from sklearn import model_selection
5
+ from sklearn.preprocessing import MinMaxScaler,StandardScaler
6
+ from sklearn.neural_network import MLPClassifier
7
+ from sklearn.linear_model import LogisticRegression
8
+ from sklearn import svm,tree
9
+ from sklearn.ensemble import RandomForestClassifier
10
+ from dython.nominal import compute_associations
11
+ from scipy.stats import wasserstein_distance
12
+ from scipy.spatial import distance
13
+ import warnings
14
+
15
+ warnings.filterwarnings("ignore")
16
+
17
+ def supervised_model_training(x_train, y_train, x_test,
18
+ y_test, model_name):
19
+
20
+
21
+ if model_name == 'lr':
22
+ model = LogisticRegression(random_state=42,max_iter=500)
23
+ elif model_name == 'svm':
24
+ model = svm.SVC(random_state=42,probability=True)
25
+ elif model_name == 'dt':
26
+ model = tree.DecisionTreeClassifier(random_state=42)
27
+ elif model_name == 'rf':
28
+ model = RandomForestClassifier(random_state=42)
29
+ elif model_name == "mlp":
30
+ model = MLPClassifier(random_state=42,max_iter=100)
31
+
32
+ model.fit(x_train, y_train)
33
+ pred = model.predict(x_test)
34
+
35
+ if len(np.unique(y_train))>2:
36
+ predict = model.predict_proba(x_test)
37
+ acc = metrics.accuracy_score(y_test,pred)*100
38
+ auc = metrics.roc_auc_score(y_test, predict,average="weighted",multi_class="ovr")
39
+ f1_score = metrics.precision_recall_fscore_support(y_test, pred,average="weighted")[2]
40
+ return [acc, auc,f1_score]
41
+
42
+ else:
43
+ predict = model.predict_proba(x_test)[:,1]
44
+ acc = metrics.accuracy_score(y_test,pred)*100
45
+ auc = metrics.roc_auc_score(y_test, predict)
46
+ f1_score = metrics.precision_recall_fscore_support(y_test,pred)[2].mean()
47
+ return [acc, auc,f1_score]
48
+
49
+
50
+ def get_utility_metrics(real_path,fake_paths,scaler="MinMax",classifiers=["lr","dt","rf","mlp"],test_ratio=.20):
51
+
52
+ data_real = pd.read_csv(real_path).to_numpy()
53
+ data_dim = data_real.shape[1]
54
+
55
+ data_real_y = data_real[:,-1]
56
+ data_real_X = data_real[:,:data_dim-1]
57
+ X_train_real, X_test_real, y_train_real, y_test_real = model_selection.train_test_split(data_real_X ,data_real_y, test_size=test_ratio, stratify=data_real_y,random_state=42)
58
+
59
+ if scaler=="MinMax":
60
+ scaler_real = MinMaxScaler()
61
+ else:
62
+ scaler_real = StandardScaler()
63
+
64
+ scaler_real.fit(data_real_X)
65
+ X_train_real_scaled = scaler_real.transform(X_train_real)
66
+ X_test_real_scaled = scaler_real.transform(X_test_real)
67
+
68
+ all_real_results = []
69
+ for classifier in classifiers:
70
+ real_results = supervised_model_training(X_train_real_scaled,y_train_real,X_test_real_scaled,y_test_real,classifier)
71
+ all_real_results.append(real_results)
72
+
73
+ all_fake_results_avg = []
74
+
75
+ for fake_path in fake_paths:
76
+ data_fake = pd.read_csv(fake_path).to_numpy()
77
+ data_fake_y = data_fake[:,-1]
78
+ data_fake_X = data_fake[:,:data_dim-1]
79
+ X_train_fake, _ , y_train_fake, _ = model_selection.train_test_split(data_fake_X ,data_fake_y, test_size=test_ratio, stratify=data_fake_y,random_state=42)
80
+
81
+ if scaler=="MinMax":
82
+ scaler_fake = MinMaxScaler()
83
+ else:
84
+ scaler_fake = StandardScaler()
85
+
86
+ scaler_fake.fit(data_fake_X)
87
+
88
+ X_train_fake_scaled = scaler_fake.transform(X_train_fake)
89
+
90
+ all_fake_results = []
91
+ for classifier in classifiers:
92
+ fake_results = supervised_model_training(X_train_fake_scaled,y_train_fake,X_test_real_scaled,y_test_real,classifier)
93
+ all_fake_results.append(fake_results)
94
+
95
+ all_fake_results_avg.append(all_fake_results)
96
+
97
+ diff_results = np.array(all_real_results)- np.array(all_fake_results_avg).mean(axis=0)
98
+
99
+ return diff_results
100
+
101
+ def stat_sim(real_path,fake_path,cat_cols=None):
102
+
103
+ Stat_dict={}
104
+
105
+ real = pd.read_csv(real_path)
106
+ fake = pd.read_csv(fake_path)
107
+
108
+ really = real.copy()
109
+ fakey = fake.copy()
110
+
111
+ real_corr = compute_associations(real, nominal_columns=cat_cols)
112
+
113
+ fake_corr = compute_associations(fake, nominal_columns=cat_cols)
114
+
115
+ corr_dist = np.linalg.norm(real_corr - fake_corr)
116
+
117
+ cat_stat = []
118
+ num_stat = []
119
+
120
+ for column in real.columns:
121
+
122
+ if column in cat_cols:
123
+
124
+ real_pdf=(really[column].value_counts()/really[column].value_counts().sum())
125
+ fake_pdf=(fakey[column].value_counts()/fakey[column].value_counts().sum())
126
+ categories = (fakey[column].value_counts()/fakey[column].value_counts().sum()).keys().tolist()
127
+ sorted_categories = sorted(categories)
128
+
129
+ real_pdf_values = []
130
+ fake_pdf_values = []
131
+
132
+ for i in sorted_categories:
133
+ real_pdf_values.append(real_pdf[i])
134
+ fake_pdf_values.append(fake_pdf[i])
135
+
136
+ if len(real_pdf)!=len(fake_pdf):
137
+ zero_cats = set(really[column].value_counts().keys())-set(fakey[column].value_counts().keys())
138
+ for z in zero_cats:
139
+ real_pdf_values.append(real_pdf[z])
140
+ fake_pdf_values.append(0)
141
+ Stat_dict[column]=(distance.jensenshannon(real_pdf_values,fake_pdf_values, 2.0))
142
+ cat_stat.append(Stat_dict[column])
143
+ else:
144
+ scaler = MinMaxScaler()
145
+ scaler.fit(real[column].values.reshape(-1,1))
146
+ l1 = scaler.transform(real[column].values.reshape(-1,1)).flatten()
147
+ l2 = scaler.transform(fake[column].values.reshape(-1,1)).flatten()
148
+ Stat_dict[column]= (wasserstein_distance(l1,l2))
149
+ num_stat.append(Stat_dict[column])
150
+
151
+ return [np.mean(num_stat),np.mean(cat_stat),corr_dist]
152
+
153
+ def privacy_metrics(real_path,fake_path,data_percent=15):
154
+
155
+ real = pd.read_csv(real_path).drop_duplicates(keep=False)
156
+ fake = pd.read_csv(fake_path).drop_duplicates(keep=False)
157
+
158
+ real_refined = real.sample(n=int(len(real)*(.01*data_percent)), random_state=42).to_numpy()
159
+ fake_refined = fake.sample(n=int(len(fake)*(.01*data_percent)), random_state=42).to_numpy()
160
+
161
+ scalerR = StandardScaler()
162
+ scalerR.fit(real_refined)
163
+ scalerF = StandardScaler()
164
+ scalerF.fit(fake_refined)
165
+ df_real_scaled = scalerR.transform(real_refined)
166
+ df_fake_scaled = scalerF.transform(fake_refined)
167
+
168
+ dist_rf = metrics.pairwise_distances(df_real_scaled, Y=df_fake_scaled, metric='minkowski', n_jobs=-1)
169
+ dist_rr = metrics.pairwise_distances(df_real_scaled, Y=None, metric='minkowski', n_jobs=-1)
170
+ rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1)
171
+ dist_ff = metrics.pairwise_distances(df_fake_scaled, Y=None, metric='minkowski', n_jobs=-1)
172
+ rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1)
173
+ smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))]
174
+ smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))]
175
+ smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))]
176
+ smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))]
177
+ smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))]
178
+ smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))]
179
+ nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr])
180
+ nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff])
181
+ nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf])
182
+ nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5)
183
+ nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5)
184
+ nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5)
185
+
186
+ min_dist_rf = np.array([i[0] for i in smallest_two_rf])
187
+ fifth_perc_rf = np.percentile(min_dist_rf,5)
188
+ min_dist_rr = np.array([i[0] for i in smallest_two_rr])
189
+ fifth_perc_rr = np.percentile(min_dist_rr,5)
190
+ min_dist_ff = np.array([i[0] for i in smallest_two_ff])
191
+ fifth_perc_ff = np.percentile(min_dist_ff,5)
192
+
193
+ return np.array([fifth_perc_rf,fifth_perc_rr,fifth_perc_ff,nn_fifth_perc_rf,nn_fifth_perc_rr,nn_fifth_perc_ff]).reshape(1,6)
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/pipeline/data_preparation.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn import preprocessing
4
+ from sklearn import model_selection
5
+
6
+ class DataPrep(object):
7
+
8
+ def __init__(self, raw_df: pd.DataFrame, categorical: list, log:list, mixed:dict, general:list, non_categorical:list, integer:list, type:dict, test_ratio:float):
9
+
10
+
11
+ self.categorical_columns = categorical
12
+ self.log_columns = log
13
+ self.mixed_columns = mixed
14
+ self.general_columns = general
15
+ self.non_categorical_columns = non_categorical
16
+ self.integer_columns = integer
17
+ self.column_types = dict()
18
+ self.column_types["categorical"] = []
19
+ self.column_types["mixed"] = {}
20
+ self.column_types["general"] = []
21
+ self.column_types["non_categorical"] = []
22
+ self.lower_bounds = {}
23
+ self.label_encoder_list = []
24
+
25
+ target_col = list(type.values())[0]
26
+ if target_col is not None:
27
+ y_real = raw_df[target_col]
28
+ X_real = raw_df.drop(columns=[target_col])
29
+ X_train_real, _, y_train_real, _ = model_selection.train_test_split(X_real ,y_real, test_size=test_ratio, stratify=y_real,random_state=42)
30
+
31
+ X_train_real[target_col]= y_train_real
32
+
33
+ self.df = X_train_real
34
+ else:
35
+ self.df = raw_df
36
+
37
+ self.df = self.df.replace(r' ', np.nan)
38
+ self.df = self.df.fillna('empty')
39
+
40
+ all_columns= set(self.df.columns)
41
+ irrelevant_missing_columns = set(self.categorical_columns)
42
+ relevant_missing_columns = list(all_columns - irrelevant_missing_columns)
43
+
44
+ for i in relevant_missing_columns:
45
+ if i in self.log_columns:
46
+ if "empty" in list(self.df[i].values):
47
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x)
48
+ self.mixed_columns[i] = [-9999999]
49
+ elif i in list(self.mixed_columns.keys()):
50
+ if "empty" in list(self.df[i].values):
51
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x )
52
+ self.mixed_columns[i].append(-9999999)
53
+ else:
54
+ if "empty" in list(self.df[i].values):
55
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x)
56
+ self.mixed_columns[i] = [-9999999]
57
+
58
+ if self.log_columns:
59
+ for log_column in self.log_columns:
60
+ valid_indices = []
61
+ for idx,val in enumerate(self.df[log_column].values):
62
+ if val!=-9999999:
63
+ valid_indices.append(idx)
64
+ eps = 1
65
+ lower = np.min(self.df[log_column].iloc[valid_indices].values)
66
+ self.lower_bounds[log_column] = lower
67
+ if lower>0:
68
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x) if x!=-9999999 else -9999999)
69
+ elif lower == 0:
70
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x+eps) if x!=-9999999 else -9999999)
71
+ else:
72
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x-lower+eps) if x!=-9999999 else -9999999)
73
+
74
+ for column_index, column in enumerate(self.df.columns):
75
+ if column in self.categorical_columns:
76
+ label_encoder = preprocessing.LabelEncoder()
77
+ self.df[column] = self.df[column].astype(str)
78
+ label_encoder.fit(self.df[column])
79
+ current_label_encoder = dict()
80
+ current_label_encoder['column'] = column
81
+ current_label_encoder['label_encoder'] = label_encoder
82
+ transformed_column = label_encoder.transform(self.df[column])
83
+ self.df[column] = transformed_column
84
+ self.label_encoder_list.append(current_label_encoder)
85
+ self.column_types["categorical"].append(column_index)
86
+
87
+ if column in self.general_columns:
88
+ self.column_types["general"].append(column_index)
89
+
90
+ if column in self.non_categorical_columns:
91
+ self.column_types["non_categorical"].append(column_index)
92
+
93
+ elif column in self.mixed_columns:
94
+ self.column_types["mixed"][column_index] = self.mixed_columns[column]
95
+
96
+ elif column in self.general_columns:
97
+ self.column_types["general"].append(column_index)
98
+
99
+
100
+ super().__init__()
101
+
102
+ def inverse_prep(self, data, eps=1):
103
+
104
+ df_sample = pd.DataFrame(data,columns=self.df.columns)
105
+
106
+ for i in range(len(self.label_encoder_list)):
107
+ le = self.label_encoder_list[i]["label_encoder"]
108
+ df_sample[self.label_encoder_list[i]["column"]] = df_sample[self.label_encoder_list[i]["column"]].astype(int)
109
+ df_sample[self.label_encoder_list[i]["column"]] = le.inverse_transform(df_sample[self.label_encoder_list[i]["column"]])
110
+
111
+ if self.log_columns:
112
+ for i in df_sample:
113
+ if i in self.log_columns:
114
+ lower_bound = self.lower_bounds[i]
115
+ if lower_bound>0:
116
+ df_sample[i].apply(lambda x: np.exp(x))
117
+ elif lower_bound==0:
118
+ df_sample[i] = df_sample[i].apply(lambda x: np.ceil(np.exp(x)-eps) if (np.exp(x)-eps) < 0 else (np.exp(x)-eps))
119
+ else:
120
+ df_sample[i] = df_sample[i].apply(lambda x: np.exp(x)-eps+lower_bound)
121
+
122
+ if self.integer_columns:
123
+ for column in self.integer_columns:
124
+ df_sample[column]= (np.round(df_sample[column].values))
125
+ df_sample[column] = df_sample[column].astype(int)
126
+
127
+ df_sample.replace(-9999999, np.nan,inplace=True)
128
+ df_sample.replace('empty', np.nan,inplace=True)
129
+
130
+ return df_sample
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/privacy_utils/rdp_accountant.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+ from __future__ import division
3
+ from __future__ import print_function
4
+
5
+ import math
6
+ import sys
7
+
8
+ import numpy as np
9
+ from scipy import special
10
+ import six
11
+
12
+ ########################
13
+ # LOG-SPACE ARITHMETIC #
14
+ ########################
15
+
16
+
17
+ def _log_add(logx, logy):
18
+ """Add two numbers in the log space."""
19
+ a, b = min(logx, logy), max(logx, logy)
20
+ if a == -np.inf: # adding 0
21
+ return b
22
+ # Use exp(a) + exp(b) = (exp(a - b) + 1) * exp(b)
23
+ return math.log1p(math.exp(a - b)) + b # log1p(x) = log(x + 1)
24
+
25
+
26
+ def _log_sub(logx, logy):
27
+ """Subtract two numbers in the log space. Answer must be non-negative."""
28
+ if logx < logy:
29
+ raise ValueError("The result of subtraction must be non-negative.")
30
+ if logy == -np.inf: # subtracting 0
31
+ return logx
32
+ if logx == logy:
33
+ return -np.inf # 0 is represented as -np.inf in the log space.
34
+
35
+ try:
36
+ # Use exp(x) - exp(y) = (exp(x - y) - 1) * exp(y).
37
+ return math.log(math.expm1(logx - logy)) + logy # expm1(x) = exp(x) - 1
38
+ except OverflowError:
39
+ return logx
40
+
41
+
42
+ def _log_print(logx):
43
+ """Pretty print."""
44
+ if logx < math.log(sys.float_info.max):
45
+ return "{}".format(math.exp(logx))
46
+ else:
47
+ return "exp({})".format(logx)
48
+
49
+
50
+ def _compute_log_a_int(q, sigma, alpha):
51
+ """Compute log(A_alpha) for integer alpha. 0 < q < 1."""
52
+ assert isinstance(alpha, six.integer_types)
53
+
54
+ # Initialize with 0 in the log space.
55
+ log_a = -np.inf
56
+
57
+ for i in range(alpha + 1):
58
+ log_coef_i = (
59
+ math.log(special.binom(alpha, i)) + i * math.log(q) +
60
+ (alpha - i) * math.log(1 - q))
61
+
62
+ s = log_coef_i + (i * i - i) / (2 * (sigma**2))
63
+ log_a = _log_add(log_a, s)
64
+
65
+ return float(log_a)
66
+
67
+
68
+ def _compute_log_a_frac(q, sigma, alpha):
69
+ """Compute log(A_alpha) for fractional alpha. 0 < q < 1."""
70
+ # The two parts of A_alpha, integrals over (-inf,z0] and [z0, +inf), are
71
+ # initialized to 0 in the log space:
72
+ log_a0, log_a1 = -np.inf, -np.inf
73
+ i = 0
74
+
75
+ z0 = sigma**2 * math.log(1 / q - 1) + .5
76
+
77
+ while True: # do ... until loop
78
+ coef = special.binom(alpha, i)
79
+ log_coef = math.log(abs(coef))
80
+ j = alpha - i
81
+
82
+ log_t0 = log_coef + i * math.log(q) + j * math.log(1 - q)
83
+ log_t1 = log_coef + j * math.log(q) + i * math.log(1 - q)
84
+
85
+ log_e0 = math.log(.5) + _log_erfc((i - z0) / (math.sqrt(2) * sigma))
86
+ log_e1 = math.log(.5) + _log_erfc((z0 - j) / (math.sqrt(2) * sigma))
87
+
88
+ log_s0 = log_t0 + (i * i - i) / (2 * (sigma**2)) + log_e0
89
+ log_s1 = log_t1 + (j * j - j) / (2 * (sigma**2)) + log_e1
90
+
91
+ if coef > 0:
92
+ log_a0 = _log_add(log_a0, log_s0)
93
+ log_a1 = _log_add(log_a1, log_s1)
94
+ else:
95
+ log_a0 = _log_sub(log_a0, log_s0)
96
+ log_a1 = _log_sub(log_a1, log_s1)
97
+
98
+ i += 1
99
+ if max(log_s0, log_s1) < -30:
100
+ break
101
+
102
+ return _log_add(log_a0, log_a1)
103
+
104
+
105
+ def _compute_log_a(q, sigma, alpha):
106
+ """Compute log(A_alpha) for any positive finite alpha."""
107
+ if float(alpha).is_integer():
108
+ return _compute_log_a_int(q, sigma, int(alpha))
109
+ else:
110
+ return _compute_log_a_frac(q, sigma, alpha)
111
+
112
+
113
+ def _log_erfc(x):
114
+ """Compute log(erfc(x)) with high accuracy for large x."""
115
+ try:
116
+ return math.log(2) + special.log_ndtr(-x * 2**.5)
117
+ except NameError:
118
+ # If log_ndtr is not available, approximate as follows:
119
+ r = special.erfc(x)
120
+ if r == 0.0:
121
+ # Using the Laurent series at infinity for the tail of the erfc function:
122
+ # erfc(x) ~ exp(-x^2-.5/x^2+.625/x^4)/(x*pi^.5)
123
+ # To verify in Mathematica:
124
+ # Series[Log[Erfc[x]] + Log[x] + Log[Pi]/2 + x^2, {x, Infinity, 6}]
125
+ return (-math.log(math.pi) / 2 - math.log(x) - x**2 - .5 * x**-2 +
126
+ .625 * x**-4 - 37. / 24. * x**-6 + 353. / 64. * x**-8)
127
+ else:
128
+ return math.log(r)
129
+
130
+
131
+ def _compute_delta(orders, rdp, eps):
132
+ """Compute delta given a list of RDP values and target epsilon.
133
+
134
+ Args:
135
+ orders: An array (or a scalar) of orders.
136
+ rdp: A list (or a scalar) of RDP guarantees.
137
+ eps: The target epsilon.
138
+
139
+ Returns:
140
+ Pair of (delta, optimal_order).
141
+
142
+ Raises:
143
+ ValueError: If input is malformed.
144
+
145
+ """
146
+ orders_vec = np.atleast_1d(orders)
147
+ rdp_vec = np.atleast_1d(rdp)
148
+
149
+ if len(orders_vec) != len(rdp_vec):
150
+ raise ValueError("Input lists must have the same length.")
151
+
152
+ deltas = np.exp((rdp_vec - eps) * (orders_vec - 1))
153
+ idx_opt = np.argmin(deltas)
154
+ return min(deltas[idx_opt], 1.), orders_vec[idx_opt]
155
+
156
+
157
+ def _compute_eps(orders, rdp, delta):
158
+ """Compute epsilon given a list of RDP values and target delta.
159
+
160
+ Args:
161
+ orders: An array (or a scalar) of orders.
162
+ rdp: A list (or a scalar) of RDP guarantees.
163
+ delta: The target delta.
164
+
165
+ Returns:
166
+ Pair of (eps, optimal_order).
167
+
168
+ Raises:
169
+ ValueError: If input is malformed.
170
+
171
+ """
172
+ orders_vec = np.atleast_1d(orders)
173
+ rdp_vec = np.atleast_1d(rdp)
174
+
175
+ if len(orders_vec) != len(rdp_vec):
176
+ raise ValueError("Input lists must have the same length.")
177
+
178
+ eps = rdp_vec - math.log(delta) / (orders_vec - 1)
179
+
180
+ idx_opt = np.nanargmin(eps) # Ignore NaNs
181
+ return eps[idx_opt], orders_vec[idx_opt]
182
+
183
+
184
+ def _compute_rdp(q, sigma, alpha):
185
+ """Compute RDP of the Sampled Gaussian mechanism at order alpha.
186
+
187
+ Args:
188
+ q: The sampling rate.
189
+ sigma: The std of the additive Gaussian noise.
190
+ alpha: The order at which RDP is computed.
191
+
192
+ Returns:
193
+ RDP at alpha, can be np.inf.
194
+ """
195
+ if q == 0:
196
+ return 0
197
+
198
+ if q == 1.:
199
+ return alpha / (2 * sigma**2)
200
+
201
+ if np.isinf(alpha):
202
+ return np.inf
203
+
204
+ return _compute_log_a(q, sigma, alpha) / (alpha - 1)
205
+
206
+
207
+ def compute_rdp(q, noise_multiplier, steps, orders):
208
+ """Compute RDP of the Sampled Gaussian Mechanism.
209
+
210
+ Args:
211
+ q: The sampling rate.
212
+ noise_multiplier: The ratio of the standard deviation of the Gaussian noise
213
+ to the l2-sensitivity of the function to which it is added.
214
+ steps: The number of steps.
215
+ orders: An array (or a scalar) of RDP orders.
216
+
217
+ Returns:
218
+ The RDPs at all orders, can be np.inf.
219
+ """
220
+ if np.isscalar(orders):
221
+ rdp = _compute_rdp(q, noise_multiplier, orders)
222
+ else:
223
+ rdp = np.array([_compute_rdp(q, noise_multiplier, order)
224
+ for order in orders])
225
+
226
+ return rdp * steps
227
+
228
+
229
+ def get_privacy_spent(orders, rdp, target_eps=None, target_delta=None):
230
+ """Compute delta (or eps) for given eps (or delta) from RDP values.
231
+
232
+ Args:
233
+ orders: An array (or a scalar) of RDP orders.
234
+ rdp: An array of RDP values. Must be of the same length as the orders list.
235
+ target_eps: If not None, the epsilon for which we compute the corresponding
236
+ delta.
237
+ target_delta: If not None, the delta for which we compute the corresponding
238
+ epsilon. Exactly one of target_eps and target_delta must be None.
239
+
240
+ Returns:
241
+ eps, delta, opt_order.
242
+
243
+ Raises:
244
+ ValueError: If target_eps and target_delta are messed up.
245
+ """
246
+ if target_eps is None and target_delta is None:
247
+ raise ValueError(
248
+ "Exactly one out of eps and delta must be None. (Both are).")
249
+
250
+ if target_eps is not None and target_delta is not None:
251
+ raise ValueError(
252
+ "Exactly one out of eps and delta must be None. (None is).")
253
+
254
+ if target_eps is not None:
255
+ delta, opt_order = _compute_delta(orders, rdp, target_eps)
256
+ return target_eps, delta, opt_order
257
+ else:
258
+ eps, opt_order = _compute_eps(orders, rdp, target_delta)
259
+ return eps, target_delta, opt_order
260
+
261
+
262
+ def compute_rdp_from_ledger(ledger, orders):
263
+ """Compute RDP of Sampled Gaussian Mechanism from ledger.
264
+
265
+ Args:
266
+ ledger: A formatted privacy ledger.
267
+ orders: An array (or a scalar) of RDP orders.
268
+
269
+ Returns:
270
+ RDP at all orders, can be np.inf.
271
+ """
272
+ total_rdp = np.zeros_like(orders, dtype=float)
273
+ for sample in ledger:
274
+ # Compute equivalent z from l2_clip_bounds and noise stddevs in sample.
275
+ # See https://arxiv.org/pdf/1812.06210.pdf for derivation of this formula.
276
+ effective_z = sum([
277
+ (q.noise_stddev / q.l2_norm_bound)**-2 for q in sample.queries])**-0.5
278
+ total_rdp += compute_rdp(
279
+ sample.selection_probability, effective_z, 1, orders)
280
+ return total_rdp
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/ctabgan_synthesizer.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import torch
4
+ import torch.utils.data
5
+ import torch.optim as optim
6
+ from torch.optim import Adam
7
+ from torch.nn import functional as F
8
+ from torch.nn import (Dropout, LeakyReLU, Linear, Module, ReLU, Sequential,
9
+ Conv2d, ConvTranspose2d, Sigmoid, init, BCELoss, CrossEntropyLoss,SmoothL1Loss,LayerNorm)
10
+ from model.synthesizer.transformer import ImageTransformer,DataTransformer
11
+ from model.privacy_utils.rdp_accountant import compute_rdp, get_privacy_spent
12
+ from tqdm import tqdm
13
+
14
+
15
+ class Classifier(Module):
16
+ def __init__(self,input_dim, dis_dims,st_ed):
17
+ super(Classifier,self).__init__()
18
+ dim = input_dim-(st_ed[1]-st_ed[0])
19
+ seq = []
20
+ self.str_end = st_ed
21
+ for item in list(dis_dims):
22
+ seq += [
23
+ Linear(dim, item),
24
+ LeakyReLU(0.2),
25
+ Dropout(0.5)
26
+ ]
27
+ dim = item
28
+
29
+ if (st_ed[1]-st_ed[0])==1:
30
+ seq += [Linear(dim, 1)]
31
+
32
+ elif (st_ed[1]-st_ed[0])==2:
33
+ seq += [Linear(dim, 1),Sigmoid()]
34
+ else:
35
+ seq += [Linear(dim,(st_ed[1]-st_ed[0]))]
36
+
37
+ self.seq = Sequential(*seq)
38
+
39
+ def forward(self, input):
40
+
41
+ label=None
42
+
43
+ if (self.str_end[1]-self.str_end[0])==1:
44
+ label = input[:, self.str_end[0]:self.str_end[1]]
45
+ else:
46
+ label = torch.argmax(input[:, self.str_end[0]:self.str_end[1]], axis=-1)
47
+
48
+ new_imp = torch.cat((input[:,:self.str_end[0]],input[:,self.str_end[1]:]),1)
49
+
50
+ if ((self.str_end[1]-self.str_end[0])==2) | ((self.str_end[1]-self.str_end[0])==1):
51
+ return self.seq(new_imp).view(-1), label
52
+ else:
53
+ return self.seq(new_imp), label
54
+
55
+ def apply_activate(data, output_info):
56
+ data_t = []
57
+ st = 0
58
+ for item in output_info:
59
+ if item[1] == 'tanh':
60
+ ed = st + item[0]
61
+ data_t.append(torch.tanh(data[:, st:ed]))
62
+ st = ed
63
+ elif item[1] == 'softmax':
64
+ ed = st + item[0]
65
+ data_t.append(F.gumbel_softmax(data[:, st:ed], tau=0.2))
66
+ st = ed
67
+ return torch.cat(data_t, dim=1)
68
+
69
+ def get_st_ed(target_col_index,output_info):
70
+ st = 0
71
+ c= 0
72
+ tc= 0
73
+
74
+ for item in output_info:
75
+ if c==target_col_index:
76
+ break
77
+ if item[1]=='tanh':
78
+ st += item[0]
79
+ if item[2] == 'yes_g':
80
+ c+=1
81
+ elif item[1] == 'softmax':
82
+ st += item[0]
83
+ c+=1
84
+ tc+=1
85
+
86
+ ed= st+output_info[tc][0]
87
+
88
+ return (st,ed)
89
+
90
+ def random_choice_prob_index_sampling(probs,col_idx):
91
+ option_list = []
92
+ for i in col_idx:
93
+ pp = probs[i]
94
+ option_list.append(np.random.choice(np.arange(len(probs[i])), p=pp))
95
+
96
+ return np.array(option_list).reshape(col_idx.shape)
97
+
98
+ def random_choice_prob_index(a, axis=1):
99
+ r = np.expand_dims(np.random.rand(a.shape[1 - axis]), axis=axis)
100
+ return (a.cumsum(axis=axis) > r).argmax(axis=axis)
101
+
102
+ def maximum_interval(output_info):
103
+ max_interval = 0
104
+ for item in output_info:
105
+ max_interval = max(max_interval, item[0])
106
+ return max_interval
107
+
108
+ class Cond(object):
109
+ def __init__(self, data, output_info):
110
+
111
+ self.model = []
112
+ st = 0
113
+ counter = 0
114
+ for item in output_info:
115
+
116
+ if item[1] == 'tanh':
117
+ st += item[0]
118
+ continue
119
+ elif item[1] == 'softmax':
120
+ ed = st + item[0]
121
+ counter += 1
122
+ self.model.append(np.argmax(data[:, st:ed], axis=-1))
123
+ st = ed
124
+
125
+ self.interval = []
126
+ self.n_col = 0
127
+ self.n_opt = 0
128
+ st = 0
129
+ self.p = np.zeros((counter, maximum_interval(output_info)))
130
+ self.p_sampling = []
131
+ for item in output_info:
132
+ if item[1] == 'tanh':
133
+ st += item[0]
134
+ continue
135
+ elif item[1] == 'softmax':
136
+ ed = st + item[0]
137
+ tmp = np.sum(data[:, st:ed], axis=0)
138
+ tmp_sampling = np.sum(data[:, st:ed], axis=0)
139
+ tmp = np.log(tmp + 1)
140
+ tmp = tmp / np.sum(tmp)
141
+ tmp_sampling = tmp_sampling / np.sum(tmp_sampling)
142
+ self.p_sampling.append(tmp_sampling)
143
+ self.p[self.n_col, :item[0]] = tmp
144
+ self.interval.append((self.n_opt, item[0]))
145
+ self.n_opt += item[0]
146
+ self.n_col += 1
147
+ st = ed
148
+
149
+ self.interval = np.asarray(self.interval)
150
+
151
+ def sample_train(self, batch):
152
+ if self.n_col == 0:
153
+ return None
154
+ batch = batch
155
+
156
+ idx = np.random.choice(np.arange(self.n_col), batch)
157
+
158
+ vec = np.zeros((batch, self.n_opt), dtype='float32')
159
+ mask = np.zeros((batch, self.n_col), dtype='float32')
160
+ mask[np.arange(batch), idx] = 1
161
+ opt1prime = random_choice_prob_index(self.p[idx])
162
+ for i in np.arange(batch):
163
+ vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1
164
+
165
+ return vec, mask, idx, opt1prime
166
+
167
+ def sample(self, batch):
168
+ if self.n_col == 0:
169
+ return None
170
+ batch = batch
171
+
172
+ idx = np.random.choice(np.arange(self.n_col), batch)
173
+
174
+ vec = np.zeros((batch, self.n_opt), dtype='float32')
175
+ opt1prime = random_choice_prob_index_sampling(self.p_sampling,idx)
176
+
177
+ for i in np.arange(batch):
178
+ vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1
179
+
180
+ return vec
181
+
182
+ def cond_loss(data, output_info, c, m):
183
+ loss = []
184
+ st = 0
185
+ st_c = 0
186
+ for item in output_info:
187
+ if item[1] == 'tanh':
188
+ st += item[0]
189
+ continue
190
+
191
+ elif item[1] == 'softmax':
192
+ ed = st + item[0]
193
+ ed_c = st_c + item[0]
194
+ tmp = F.cross_entropy(
195
+ data[:, st:ed],
196
+ torch.argmax(c[:, st_c:ed_c], dim=1),
197
+ reduction='none')
198
+ loss.append(tmp)
199
+ st = ed
200
+ st_c = ed_c
201
+
202
+ loss = torch.stack(loss, dim=1)
203
+ return (loss * m).sum() / data.size()[0]
204
+
205
+ class Sampler(object):
206
+ def __init__(self, data, output_info):
207
+ super(Sampler, self).__init__()
208
+ self.data = data
209
+ self.model = []
210
+ self.n = len(data)
211
+ st = 0
212
+ for item in output_info:
213
+ if item[1] == 'tanh':
214
+ st += item[0]
215
+ continue
216
+ elif item[1] == 'softmax':
217
+ ed = st + item[0]
218
+ tmp = []
219
+ for j in range(item[0]):
220
+ tmp.append(np.nonzero(data[:, st + j])[0])
221
+ self.model.append(tmp)
222
+ st = ed
223
+
224
+ def sample(self, n, col, opt):
225
+ if col is None:
226
+ idx = np.random.choice(np.arange(self.n), n)
227
+ return self.data[idx]
228
+ idx = []
229
+ for c, o in zip(col, opt):
230
+ idx.append(np.random.choice(self.model[c][o]))
231
+ return self.data[idx]
232
+
233
+ class Discriminator(Module):
234
+ def __init__(self, side, layers):
235
+ super(Discriminator, self).__init__()
236
+ self.side = side
237
+ info = len(layers)-2
238
+ self.seq = Sequential(*layers)
239
+ self.seq_info = Sequential(*layers[:info])
240
+
241
+ def forward(self, input):
242
+ return (self.seq(input)), self.seq_info(input)
243
+
244
+ class Generator(Module):
245
+ def __init__(self, side, layers):
246
+ super(Generator, self).__init__()
247
+ self.side = side
248
+ self.seq = Sequential(*layers)
249
+
250
+ def forward(self, input_):
251
+ return self.seq(input_)
252
+
253
+ def determine_layers_disc(side, num_channels):
254
+ assert side >= 4 and side <= 64
255
+
256
+ layer_dims = [(1, side), (num_channels, side // 2)]
257
+
258
+ while layer_dims[-1][1] > 3 and len(layer_dims) < 4:
259
+ layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2))
260
+
261
+ layerNorms = []
262
+ num_c = num_channels
263
+ num_s = side / 2
264
+ for l in range(len(layer_dims) - 1):
265
+ layerNorms.append([int(num_c), int(num_s), int(num_s)])
266
+ num_c = num_c * 2
267
+ num_s = num_s / 2
268
+
269
+ layers_D = []
270
+
271
+ for prev, curr, ln in zip(layer_dims, layer_dims[1:], layerNorms):
272
+ layers_D += [
273
+ Conv2d(prev[0], curr[0], 4, 2, 1, bias=False),
274
+ LayerNorm(ln),
275
+ LeakyReLU(0.2, inplace=True),
276
+ ]
277
+
278
+ layers_D += [Conv2d(layer_dims[-1][0], 1, layer_dims[-1][1], 1, 0), ReLU(True)]
279
+
280
+ return layers_D
281
+
282
+ def determine_layers_gen(side, random_dim, num_channels):
283
+ assert side >= 4 and side <= 64
284
+
285
+ layer_dims = [(1, side), (num_channels, side // 2)]
286
+
287
+ while layer_dims[-1][1] > 3 and len(layer_dims) < 4:
288
+ layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2))
289
+
290
+ layerNorms = []
291
+
292
+ num_c = num_channels * (2 ** (len(layer_dims) - 2))
293
+ num_s = int(side / (2 ** (len(layer_dims) - 1)))
294
+ for l in range(len(layer_dims) - 1):
295
+ layerNorms.append([int(num_c), int(num_s), int(num_s)])
296
+ num_c = num_c / 2
297
+ num_s = num_s * 2
298
+
299
+ layers_G = [ConvTranspose2d(random_dim, layer_dims[-1][0], layer_dims[-1][1], 1, 0, output_padding=0, bias=False)]
300
+
301
+ for prev, curr, ln in zip(reversed(layer_dims), reversed(layer_dims[:-1]), layerNorms):
302
+ layers_G += [LayerNorm(ln), ReLU(True), ConvTranspose2d(prev[0], curr[0], 4, 2, 1, output_padding=0, bias=True)]
303
+ return layers_G
304
+
305
+ def slerp(val, low, high):
306
+ low_norm = low/torch.norm(low, dim=1, keepdim=True)
307
+ high_norm = high/torch.norm(high, dim=1, keepdim=True)
308
+ omega = torch.acos((low_norm*high_norm).sum(1)).view(val.size(0), 1)
309
+ so = torch.sin(omega)
310
+ res = (torch.sin((1.0-val)*omega)/so)*low + (torch.sin(val*omega)/so) * high
311
+
312
+ return res
313
+
314
+ def calc_gradient_penalty_slerp(netD, real_data, fake_data, transformer, device='cpu', lambda_=10):
315
+ batchsize = real_data.shape[0]
316
+ alpha = torch.rand(batchsize, 1, device=device)
317
+ interpolates = slerp(alpha, real_data, fake_data)
318
+ interpolates = interpolates.to(device)
319
+ interpolates = transformer.transform(interpolates)
320
+ interpolates = torch.autograd.Variable(interpolates, requires_grad=True)
321
+ disc_interpolates,_ = netD(interpolates)
322
+
323
+ gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates,
324
+ grad_outputs=torch.ones(disc_interpolates.size()).to(device),
325
+ create_graph=True, retain_graph=True, only_inputs=True)[0]
326
+
327
+ gradients_norm = gradients.norm(2, dim=1)
328
+ gradient_penalty = ((gradients_norm - 1) ** 2).mean() * lambda_
329
+
330
+ return gradient_penalty
331
+
332
+ def weights_init(m):
333
+ classname = m.__class__.__name__
334
+
335
+ if classname.find('Conv') != -1:
336
+ init.normal_(m.weight.data, 0.0, 0.02)
337
+
338
+ elif classname.find('BatchNorm') != -1:
339
+ init.normal_(m.weight.data, 1.0, 0.02)
340
+ init.constant_(m.bias.data, 0)
341
+
342
+ class CTABGANSynthesizer:
343
+ def __init__(self,
344
+ class_dim=(256, 256, 256, 256),
345
+ random_dim=100,
346
+ num_channels=64,
347
+ l2scale=1e-5,
348
+ batch_size=500,
349
+ epochs=150,
350
+ device="cpu"):
351
+
352
+
353
+ self.random_dim = random_dim
354
+ self.class_dim = class_dim
355
+ self.num_channels = num_channels
356
+ self.dside = None
357
+ self.gside = None
358
+ self.l2scale = l2scale
359
+ self.batch_size = batch_size
360
+ self.epochs = epochs
361
+ self.device = torch.device(device)
362
+
363
+ def fit(self, train_data=pd.DataFrame, categorical=[], mixed={}, general=[], non_categorical=[], type={}):
364
+
365
+ problem_type = None
366
+ target_index=None
367
+ if type:
368
+ problem_type = list(type.keys())[0]
369
+ if problem_type:
370
+ target_index = train_data.columns.get_loc(type[problem_type])
371
+
372
+ self.transformer = DataTransformer(train_data=train_data, categorical_list=categorical, mixed_dict=mixed, general_list=general, non_categorical_list=non_categorical)
373
+ self.transformer.fit()
374
+ train_data = self.transformer.transform(train_data.values)
375
+ data_sampler = Sampler(train_data, self.transformer.output_info)
376
+ data_dim = self.transformer.output_dim
377
+ self.cond_generator = Cond(train_data, self.transformer.output_info)
378
+
379
+ sides = [4, 8, 16, 24, 64]
380
+ col_size_d = data_dim + self.cond_generator.n_opt
381
+ for i in sides:
382
+ if i * i >= col_size_d:
383
+ self.dside = i
384
+ break
385
+
386
+ sides = [4, 8, 16, 24, 64]
387
+ col_size_g = data_dim
388
+ for i in sides:
389
+ if i * i >= col_size_g:
390
+ self.gside = i
391
+ break
392
+
393
+
394
+ layers_G = determine_layers_gen(self.gside, self.random_dim+self.cond_generator.n_opt, self.num_channels)
395
+ layers_D = determine_layers_disc(self.dside, self.num_channels)
396
+
397
+ self.generator = Generator(self.gside, layers_G).to(self.device)
398
+ discriminator = Discriminator(self.dside, layers_D).to(self.device)
399
+ optimizer_params = dict(lr=2e-4, betas=(0.5, 0.9), eps=1e-3, weight_decay=self.l2scale)
400
+ optimizerG = Adam(self.generator.parameters(), **optimizer_params)
401
+ optimizerD = Adam(discriminator.parameters(), **optimizer_params)
402
+
403
+ st_ed = None
404
+ classifier=None
405
+ optimizerC= None
406
+ if target_index != None:
407
+ st_ed= get_st_ed(target_index,self.transformer.output_info)
408
+ classifier = Classifier(data_dim,self.class_dim,st_ed).to(self.device)
409
+ optimizerC = optim.Adam(classifier.parameters(),**optimizer_params)
410
+
411
+
412
+ self.generator.apply(weights_init)
413
+ discriminator.apply(weights_init)
414
+
415
+ self.Gtransformer = ImageTransformer(self.gside)
416
+ self.Dtransformer = ImageTransformer(self.dside)
417
+
418
+ epsilon = 0
419
+ epoch = 0
420
+ steps = 0
421
+ ci = 1
422
+
423
+ for i in tqdm(range(self.epochs)):
424
+
425
+
426
+ for _ in range(ci):
427
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
428
+ condvec = self.cond_generator.sample_train(self.batch_size)
429
+
430
+ c, m, col, opt = condvec
431
+ c = torch.from_numpy(c).to(self.device)
432
+ m = torch.from_numpy(m).to(self.device)
433
+ noisez = torch.cat([noisez, c], dim=1)
434
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
435
+
436
+ perm = np.arange(self.batch_size)
437
+ np.random.shuffle(perm)
438
+ real = data_sampler.sample(self.batch_size, col[perm], opt[perm])
439
+ c_perm = c[perm]
440
+
441
+ real = torch.from_numpy(real.astype('float32')).to(self.device)
442
+
443
+ fake = self.generator(noisez)
444
+ faket = self.Gtransformer.inverse_transform(fake)
445
+ fakeact = apply_activate(faket, self.transformer.output_info)
446
+
447
+ fake_cat = torch.cat([fakeact, c], dim=1)
448
+ real_cat = torch.cat([real, c_perm], dim=1)
449
+
450
+ real_cat_d = self.Dtransformer.transform(real_cat)
451
+ fake_cat_d = self.Dtransformer.transform(fake_cat)
452
+
453
+ optimizerD.zero_grad()
454
+
455
+ d_real,_ = discriminator(real_cat_d)
456
+
457
+
458
+ d_real = -torch.mean(d_real)
459
+ d_real.backward()
460
+
461
+
462
+ d_fake,_ = discriminator(fake_cat_d)
463
+
464
+ d_fake = torch.mean(d_fake)
465
+
466
+ d_fake.backward()
467
+
468
+ pen = calc_gradient_penalty_slerp(discriminator, real_cat, fake_cat, self.Dtransformer , self.device)
469
+
470
+ pen.backward()
471
+
472
+ optimizerD.step()
473
+
474
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
475
+
476
+ condvec = self.cond_generator.sample_train(self.batch_size)
477
+
478
+ c, m, col, opt = condvec
479
+ c = torch.from_numpy(c).to(self.device)
480
+ m = torch.from_numpy(m).to(self.device)
481
+ noisez = torch.cat([noisez, c], dim=1)
482
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
483
+
484
+ optimizerG.zero_grad()
485
+
486
+ fake = self.generator(noisez)
487
+ faket = self.Gtransformer.inverse_transform(fake)
488
+ fakeact = apply_activate(faket, self.transformer.output_info)
489
+
490
+ fake_cat = torch.cat([fakeact, c], dim=1)
491
+ fake_cat = self.Dtransformer.transform(fake_cat)
492
+
493
+ y_fake,info_fake = discriminator(fake_cat)
494
+
495
+ cross_entropy = cond_loss(faket, self.transformer.output_info, c, m)
496
+
497
+ _,info_real = discriminator(real_cat_d)
498
+
499
+
500
+ g = -torch.mean(y_fake) + cross_entropy
501
+ g.backward(retain_graph=True)
502
+ loss_mean = torch.norm(torch.mean(info_fake.view(self.batch_size,-1), dim=0) - torch.mean(info_real.view(self.batch_size,-1), dim=0), 1)
503
+ loss_std = torch.norm(torch.std(info_fake.view(self.batch_size,-1), dim=0) - torch.std(info_real.view(self.batch_size,-1), dim=0), 1)
504
+ loss_info = loss_mean + loss_std
505
+ loss_info.backward()
506
+ optimizerG.step()
507
+
508
+
509
+ if problem_type:
510
+
511
+ fake = self.generator(noisez)
512
+
513
+ faket = self.Gtransformer.inverse_transform(fake)
514
+
515
+ fakeact = apply_activate(faket, self.transformer.output_info)
516
+
517
+ real_pre, real_label = classifier(real)
518
+ fake_pre, fake_label = classifier(fakeact)
519
+
520
+ c_loss = CrossEntropyLoss()
521
+
522
+ if (st_ed[1] - st_ed[0])==1:
523
+ c_loss= SmoothL1Loss()
524
+ real_label = real_label.type_as(real_pre)
525
+ fake_label = fake_label.type_as(fake_pre)
526
+ real_label = torch.reshape(real_label,real_pre.size())
527
+ fake_label = torch.reshape(fake_label,fake_pre.size())
528
+
529
+
530
+ elif (st_ed[1] - st_ed[0])==2:
531
+ c_loss = BCELoss()
532
+ real_label = real_label.type_as(real_pre)
533
+ fake_label = fake_label.type_as(fake_pre)
534
+
535
+ loss_cc = c_loss(real_pre, real_label)
536
+ loss_cg = c_loss(fake_pre, fake_label)
537
+
538
+ optimizerG.zero_grad()
539
+ loss_cg.backward()
540
+ optimizerG.step()
541
+
542
+ optimizerC.zero_grad()
543
+ loss_cc.backward()
544
+ optimizerC.step()
545
+
546
+
547
+
548
+
549
+ @torch.no_grad()
550
+ def sample(self, n, seed=0):
551
+
552
+ torch.manual_seed(seed)
553
+ torch.cuda.manual_seed(seed)
554
+ sample_batch_size = 8092
555
+ self.generator.eval()
556
+
557
+ output_info = self.transformer.output_info
558
+ steps = n // sample_batch_size + 1
559
+
560
+ data = []
561
+
562
+ for i in range(steps):
563
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
564
+ condvec = self.cond_generator.sample(self.batch_size)
565
+ c = condvec
566
+ c = torch.from_numpy(c).to(self.device)
567
+ noisez = torch.cat([noisez, c], dim=1)
568
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
569
+
570
+ fake = self.generator(noisez)
571
+ faket = self.Gtransformer.inverse_transform(fake)
572
+ fakeact = apply_activate(faket,output_info)
573
+ data.append(fakeact.detach().cpu().numpy())
574
+
575
+ data = np.concatenate(data, axis=0)
576
+ result,resample = self.transformer.inverse_transform(data)
577
+
578
+ while len(result) < n:
579
+ data_resample = []
580
+ steps_left = resample// self.batch_size + 1
581
+
582
+ for i in range(steps_left):
583
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
584
+ condvec = self.cond_generator.sample(self.batch_size)
585
+ c = condvec
586
+ c = torch.from_numpy(c).to(self.device)
587
+ noisez = torch.cat([noisez, c], dim=1)
588
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
589
+
590
+ fake = self.generator(noisez)
591
+ faket = self.Gtransformer.inverse_transform(fake)
592
+ fakeact = apply_activate(faket, output_info)
593
+ data_resample.append(fakeact.detach().cpu().numpy())
594
+
595
+ data_resample = np.concatenate(data_resample, axis=0)
596
+
597
+ res,resample = self.transformer.inverse_transform(data_resample)
598
+ result = np.concatenate([result,res],axis=0)
599
+
600
+ return result[0:n]
601
+
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/transformer.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import torch
4
+ from sklearn.mixture import BayesianGaussianMixture
5
+
6
+ class DataTransformer():
7
+
8
+ def __init__(self, train_data=pd.DataFrame, categorical_list=[], mixed_dict={}, general_list=[], non_categorical_list=[], n_clusters=10, eps=0.005):
9
+ self.meta = None
10
+ self.n_clusters = n_clusters
11
+ self.eps = eps
12
+ self.train_data = train_data
13
+ self.categorical_columns= categorical_list
14
+ self.mixed_columns= mixed_dict
15
+ self.general_columns = general_list
16
+ self.non_categorical_columns= non_categorical_list
17
+
18
+ def get_metadata(self):
19
+
20
+ meta = []
21
+
22
+ for index in range(self.train_data.shape[1]):
23
+ column = self.train_data.iloc[:,index]
24
+ if index in self.categorical_columns:
25
+ if index in self.non_categorical_columns:
26
+ meta.append({
27
+ "name": index,
28
+ "type": "continuous",
29
+ "min": column.min(),
30
+ "max": column.max(),
31
+ })
32
+ else:
33
+ mapper = column.value_counts().index.tolist()
34
+ meta.append({
35
+ "name": index,
36
+ "type": "categorical",
37
+ "size": len(mapper),
38
+ "i2s": mapper
39
+ })
40
+
41
+ elif index in self.mixed_columns.keys():
42
+ meta.append({
43
+ "name": index,
44
+ "type": "mixed",
45
+ "min": column.min(),
46
+ "max": column.max(),
47
+ "modal": self.mixed_columns[index]
48
+ })
49
+ else:
50
+ meta.append({
51
+ "name": index,
52
+ "type": "continuous",
53
+ "min": column.min(),
54
+ "max": column.max(),
55
+ })
56
+
57
+ return meta
58
+
59
+ def fit(self):
60
+ data = self.train_data.values
61
+ self.meta = self.get_metadata()
62
+ model = []
63
+ self.ordering = []
64
+ self.output_info = []
65
+ self.output_dim = 0
66
+ self.components = []
67
+ self.filter_arr = []
68
+ for id_, info in enumerate(self.meta):
69
+ if info['type'] == "continuous":
70
+ if id_ not in self.general_columns:
71
+ gm = BayesianGaussianMixture(
72
+ n_components = self.n_clusters,
73
+ weight_concentration_prior_type='dirichlet_process',
74
+ weight_concentration_prior=0.001,
75
+ max_iter=100,n_init=1, random_state=42)
76
+ gm.fit(data[:, id_].reshape([-1, 1]))
77
+ mode_freq = (pd.Series(gm.predict(data[:, id_].reshape([-1, 1]))).value_counts().keys())
78
+ model.append(gm)
79
+ old_comp = gm.weights_ > self.eps
80
+ comp = []
81
+ for i in range(self.n_clusters):
82
+ if (i in (mode_freq)) & old_comp[i]:
83
+ comp.append(True)
84
+ else:
85
+ comp.append(False)
86
+ self.components.append(comp)
87
+ self.output_info += [(1, 'tanh','no_g'), (np.sum(comp), 'softmax')]
88
+ self.output_dim += 1 + np.sum(comp)
89
+ else:
90
+ model.append(None)
91
+ self.components.append(None)
92
+ self.output_info += [(1, 'tanh','yes_g')]
93
+ self.output_dim += 1
94
+
95
+ elif info['type'] == "mixed":
96
+
97
+ gm1 = BayesianGaussianMixture(
98
+ n_components = self.n_clusters,
99
+ weight_concentration_prior_type='dirichlet_process',
100
+ weight_concentration_prior=0.001, max_iter=100,
101
+ n_init=1,random_state=42)
102
+ gm2 = BayesianGaussianMixture(
103
+ n_components = self.n_clusters,
104
+ weight_concentration_prior_type='dirichlet_process',
105
+ weight_concentration_prior=0.001, max_iter=100,
106
+ n_init=1,random_state=42)
107
+
108
+ gm1.fit(data[:, id_].reshape([-1, 1]))
109
+
110
+ filter_arr = []
111
+ for element in data[:, id_]:
112
+ if element not in info['modal']:
113
+ filter_arr.append(True)
114
+ else:
115
+ filter_arr.append(False)
116
+
117
+ gm2.fit(data[:, id_][filter_arr].reshape([-1, 1]))
118
+ mode_freq = (pd.Series(gm2.predict(data[:, id_][filter_arr].reshape([-1, 1]))).value_counts().keys())
119
+ self.filter_arr.append(filter_arr)
120
+ model.append((gm1,gm2))
121
+
122
+ old_comp = gm2.weights_ > self.eps
123
+
124
+ comp = []
125
+
126
+ for i in range(self.n_clusters):
127
+ if (i in (mode_freq)) & old_comp[i]:
128
+ comp.append(True)
129
+ else:
130
+ comp.append(False)
131
+
132
+ self.components.append(comp)
133
+
134
+ self.output_info += [(1, 'tanh',"no_g"), (np.sum(comp) + len(info['modal']), 'softmax')]
135
+ self.output_dim += 1 + np.sum(comp) + len(info['modal'])
136
+ else:
137
+ model.append(None)
138
+ self.components.append(None)
139
+ self.output_info += [(info['size'], 'softmax')]
140
+ self.output_dim += info['size']
141
+ self.model = model
142
+
143
+ def transform(self, data, ispositive = False, positive_list = None):
144
+ values = []
145
+ mixed_counter = 0
146
+ for id_, info in enumerate(self.meta):
147
+ current = data[:, id_]
148
+ if info['type'] == "continuous":
149
+ if id_ not in self.general_columns:
150
+ current = current.reshape([-1, 1])
151
+ means = self.model[id_].means_.reshape((1, self.n_clusters))
152
+ stds = np.sqrt(self.model[id_].covariances_).reshape((1, self.n_clusters))
153
+ features = np.empty(shape=(len(current),self.n_clusters))
154
+ if ispositive == True:
155
+ if id_ in positive_list:
156
+ features = np.abs(current - means) / (4 * stds)
157
+ else:
158
+ features = (current - means) / (4 * stds)
159
+
160
+ probs = self.model[id_].predict_proba(current.reshape([-1, 1]))
161
+ n_opts = sum(self.components[id_])
162
+ features = features[:, self.components[id_]]
163
+ probs = probs[:, self.components[id_]]
164
+
165
+ opt_sel = np.zeros(len(data), dtype='int')
166
+ for i in range(len(data)):
167
+ pp = probs[i] + 1e-6
168
+ pp = pp / sum(pp)
169
+ opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp)
170
+
171
+ idx = np.arange((len(features)))
172
+ features = features[idx, opt_sel].reshape([-1, 1])
173
+ features = np.clip(features, -.99, .99)
174
+ probs_onehot = np.zeros_like(probs)
175
+ probs_onehot[np.arange(len(probs)), opt_sel] = 1
176
+
177
+ re_ordered_phot = np.zeros_like(probs_onehot)
178
+
179
+ col_sums = probs_onehot.sum(axis=0)
180
+
181
+
182
+ n = probs_onehot.shape[1]
183
+ largest_indices = np.argsort(-1*col_sums)[:n]
184
+ self.ordering.append(largest_indices)
185
+ for id,val in enumerate(largest_indices):
186
+ re_ordered_phot[:,id] = probs_onehot[:,val]
187
+
188
+
189
+ values += [features, re_ordered_phot]
190
+
191
+ else:
192
+
193
+ self.ordering.append(None)
194
+
195
+ if id_ in self.non_categorical_columns:
196
+ info['min'] = -1e-3
197
+ info['max'] = info['max'] + 1e-3
198
+
199
+ current = (current - (info['min'])) / (info['max'] - info['min'])
200
+ current = current * 2 - 1
201
+ current = current.reshape([-1, 1])
202
+ values.append(current)
203
+
204
+ elif info['type'] == "mixed":
205
+
206
+ means_0 = self.model[id_][0].means_.reshape([-1])
207
+ stds_0 = np.sqrt(self.model[id_][0].covariances_).reshape([-1])
208
+
209
+ zero_std_list = []
210
+ means_needed = []
211
+ stds_needed = []
212
+
213
+ for mode in info['modal']:
214
+ if mode!=-9999999:
215
+ dist = []
216
+ for idx,val in enumerate(list(means_0.flatten())):
217
+ dist.append(abs(mode-val))
218
+ index_min = np.argmin(np.array(dist))
219
+ zero_std_list.append(index_min)
220
+ else: continue
221
+
222
+ for idx in zero_std_list:
223
+ means_needed.append(means_0[idx])
224
+ stds_needed.append(stds_0[idx])
225
+
226
+
227
+ mode_vals = []
228
+
229
+ for i,j,k in zip(info['modal'],means_needed,stds_needed):
230
+ this_val = np.abs(i - j) / (4*k)
231
+ mode_vals.append(this_val)
232
+
233
+ if -9999999 in info["modal"]:
234
+ mode_vals.append(0)
235
+
236
+ current = current.reshape([-1, 1])
237
+ filter_arr = self.filter_arr[mixed_counter]
238
+ current = current[filter_arr]
239
+
240
+ means = self.model[id_][1].means_.reshape((1, self.n_clusters))
241
+ stds = np.sqrt(self.model[id_][1].covariances_).reshape((1, self.n_clusters))
242
+ features = np.empty(shape=(len(current),self.n_clusters))
243
+ if ispositive == True:
244
+ if id_ in positive_list:
245
+ features = np.abs(current - means) / (4 * stds)
246
+ else:
247
+ features = (current - means) / (4 * stds)
248
+
249
+ probs = self.model[id_][1].predict_proba(current.reshape([-1, 1]))
250
+
251
+ n_opts = sum(self.components[id_]) # 8
252
+ features = features[:, self.components[id_]]
253
+ probs = probs[:, self.components[id_]]
254
+
255
+ opt_sel = np.zeros(len(current), dtype='int')
256
+ for i in range(len(current)):
257
+ pp = probs[i] + 1e-6
258
+ pp = pp / sum(pp)
259
+ opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp)
260
+ idx = np.arange((len(features)))
261
+ features = features[idx, opt_sel].reshape([-1, 1])
262
+ features = np.clip(features, -.99, .99)
263
+ probs_onehot = np.zeros_like(probs)
264
+ probs_onehot[np.arange(len(probs)), opt_sel] = 1
265
+ extra_bits = np.zeros([len(current), len(info['modal'])])
266
+ temp_probs_onehot = np.concatenate([extra_bits,probs_onehot], axis = 1)
267
+ final = np.zeros([len(data), 1 + probs_onehot.shape[1] + len(info['modal'])])
268
+ features_curser = 0
269
+ for idx, val in enumerate(data[:, id_]):
270
+ if val in info['modal']:
271
+ category_ = list(map(info['modal'].index, [val]))[0]
272
+ final[idx, 0] = mode_vals[category_]
273
+ final[idx, (category_+1)] = 1
274
+
275
+ else:
276
+ final[idx, 0] = features[features_curser]
277
+ final[idx, (1+len(info['modal'])):] = temp_probs_onehot[features_curser][len(info['modal']):]
278
+ features_curser = features_curser + 1
279
+
280
+ just_onehot = final[:,1:]
281
+ re_ordered_jhot= np.zeros_like(just_onehot)
282
+ n = just_onehot.shape[1]
283
+ col_sums = just_onehot.sum(axis=0)
284
+ largest_indices = np.argsort(-1*col_sums)[:n]
285
+ self.ordering.append(largest_indices)
286
+ for id,val in enumerate(largest_indices):
287
+ re_ordered_jhot[:,id] = just_onehot[:,val]
288
+ final_features = final[:,0].reshape([-1, 1])
289
+ values += [final_features, re_ordered_jhot]
290
+ mixed_counter = mixed_counter + 1
291
+
292
+ else:
293
+ self.ordering.append(None)
294
+ col_t = np.zeros([len(data), info['size']])
295
+ idx = list(map(info['i2s'].index, current))
296
+ col_t[np.arange(len(data)), idx] = 1
297
+ values.append(col_t)
298
+
299
+ return np.concatenate(values, axis=1)
300
+
301
+ def inverse_transform(self, data):
302
+ data_t = np.zeros([len(data), len(self.meta)])
303
+ invalid_ids = []
304
+ st = 0
305
+ for id_, info in enumerate(self.meta):
306
+ if info['type'] == "continuous":
307
+ if id_ not in self.general_columns:
308
+ u = data[:, st]
309
+ v = data[:, st + 1:st + 1 + np.sum(self.components[id_])]
310
+ order = self.ordering[id_]
311
+ v_re_ordered = np.zeros_like(v)
312
+
313
+ for id,val in enumerate(order):
314
+ v_re_ordered[:,val] = v[:,id]
315
+
316
+ v = v_re_ordered
317
+
318
+ u = np.clip(u, -1, 1)
319
+ v_t = np.ones((data.shape[0], self.n_clusters)) * -100
320
+ v_t[:, self.components[id_]] = v
321
+ v = v_t
322
+ st += 1 + np.sum(self.components[id_])
323
+ means = self.model[id_].means_.reshape([-1])
324
+ stds = np.sqrt(self.model[id_].covariances_).reshape([-1])
325
+ p_argmax = np.argmax(v, axis=1)
326
+ std_t = stds[p_argmax]
327
+ mean_t = means[p_argmax]
328
+ tmp = u * 4 * std_t + mean_t
329
+
330
+ for idx,val in enumerate(tmp):
331
+ if (val < info["min"]) | (val > info['max']):
332
+ invalid_ids.append(idx)
333
+
334
+ if id_ in self.non_categorical_columns:
335
+
336
+ tmp = np.round(tmp)
337
+
338
+ data_t[:, id_] = tmp
339
+
340
+ else:
341
+ u = data[:, st]
342
+ u = (u + 1) / 2
343
+ u = np.clip(u, 0, 1)
344
+ u = u * (info['max'] - info['min']) + info['min']
345
+ if id_ in self.non_categorical_columns:
346
+ data_t[:, id_] = np.round(u)
347
+ else: data_t[:, id_] = u
348
+
349
+ st += 1
350
+
351
+ elif info['type'] == "mixed":
352
+
353
+ u = data[:, st]
354
+ full_v = data[:,(st+1):(st+1)+len(info['modal'])+np.sum(self.components[id_])]
355
+ order = self.ordering[id_]
356
+ full_v_re_ordered = np.zeros_like(full_v)
357
+
358
+ for id,val in enumerate(order):
359
+ full_v_re_ordered[:,val] = full_v[:,id]
360
+
361
+ full_v = full_v_re_ordered
362
+
363
+
364
+ mixed_v = full_v[:,:len(info['modal'])]
365
+ v = full_v[:,-np.sum(self.components[id_]):]
366
+
367
+ u = np.clip(u, -1, 1)
368
+ v_t = np.ones((data.shape[0], self.n_clusters)) * -100
369
+ v_t[:, self.components[id_]] = v
370
+ v = np.concatenate([mixed_v,v_t], axis=1)
371
+
372
+ st += 1 + np.sum(self.components[id_]) + len(info['modal'])
373
+ means = self.model[id_][1].means_.reshape([-1])
374
+ stds = np.sqrt(self.model[id_][1].covariances_).reshape([-1])
375
+ p_argmax = np.argmax(v, axis=1)
376
+
377
+ result = np.zeros_like(u)
378
+
379
+ for idx in range(len(data)):
380
+ if p_argmax[idx] < len(info['modal']):
381
+ argmax_value = p_argmax[idx]
382
+ result[idx] = float(list(map(info['modal'].__getitem__, [argmax_value]))[0])
383
+ else:
384
+ std_t = stds[(p_argmax[idx]-len(info['modal']))]
385
+ mean_t = means[(p_argmax[idx]-len(info['modal']))]
386
+ result[idx] = u[idx] * 4 * std_t + mean_t
387
+
388
+ for idx,val in enumerate(result):
389
+ if (val < info["min"]) | (val > info['max']):
390
+ invalid_ids.append(idx)
391
+
392
+ data_t[:, id_] = result
393
+
394
+ else:
395
+ current = data[:, st:st + info['size']]
396
+ st += info['size']
397
+ idx = np.argmax(current, axis=1)
398
+ data_t[:, id_] = list(map(info['i2s'].__getitem__, idx))
399
+
400
+
401
+ invalid_ids = np.unique(np.array(invalid_ids))
402
+ all_ids = np.arange(0,len(data))
403
+ valid_ids = list(set(all_ids) - set(invalid_ids))
404
+
405
+ return data_t[valid_ids],len(invalid_ids)
406
+
407
+
408
+ class ImageTransformer():
409
+
410
+ def __init__(self, side):
411
+
412
+ self.height = side
413
+
414
+ def transform(self, data):
415
+
416
+ if self.height * self.height > len(data[0]):
417
+
418
+ padding = torch.zeros((len(data), self.height * self.height - len(data[0]))).to(data.device)
419
+ data = torch.cat([data, padding], axis=1)
420
+
421
+ return data.view(-1, 1, self.height, self.height)
422
+
423
+ def inverse_transform(self, data):
424
+
425
+ data = data.view(-1, self.height * self.height)
426
+
427
+ return data
428
+
429
+
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generative model training algorithm based on the CTABGANSynthesiser
3
+
4
+ """
5
+ import pandas as pd
6
+ import time
7
+ from model.pipeline.data_preparation import DataPrep
8
+ from model.synthesizer.ctabgan_synthesizer import CTABGANSynthesizer
9
+
10
+ import warnings
11
+
12
+ warnings.filterwarnings("ignore")
13
+
14
+ class CTABGAN():
15
+
16
+ def __init__(self,
17
+ df,
18
+ test_ratio = 0.20,
19
+ categorical_columns = [],
20
+ log_columns = [],
21
+ mixed_columns= {},
22
+ general_columns = [],
23
+ non_categorical_columns = [],
24
+ integer_columns = [],
25
+ problem_type= {},
26
+ class_dim=(256, 256, 256, 256),
27
+ random_dim=100,
28
+ num_channels=64,
29
+ l2scale=1e-5,
30
+ batch_size=500,
31
+ epochs=150,
32
+ lr=2e-4,
33
+ device="cpu"):
34
+
35
+ self.__name__ = 'CTABGAN'
36
+
37
+ self.synthesizer = CTABGANSynthesizer(
38
+ class_dim=class_dim,
39
+ random_dim=random_dim,
40
+ num_channels=num_channels,
41
+ l2scale=l2scale,
42
+ lr=lr,
43
+ batch_size=batch_size,
44
+ epochs=epochs,
45
+ device=device
46
+ )
47
+ self.raw_df = df
48
+ self.test_ratio = test_ratio
49
+ self.categorical_columns = categorical_columns
50
+ self.log_columns = log_columns
51
+ self.mixed_columns = mixed_columns
52
+ self.general_columns = general_columns
53
+ self.non_categorical_columns = non_categorical_columns
54
+ self.integer_columns = integer_columns
55
+ self.problem_type = problem_type
56
+
57
+ def fit(self):
58
+
59
+ start_time = time.time()
60
+ self.data_prep = DataPrep(self.raw_df,self.categorical_columns,self.log_columns,self.mixed_columns,self.general_columns,self.non_categorical_columns,self.integer_columns,self.problem_type,self.test_ratio)
61
+ self.synthesizer.fit(train_data=self.data_prep.df, categorical = self.data_prep.column_types["categorical"], mixed = self.data_prep.column_types["mixed"],
62
+ general = self.data_prep.column_types["general"], non_categorical = self.data_prep.column_types["non_categorical"], type=self.problem_type)
63
+ end_time = time.time()
64
+ print('Finished training in',end_time-start_time," seconds.")
65
+
66
+
67
+ def generate_samples(self, num_samples, seed=0):
68
+
69
+ sample = self.synthesizer.sample(num_samples, seed)
70
+ sample_df = self.data_prep.inverse_prep(sample)
71
+
72
+ return sample_df
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/eval/evaluation.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn import metrics
4
+ from sklearn import model_selection
5
+ from sklearn.preprocessing import MinMaxScaler,StandardScaler
6
+ from sklearn.neural_network import MLPClassifier
7
+ from sklearn.linear_model import LogisticRegression
8
+ from sklearn import svm,tree
9
+ from sklearn.ensemble import RandomForestClassifier
10
+ from dython.nominal import compute_associations
11
+ from scipy.stats import wasserstein_distance
12
+ from scipy.spatial import distance
13
+ import warnings
14
+
15
+ warnings.filterwarnings("ignore")
16
+
17
+ def supervised_model_training(x_train, y_train, x_test,
18
+ y_test, model_name):
19
+
20
+
21
+ if model_name == 'lr':
22
+ model = LogisticRegression(random_state=42,max_iter=500)
23
+ elif model_name == 'svm':
24
+ model = svm.SVC(random_state=42,probability=True)
25
+ elif model_name == 'dt':
26
+ model = tree.DecisionTreeClassifier(random_state=42)
27
+ elif model_name == 'rf':
28
+ model = RandomForestClassifier(random_state=42)
29
+ elif model_name == "mlp":
30
+ model = MLPClassifier(random_state=42,max_iter=100)
31
+
32
+ model.fit(x_train, y_train)
33
+ pred = model.predict(x_test)
34
+
35
+ if len(np.unique(y_train))>2:
36
+ predict = model.predict_proba(x_test)
37
+ acc = metrics.accuracy_score(y_test,pred)*100
38
+ auc = metrics.roc_auc_score(y_test, predict,average="weighted",multi_class="ovr")
39
+ f1_score = metrics.precision_recall_fscore_support(y_test, pred,average="weighted")[2]
40
+ return [acc, auc,f1_score]
41
+
42
+ else:
43
+ predict = model.predict_proba(x_test)[:,1]
44
+ acc = metrics.accuracy_score(y_test,pred)*100
45
+ auc = metrics.roc_auc_score(y_test, predict)
46
+ f1_score = metrics.precision_recall_fscore_support(y_test,pred)[2].mean()
47
+ return [acc, auc,f1_score]
48
+
49
+
50
+ def get_utility_metrics(real_path,fake_paths,scaler="MinMax",classifiers=["lr","dt","rf","mlp"],test_ratio=.20):
51
+
52
+ data_real = pd.read_csv(real_path).to_numpy()
53
+ data_dim = data_real.shape[1]
54
+
55
+ data_real_y = data_real[:,-1]
56
+ data_real_X = data_real[:,:data_dim-1]
57
+ X_train_real, X_test_real, y_train_real, y_test_real = model_selection.train_test_split(data_real_X ,data_real_y, test_size=test_ratio, stratify=data_real_y,random_state=42)
58
+
59
+ if scaler=="MinMax":
60
+ scaler_real = MinMaxScaler()
61
+ else:
62
+ scaler_real = StandardScaler()
63
+
64
+ scaler_real.fit(data_real_X)
65
+ X_train_real_scaled = scaler_real.transform(X_train_real)
66
+ X_test_real_scaled = scaler_real.transform(X_test_real)
67
+
68
+ all_real_results = []
69
+ for classifier in classifiers:
70
+ real_results = supervised_model_training(X_train_real_scaled,y_train_real,X_test_real_scaled,y_test_real,classifier)
71
+ all_real_results.append(real_results)
72
+
73
+ all_fake_results_avg = []
74
+
75
+ for fake_path in fake_paths:
76
+ data_fake = pd.read_csv(fake_path).to_numpy()
77
+ data_fake_y = data_fake[:,-1]
78
+ data_fake_X = data_fake[:,:data_dim-1]
79
+ X_train_fake, _ , y_train_fake, _ = model_selection.train_test_split(data_fake_X ,data_fake_y, test_size=test_ratio, stratify=data_fake_y,random_state=42)
80
+
81
+ if scaler=="MinMax":
82
+ scaler_fake = MinMaxScaler()
83
+ else:
84
+ scaler_fake = StandardScaler()
85
+
86
+ scaler_fake.fit(data_fake_X)
87
+
88
+ X_train_fake_scaled = scaler_fake.transform(X_train_fake)
89
+
90
+ all_fake_results = []
91
+ for classifier in classifiers:
92
+ fake_results = supervised_model_training(X_train_fake_scaled,y_train_fake,X_test_real_scaled,y_test_real,classifier)
93
+ all_fake_results.append(fake_results)
94
+
95
+ all_fake_results_avg.append(all_fake_results)
96
+
97
+ diff_results = np.array(all_real_results)- np.array(all_fake_results_avg).mean(axis=0)
98
+
99
+ return diff_results
100
+
101
+ def stat_sim(real_path,fake_path,cat_cols=None):
102
+
103
+ Stat_dict={}
104
+
105
+ real = pd.read_csv(real_path)
106
+ fake = pd.read_csv(fake_path)
107
+
108
+ really = real.copy()
109
+ fakey = fake.copy()
110
+
111
+ real_corr = compute_associations(real, nominal_columns=cat_cols)
112
+
113
+ fake_corr = compute_associations(fake, nominal_columns=cat_cols)
114
+
115
+ corr_dist = np.linalg.norm(real_corr - fake_corr)
116
+
117
+ cat_stat = []
118
+ num_stat = []
119
+
120
+ for column in real.columns:
121
+
122
+ if column in cat_cols:
123
+
124
+ real_pdf=(really[column].value_counts()/really[column].value_counts().sum())
125
+ fake_pdf=(fakey[column].value_counts()/fakey[column].value_counts().sum())
126
+ categories = (fakey[column].value_counts()/fakey[column].value_counts().sum()).keys().tolist()
127
+ sorted_categories = sorted(categories)
128
+
129
+ real_pdf_values = []
130
+ fake_pdf_values = []
131
+
132
+ for i in sorted_categories:
133
+ real_pdf_values.append(real_pdf[i])
134
+ fake_pdf_values.append(fake_pdf[i])
135
+
136
+ if len(real_pdf)!=len(fake_pdf):
137
+ zero_cats = set(really[column].value_counts().keys())-set(fakey[column].value_counts().keys())
138
+ for z in zero_cats:
139
+ real_pdf_values.append(real_pdf[z])
140
+ fake_pdf_values.append(0)
141
+ Stat_dict[column]=(distance.jensenshannon(real_pdf_values,fake_pdf_values, 2.0))
142
+ cat_stat.append(Stat_dict[column])
143
+ else:
144
+ scaler = MinMaxScaler()
145
+ scaler.fit(real[column].values.reshape(-1,1))
146
+ l1 = scaler.transform(real[column].values.reshape(-1,1)).flatten()
147
+ l2 = scaler.transform(fake[column].values.reshape(-1,1)).flatten()
148
+ Stat_dict[column]= (wasserstein_distance(l1,l2))
149
+ num_stat.append(Stat_dict[column])
150
+
151
+ return [np.mean(num_stat),np.mean(cat_stat),corr_dist]
152
+
153
+ def privacy_metrics(real_path,fake_path,data_percent=15):
154
+
155
+ real = pd.read_csv(real_path).drop_duplicates(keep=False)
156
+ fake = pd.read_csv(fake_path).drop_duplicates(keep=False)
157
+
158
+ real_refined = real.sample(n=int(len(real)*(.01*data_percent)), random_state=42).to_numpy()
159
+ fake_refined = fake.sample(n=int(len(fake)*(.01*data_percent)), random_state=42).to_numpy()
160
+
161
+ scalerR = StandardScaler()
162
+ scalerR.fit(real_refined)
163
+ scalerF = StandardScaler()
164
+ scalerF.fit(fake_refined)
165
+ df_real_scaled = scalerR.transform(real_refined)
166
+ df_fake_scaled = scalerF.transform(fake_refined)
167
+
168
+ dist_rf = metrics.pairwise_distances(df_real_scaled, Y=df_fake_scaled, metric='minkowski', n_jobs=-1)
169
+ dist_rr = metrics.pairwise_distances(df_real_scaled, Y=None, metric='minkowski', n_jobs=-1)
170
+ rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1)
171
+ dist_ff = metrics.pairwise_distances(df_fake_scaled, Y=None, metric='minkowski', n_jobs=-1)
172
+ rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1)
173
+ smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))]
174
+ smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))]
175
+ smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))]
176
+ smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))]
177
+ smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))]
178
+ smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))]
179
+ nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr])
180
+ nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff])
181
+ nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf])
182
+ nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5)
183
+ nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5)
184
+ nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5)
185
+
186
+ min_dist_rf = np.array([i[0] for i in smallest_two_rf])
187
+ fifth_perc_rf = np.percentile(min_dist_rf,5)
188
+ min_dist_rr = np.array([i[0] for i in smallest_two_rr])
189
+ fifth_perc_rr = np.percentile(min_dist_rr,5)
190
+ min_dist_ff = np.array([i[0] for i in smallest_two_ff])
191
+ fifth_perc_ff = np.percentile(min_dist_ff,5)
192
+
193
+ return np.array([fifth_perc_rf,fifth_perc_rr,fifth_perc_ff,nn_fifth_perc_rf,nn_fifth_perc_rr,nn_fifth_perc_ff]).reshape(1,6)
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/pipeline/data_preparation.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn import preprocessing
4
+ from sklearn import model_selection
5
+
6
+ class DataPrep(object):
7
+
8
+ def __init__(self, raw_df: pd.DataFrame, categorical: list, log:list, mixed:dict, general:list, non_categorical:list, integer:list, type:dict, test_ratio:float):
9
+
10
+
11
+ self.categorical_columns = categorical
12
+ self.log_columns = log
13
+ self.mixed_columns = mixed
14
+ self.general_columns = general
15
+ self.non_categorical_columns = non_categorical
16
+ self.integer_columns = integer
17
+ self.column_types = dict()
18
+ self.column_types["categorical"] = []
19
+ self.column_types["mixed"] = {}
20
+ self.column_types["general"] = []
21
+ self.column_types["non_categorical"] = []
22
+ self.lower_bounds = {}
23
+ self.label_encoder_list = []
24
+
25
+ target_col = list(type.values())[0]
26
+ if target_col is not None:
27
+ y_real = raw_df[target_col]
28
+ X_real = raw_df.drop(columns=[target_col])
29
+ # X_train_real, _, y_train_real, _ = model_selection.train_test_split(X_real ,y_real, test_size=test_ratio, stratify=y_real,random_state=42)
30
+ X_train_real, y_train_real = X_real, y_real
31
+
32
+ X_train_real[target_col]= y_train_real
33
+
34
+ self.df = X_train_real
35
+ else:
36
+ self.df = raw_df
37
+
38
+ self.df = self.df.replace(r' ', np.nan)
39
+ self.df = self.df.fillna('empty')
40
+
41
+ all_columns= set(self.df.columns)
42
+ irrelevant_missing_columns = set(self.categorical_columns)
43
+ relevant_missing_columns = list(all_columns - irrelevant_missing_columns)
44
+
45
+ for i in relevant_missing_columns:
46
+ if i in self.log_columns:
47
+ if "empty" in list(self.df[i].values):
48
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x)
49
+ self.mixed_columns[i] = [-9999999]
50
+ elif i in list(self.mixed_columns.keys()):
51
+ if "empty" in list(self.df[i].values):
52
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x )
53
+ self.mixed_columns[i].append(-9999999)
54
+ else:
55
+ if "empty" in list(self.df[i].values):
56
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x)
57
+ self.mixed_columns[i] = [-9999999]
58
+
59
+ if self.log_columns:
60
+ for log_column in self.log_columns:
61
+ valid_indices = []
62
+ for idx,val in enumerate(self.df[log_column].values):
63
+ if val!=-9999999:
64
+ valid_indices.append(idx)
65
+ eps = 1
66
+ lower = np.min(self.df[log_column].iloc[valid_indices].values)
67
+ self.lower_bounds[log_column] = lower
68
+ if lower>0:
69
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x) if x!=-9999999 else -9999999)
70
+ elif lower == 0:
71
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x+eps) if x!=-9999999 else -9999999)
72
+ else:
73
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x-lower+eps) if x!=-9999999 else -9999999)
74
+
75
+ for column_index, column in enumerate(self.df.columns):
76
+ if column in self.categorical_columns:
77
+ label_encoder = preprocessing.LabelEncoder()
78
+ self.df[column] = self.df[column].astype(str)
79
+ label_encoder.fit(self.df[column])
80
+ current_label_encoder = dict()
81
+ current_label_encoder['column'] = column
82
+ current_label_encoder['label_encoder'] = label_encoder
83
+ transformed_column = label_encoder.transform(self.df[column])
84
+ self.df[column] = transformed_column
85
+ self.label_encoder_list.append(current_label_encoder)
86
+ self.column_types["categorical"].append(column_index)
87
+
88
+ if column in self.general_columns:
89
+ self.column_types["general"].append(column_index)
90
+
91
+ if column in self.non_categorical_columns:
92
+ self.column_types["non_categorical"].append(column_index)
93
+
94
+ elif column in self.mixed_columns:
95
+ self.column_types["mixed"][column_index] = self.mixed_columns[column]
96
+
97
+ elif column in self.general_columns:
98
+ self.column_types["general"].append(column_index)
99
+
100
+
101
+ super().__init__()
102
+
103
+ def inverse_prep(self, data, eps=1):
104
+
105
+ df_sample = pd.DataFrame(data,columns=self.df.columns)
106
+
107
+ for i in range(len(self.label_encoder_list)):
108
+ le = self.label_encoder_list[i]["label_encoder"]
109
+ df_sample[self.label_encoder_list[i]["column"]] = df_sample[self.label_encoder_list[i]["column"]].astype(int)
110
+ df_sample[self.label_encoder_list[i]["column"]] = le.inverse_transform(df_sample[self.label_encoder_list[i]["column"]])
111
+
112
+ if self.log_columns:
113
+ for i in df_sample:
114
+ if i in self.log_columns:
115
+ lower_bound = self.lower_bounds[i]
116
+ if lower_bound>0:
117
+ df_sample[i].apply(lambda x: np.exp(x))
118
+ elif lower_bound==0:
119
+ df_sample[i] = df_sample[i].apply(lambda x: np.ceil(np.exp(x)-eps) if (np.exp(x)-eps) < 0 else (np.exp(x)-eps))
120
+ else:
121
+ df_sample[i] = df_sample[i].apply(lambda x: np.exp(x)-eps+lower_bound)
122
+
123
+ if self.integer_columns:
124
+ for column in self.integer_columns:
125
+ df_sample[column]= (np.round(df_sample[column].values))
126
+ df_sample[column] = df_sample[column].astype(int)
127
+
128
+ df_sample.replace(-9999999, np.nan,inplace=True)
129
+ df_sample.replace('empty', np.nan,inplace=True)
130
+
131
+ return df_sample
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/privacy_utils/rdp_accountant.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+ from __future__ import division
3
+ from __future__ import print_function
4
+
5
+ import math
6
+ import sys
7
+
8
+ import numpy as np
9
+ from scipy import special
10
+ import six
11
+
12
+ ########################
13
+ # LOG-SPACE ARITHMETIC #
14
+ ########################
15
+
16
+
17
+ def _log_add(logx, logy):
18
+ """Add two numbers in the log space."""
19
+ a, b = min(logx, logy), max(logx, logy)
20
+ if a == -np.inf: # adding 0
21
+ return b
22
+ # Use exp(a) + exp(b) = (exp(a - b) + 1) * exp(b)
23
+ return math.log1p(math.exp(a - b)) + b # log1p(x) = log(x + 1)
24
+
25
+
26
+ def _log_sub(logx, logy):
27
+ """Subtract two numbers in the log space. Answer must be non-negative."""
28
+ if logx < logy:
29
+ raise ValueError("The result of subtraction must be non-negative.")
30
+ if logy == -np.inf: # subtracting 0
31
+ return logx
32
+ if logx == logy:
33
+ return -np.inf # 0 is represented as -np.inf in the log space.
34
+
35
+ try:
36
+ # Use exp(x) - exp(y) = (exp(x - y) - 1) * exp(y).
37
+ return math.log(math.expm1(logx - logy)) + logy # expm1(x) = exp(x) - 1
38
+ except OverflowError:
39
+ return logx
40
+
41
+
42
+ def _log_print(logx):
43
+ """Pretty print."""
44
+ if logx < math.log(sys.float_info.max):
45
+ return "{}".format(math.exp(logx))
46
+ else:
47
+ return "exp({})".format(logx)
48
+
49
+
50
+ def _compute_log_a_int(q, sigma, alpha):
51
+ """Compute log(A_alpha) for integer alpha. 0 < q < 1."""
52
+ assert isinstance(alpha, six.integer_types)
53
+
54
+ # Initialize with 0 in the log space.
55
+ log_a = -np.inf
56
+
57
+ for i in range(alpha + 1):
58
+ log_coef_i = (
59
+ math.log(special.binom(alpha, i)) + i * math.log(q) +
60
+ (alpha - i) * math.log(1 - q))
61
+
62
+ s = log_coef_i + (i * i - i) / (2 * (sigma**2))
63
+ log_a = _log_add(log_a, s)
64
+
65
+ return float(log_a)
66
+
67
+
68
+ def _compute_log_a_frac(q, sigma, alpha):
69
+ """Compute log(A_alpha) for fractional alpha. 0 < q < 1."""
70
+ # The two parts of A_alpha, integrals over (-inf,z0] and [z0, +inf), are
71
+ # initialized to 0 in the log space:
72
+ log_a0, log_a1 = -np.inf, -np.inf
73
+ i = 0
74
+
75
+ z0 = sigma**2 * math.log(1 / q - 1) + .5
76
+
77
+ while True: # do ... until loop
78
+ coef = special.binom(alpha, i)
79
+ log_coef = math.log(abs(coef))
80
+ j = alpha - i
81
+
82
+ log_t0 = log_coef + i * math.log(q) + j * math.log(1 - q)
83
+ log_t1 = log_coef + j * math.log(q) + i * math.log(1 - q)
84
+
85
+ log_e0 = math.log(.5) + _log_erfc((i - z0) / (math.sqrt(2) * sigma))
86
+ log_e1 = math.log(.5) + _log_erfc((z0 - j) / (math.sqrt(2) * sigma))
87
+
88
+ log_s0 = log_t0 + (i * i - i) / (2 * (sigma**2)) + log_e0
89
+ log_s1 = log_t1 + (j * j - j) / (2 * (sigma**2)) + log_e1
90
+
91
+ if coef > 0:
92
+ log_a0 = _log_add(log_a0, log_s0)
93
+ log_a1 = _log_add(log_a1, log_s1)
94
+ else:
95
+ log_a0 = _log_sub(log_a0, log_s0)
96
+ log_a1 = _log_sub(log_a1, log_s1)
97
+
98
+ i += 1
99
+ if max(log_s0, log_s1) < -30:
100
+ break
101
+
102
+ return _log_add(log_a0, log_a1)
103
+
104
+
105
+ def _compute_log_a(q, sigma, alpha):
106
+ """Compute log(A_alpha) for any positive finite alpha."""
107
+ if float(alpha).is_integer():
108
+ return _compute_log_a_int(q, sigma, int(alpha))
109
+ else:
110
+ return _compute_log_a_frac(q, sigma, alpha)
111
+
112
+
113
+ def _log_erfc(x):
114
+ """Compute log(erfc(x)) with high accuracy for large x."""
115
+ try:
116
+ return math.log(2) + special.log_ndtr(-x * 2**.5)
117
+ except NameError:
118
+ # If log_ndtr is not available, approximate as follows:
119
+ r = special.erfc(x)
120
+ if r == 0.0:
121
+ # Using the Laurent series at infinity for the tail of the erfc function:
122
+ # erfc(x) ~ exp(-x^2-.5/x^2+.625/x^4)/(x*pi^.5)
123
+ # To verify in Mathematica:
124
+ # Series[Log[Erfc[x]] + Log[x] + Log[Pi]/2 + x^2, {x, Infinity, 6}]
125
+ return (-math.log(math.pi) / 2 - math.log(x) - x**2 - .5 * x**-2 +
126
+ .625 * x**-4 - 37. / 24. * x**-6 + 353. / 64. * x**-8)
127
+ else:
128
+ return math.log(r)
129
+
130
+
131
+ def _compute_delta(orders, rdp, eps):
132
+ """Compute delta given a list of RDP values and target epsilon.
133
+
134
+ Args:
135
+ orders: An array (or a scalar) of orders.
136
+ rdp: A list (or a scalar) of RDP guarantees.
137
+ eps: The target epsilon.
138
+
139
+ Returns:
140
+ Pair of (delta, optimal_order).
141
+
142
+ Raises:
143
+ ValueError: If input is malformed.
144
+
145
+ """
146
+ orders_vec = np.atleast_1d(orders)
147
+ rdp_vec = np.atleast_1d(rdp)
148
+
149
+ if len(orders_vec) != len(rdp_vec):
150
+ raise ValueError("Input lists must have the same length.")
151
+
152
+ deltas = np.exp((rdp_vec - eps) * (orders_vec - 1))
153
+ idx_opt = np.argmin(deltas)
154
+ return min(deltas[idx_opt], 1.), orders_vec[idx_opt]
155
+
156
+
157
+ def _compute_eps(orders, rdp, delta):
158
+ """Compute epsilon given a list of RDP values and target delta.
159
+
160
+ Args:
161
+ orders: An array (or a scalar) of orders.
162
+ rdp: A list (or a scalar) of RDP guarantees.
163
+ delta: The target delta.
164
+
165
+ Returns:
166
+ Pair of (eps, optimal_order).
167
+
168
+ Raises:
169
+ ValueError: If input is malformed.
170
+
171
+ """
172
+ orders_vec = np.atleast_1d(orders)
173
+ rdp_vec = np.atleast_1d(rdp)
174
+
175
+ if len(orders_vec) != len(rdp_vec):
176
+ raise ValueError("Input lists must have the same length.")
177
+
178
+ eps = rdp_vec - math.log(delta) / (orders_vec - 1)
179
+
180
+ idx_opt = np.nanargmin(eps) # Ignore NaNs
181
+ return eps[idx_opt], orders_vec[idx_opt]
182
+
183
+
184
+ def _compute_rdp(q, sigma, alpha):
185
+ """Compute RDP of the Sampled Gaussian mechanism at order alpha.
186
+
187
+ Args:
188
+ q: The sampling rate.
189
+ sigma: The std of the additive Gaussian noise.
190
+ alpha: The order at which RDP is computed.
191
+
192
+ Returns:
193
+ RDP at alpha, can be np.inf.
194
+ """
195
+ if q == 0:
196
+ return 0
197
+
198
+ if q == 1.:
199
+ return alpha / (2 * sigma**2)
200
+
201
+ if np.isinf(alpha):
202
+ return np.inf
203
+
204
+ return _compute_log_a(q, sigma, alpha) / (alpha - 1)
205
+
206
+
207
+ def compute_rdp(q, noise_multiplier, steps, orders):
208
+ """Compute RDP of the Sampled Gaussian Mechanism.
209
+
210
+ Args:
211
+ q: The sampling rate.
212
+ noise_multiplier: The ratio of the standard deviation of the Gaussian noise
213
+ to the l2-sensitivity of the function to which it is added.
214
+ steps: The number of steps.
215
+ orders: An array (or a scalar) of RDP orders.
216
+
217
+ Returns:
218
+ The RDPs at all orders, can be np.inf.
219
+ """
220
+ if np.isscalar(orders):
221
+ rdp = _compute_rdp(q, noise_multiplier, orders)
222
+ else:
223
+ rdp = np.array([_compute_rdp(q, noise_multiplier, order)
224
+ for order in orders])
225
+
226
+ return rdp * steps
227
+
228
+
229
+ def get_privacy_spent(orders, rdp, target_eps=None, target_delta=None):
230
+ """Compute delta (or eps) for given eps (or delta) from RDP values.
231
+
232
+ Args:
233
+ orders: An array (or a scalar) of RDP orders.
234
+ rdp: An array of RDP values. Must be of the same length as the orders list.
235
+ target_eps: If not None, the epsilon for which we compute the corresponding
236
+ delta.
237
+ target_delta: If not None, the delta for which we compute the corresponding
238
+ epsilon. Exactly one of target_eps and target_delta must be None.
239
+
240
+ Returns:
241
+ eps, delta, opt_order.
242
+
243
+ Raises:
244
+ ValueError: If target_eps and target_delta are messed up.
245
+ """
246
+ if target_eps is None and target_delta is None:
247
+ raise ValueError(
248
+ "Exactly one out of eps and delta must be None. (Both are).")
249
+
250
+ if target_eps is not None and target_delta is not None:
251
+ raise ValueError(
252
+ "Exactly one out of eps and delta must be None. (None is).")
253
+
254
+ if target_eps is not None:
255
+ delta, opt_order = _compute_delta(orders, rdp, target_eps)
256
+ return target_eps, delta, opt_order
257
+ else:
258
+ eps, opt_order = _compute_eps(orders, rdp, target_delta)
259
+ return eps, target_delta, opt_order
260
+
261
+
262
+ def compute_rdp_from_ledger(ledger, orders):
263
+ """Compute RDP of Sampled Gaussian Mechanism from ledger.
264
+
265
+ Args:
266
+ ledger: A formatted privacy ledger.
267
+ orders: An array (or a scalar) of RDP orders.
268
+
269
+ Returns:
270
+ RDP at all orders, can be np.inf.
271
+ """
272
+ total_rdp = np.zeros_like(orders, dtype=float)
273
+ for sample in ledger:
274
+ # Compute equivalent z from l2_clip_bounds and noise stddevs in sample.
275
+ # See https://arxiv.org/pdf/1812.06210.pdf for derivation of this formula.
276
+ effective_z = sum([
277
+ (q.noise_stddev / q.l2_norm_bound)**-2 for q in sample.queries])**-0.5
278
+ total_rdp += compute_rdp(
279
+ sample.selection_probability, effective_z, 1, orders)
280
+ return total_rdp
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/ctabgan_synthesizer.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import torch
4
+ import torch.utils.data
5
+ import torch.optim as optim
6
+ from torch.optim import Adam
7
+ from torch.nn import functional as F
8
+ from torch.nn import (Dropout, LeakyReLU, Linear, Module, ReLU, Sequential,
9
+ Conv2d, ConvTranspose2d, Sigmoid, init, BCELoss, CrossEntropyLoss,SmoothL1Loss,LayerNorm)
10
+ from model.synthesizer.transformer import ImageTransformer,DataTransformer
11
+ from model.privacy_utils.rdp_accountant import compute_rdp, get_privacy_spent
12
+ from tqdm import tqdm, trange
13
+ import time
14
+
15
+
16
+ class Classifier(Module):
17
+ def __init__(self,input_dim, dis_dims,st_ed):
18
+ super(Classifier,self).__init__()
19
+ dim = input_dim-(st_ed[1]-st_ed[0])
20
+ seq = []
21
+ self.str_end = st_ed
22
+ for item in list(dis_dims):
23
+ seq += [
24
+ Linear(dim, item),
25
+ LeakyReLU(0.2),
26
+ Dropout(0.5)
27
+ ]
28
+ dim = item
29
+
30
+ if (st_ed[1]-st_ed[0])==1:
31
+ seq += [Linear(dim, 1)]
32
+
33
+ elif (st_ed[1]-st_ed[0])==2:
34
+ seq += [Linear(dim, 1),Sigmoid()]
35
+ else:
36
+ seq += [Linear(dim,(st_ed[1]-st_ed[0]))]
37
+
38
+ self.seq = Sequential(*seq)
39
+
40
+ def forward(self, input):
41
+
42
+ label=None
43
+
44
+ if (self.str_end[1]-self.str_end[0])==1:
45
+ label = input[:, self.str_end[0]:self.str_end[1]]
46
+ else:
47
+ label = torch.argmax(input[:, self.str_end[0]:self.str_end[1]], axis=-1)
48
+
49
+ new_imp = torch.cat((input[:,:self.str_end[0]],input[:,self.str_end[1]:]),1)
50
+
51
+ if ((self.str_end[1]-self.str_end[0])==2) | ((self.str_end[1]-self.str_end[0])==1):
52
+ return self.seq(new_imp).view(-1), label
53
+ else:
54
+ return self.seq(new_imp), label
55
+
56
+ def apply_activate(data, output_info):
57
+ data_t = []
58
+ st = 0
59
+ for item in output_info:
60
+ if item[1] == 'tanh':
61
+ ed = st + item[0]
62
+ data_t.append(torch.tanh(data[:, st:ed]))
63
+ st = ed
64
+ elif item[1] == 'softmax':
65
+ ed = st + item[0]
66
+ data_t.append(F.gumbel_softmax(data[:, st:ed], tau=0.2))
67
+ st = ed
68
+ return torch.cat(data_t, dim=1)
69
+
70
+ def get_st_ed(target_col_index,output_info):
71
+ st = 0
72
+ c= 0
73
+ tc= 0
74
+
75
+ for item in output_info:
76
+ if c==target_col_index:
77
+ break
78
+ if item[1]=='tanh':
79
+ st += item[0]
80
+ if item[2] == 'yes_g':
81
+ c+=1
82
+ elif item[1] == 'softmax':
83
+ st += item[0]
84
+ c+=1
85
+ tc+=1
86
+
87
+ ed= st+output_info[tc][0]
88
+
89
+ return (st,ed)
90
+
91
+ def random_choice_prob_index_sampling(probs,col_idx):
92
+ option_list = []
93
+ for i in col_idx:
94
+ pp = probs[i]
95
+ option_list.append(np.random.choice(np.arange(len(probs[i])), p=pp))
96
+
97
+ return np.array(option_list).reshape(col_idx.shape)
98
+
99
+ def random_choice_prob_index(a, axis=1):
100
+ r = np.expand_dims(np.random.rand(a.shape[1 - axis]), axis=axis)
101
+ return (a.cumsum(axis=axis) > r).argmax(axis=axis)
102
+
103
+ def maximum_interval(output_info):
104
+ max_interval = 0
105
+ for item in output_info:
106
+ max_interval = max(max_interval, item[0])
107
+ return max_interval
108
+
109
+ class Cond(object):
110
+ def __init__(self, data, output_info):
111
+
112
+ self.model = []
113
+ st = 0
114
+ counter = 0
115
+ for item in output_info:
116
+
117
+ if item[1] == 'tanh':
118
+ st += item[0]
119
+ continue
120
+ elif item[1] == 'softmax':
121
+ ed = st + item[0]
122
+ counter += 1
123
+ self.model.append(np.argmax(data[:, st:ed], axis=-1))
124
+ st = ed
125
+
126
+ self.interval = []
127
+ self.n_col = 0
128
+ self.n_opt = 0
129
+ st = 0
130
+ self.p = np.zeros((counter, maximum_interval(output_info)))
131
+ self.p_sampling = []
132
+ for item in output_info:
133
+ if item[1] == 'tanh':
134
+ st += item[0]
135
+ continue
136
+ elif item[1] == 'softmax':
137
+ ed = st + item[0]
138
+ tmp = np.sum(data[:, st:ed], axis=0)
139
+ tmp_sampling = np.sum(data[:, st:ed], axis=0)
140
+ tmp = np.log(tmp + 1)
141
+ tmp = tmp / np.sum(tmp)
142
+ tmp_sampling = tmp_sampling / np.sum(tmp_sampling)
143
+ self.p_sampling.append(tmp_sampling)
144
+ self.p[self.n_col, :item[0]] = tmp
145
+ self.interval.append((self.n_opt, item[0]))
146
+ self.n_opt += item[0]
147
+ self.n_col += 1
148
+ st = ed
149
+
150
+ self.interval = np.asarray(self.interval)
151
+
152
+ def sample_train(self, batch):
153
+ if self.n_col == 0:
154
+ return None
155
+ batch = batch
156
+
157
+ idx = np.random.choice(np.arange(self.n_col), batch)
158
+
159
+ vec = np.zeros((batch, self.n_opt), dtype='float32')
160
+ mask = np.zeros((batch, self.n_col), dtype='float32')
161
+ mask[np.arange(batch), idx] = 1
162
+ opt1prime = random_choice_prob_index(self.p[idx])
163
+ for i in np.arange(batch):
164
+ vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1
165
+
166
+ return vec, mask, idx, opt1prime
167
+
168
+ def sample(self, batch):
169
+ if self.n_col == 0:
170
+ return None
171
+ batch = batch
172
+
173
+ idx = np.random.choice(np.arange(self.n_col), batch)
174
+
175
+ vec = np.zeros((batch, self.n_opt), dtype='float32')
176
+ opt1prime = random_choice_prob_index_sampling(self.p_sampling,idx)
177
+
178
+ for i in np.arange(batch):
179
+ vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1
180
+
181
+ return vec
182
+
183
+ def cond_loss(data, output_info, c, m):
184
+ loss = []
185
+ st = 0
186
+ st_c = 0
187
+ for item in output_info:
188
+ if item[1] == 'tanh':
189
+ st += item[0]
190
+ continue
191
+
192
+ elif item[1] == 'softmax':
193
+ ed = st + item[0]
194
+ ed_c = st_c + item[0]
195
+ tmp = F.cross_entropy(
196
+ data[:, st:ed],
197
+ torch.argmax(c[:, st_c:ed_c], dim=1),
198
+ reduction='none')
199
+ loss.append(tmp)
200
+ st = ed
201
+ st_c = ed_c
202
+
203
+ loss = torch.stack(loss, dim=1)
204
+ return (loss * m).sum() / data.size()[0]
205
+
206
+ class Sampler(object):
207
+ def __init__(self, data, output_info):
208
+ super(Sampler, self).__init__()
209
+ self.data = data
210
+ self.model = []
211
+ self.n = len(data)
212
+ st = 0
213
+ for item in output_info:
214
+ if item[1] == 'tanh':
215
+ st += item[0]
216
+ continue
217
+ elif item[1] == 'softmax':
218
+ ed = st + item[0]
219
+ tmp = []
220
+ for j in range(item[0]):
221
+ tmp.append(np.nonzero(data[:, st + j])[0])
222
+ self.model.append(tmp)
223
+ st = ed
224
+
225
+ def sample(self, n, col, opt):
226
+ if col is None:
227
+ idx = np.random.choice(np.arange(self.n), n)
228
+ return self.data[idx]
229
+ idx = []
230
+ for c, o in zip(col, opt):
231
+ idx.append(np.random.choice(self.model[c][o]))
232
+ return self.data[idx]
233
+
234
+ class Discriminator(Module):
235
+ def __init__(self, side, layers):
236
+ super(Discriminator, self).__init__()
237
+ self.side = side
238
+ info = len(layers)-2
239
+ self.seq = Sequential(*layers)
240
+ self.seq_info = Sequential(*layers[:info])
241
+
242
+ def forward(self, input):
243
+ return (self.seq(input)), self.seq_info(input)
244
+
245
+ class Generator(Module):
246
+ def __init__(self, side, layers):
247
+ super(Generator, self).__init__()
248
+ self.side = side
249
+ self.seq = Sequential(*layers)
250
+
251
+ def forward(self, input_):
252
+ return self.seq(input_)
253
+
254
+ def determine_layers_disc(side, num_channels):
255
+ assert side >= 4 and side <= 64
256
+
257
+ layer_dims = [(1, side), (num_channels, side // 2)]
258
+
259
+ while layer_dims[-1][1] > 3 and len(layer_dims) < 4:
260
+ layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2))
261
+
262
+ layerNorms = []
263
+ num_c = num_channels
264
+ num_s = side / 2
265
+ for l in range(len(layer_dims) - 1):
266
+ layerNorms.append([int(num_c), int(num_s), int(num_s)])
267
+ num_c = num_c * 2
268
+ num_s = num_s / 2
269
+
270
+ layers_D = []
271
+
272
+ for prev, curr, ln in zip(layer_dims, layer_dims[1:], layerNorms):
273
+ layers_D += [
274
+ Conv2d(prev[0], curr[0], 4, 2, 1, bias=False),
275
+ LayerNorm(ln),
276
+ LeakyReLU(0.2, inplace=True),
277
+ ]
278
+
279
+ layers_D += [Conv2d(layer_dims[-1][0], 1, layer_dims[-1][1], 1, 0), ReLU(True)]
280
+
281
+ return layers_D
282
+
283
+ def determine_layers_gen(side, random_dim, num_channels):
284
+ assert side >= 4 and side <= 64
285
+
286
+ layer_dims = [(1, side), (num_channels, side // 2)]
287
+
288
+ while layer_dims[-1][1] > 3 and len(layer_dims) < 4:
289
+ layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2))
290
+
291
+ layerNorms = []
292
+
293
+ num_c = num_channels * (2 ** (len(layer_dims) - 2))
294
+ num_s = int(side / (2 ** (len(layer_dims) - 1)))
295
+ for l in range(len(layer_dims) - 1):
296
+ layerNorms.append([int(num_c), int(num_s), int(num_s)])
297
+ num_c = num_c / 2
298
+ num_s = num_s * 2
299
+
300
+ layers_G = [ConvTranspose2d(random_dim, layer_dims[-1][0], layer_dims[-1][1], 1, 0, output_padding=0, bias=False)]
301
+
302
+ for prev, curr, ln in zip(reversed(layer_dims), reversed(layer_dims[:-1]), layerNorms):
303
+ layers_G += [LayerNorm(ln), ReLU(True), ConvTranspose2d(prev[0], curr[0], 4, 2, 1, output_padding=0, bias=True)]
304
+ return layers_G
305
+
306
+ def slerp(val, low, high):
307
+ low_norm = low/torch.norm(low, dim=1, keepdim=True)
308
+ high_norm = high/torch.norm(high, dim=1, keepdim=True)
309
+ omega = torch.acos((low_norm*high_norm).sum(1)).view(val.size(0), 1)
310
+ so = torch.sin(omega)
311
+ res = (torch.sin((1.0-val)*omega)/so)*low + (torch.sin(val*omega)/so) * high
312
+
313
+ return res
314
+
315
+ def calc_gradient_penalty_slerp(netD, real_data, fake_data, transformer, device='cpu', lambda_=10):
316
+ batchsize = real_data.shape[0]
317
+ alpha = torch.rand(batchsize, 1, device=device)
318
+ interpolates = slerp(alpha, real_data, fake_data)
319
+ interpolates = interpolates.to(device)
320
+ interpolates = transformer.transform(interpolates)
321
+ interpolates = torch.autograd.Variable(interpolates, requires_grad=True)
322
+ disc_interpolates,_ = netD(interpolates)
323
+
324
+ gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates,
325
+ grad_outputs=torch.ones(disc_interpolates.size()).to(device),
326
+ create_graph=True, retain_graph=True, only_inputs=True)[0]
327
+
328
+ gradients_norm = gradients.norm(2, dim=1)
329
+ gradient_penalty = ((gradients_norm - 1) ** 2).mean() * lambda_
330
+
331
+ return gradient_penalty
332
+
333
+ def weights_init(m):
334
+ classname = m.__class__.__name__
335
+
336
+ if classname.find('Conv') != -1:
337
+ init.normal_(m.weight.data, 0.0, 0.02)
338
+
339
+ elif classname.find('BatchNorm') != -1:
340
+ init.normal_(m.weight.data, 1.0, 0.02)
341
+ init.constant_(m.bias.data, 0)
342
+
343
+ class CTABGANSynthesizer:
344
+ def __init__(self,
345
+ class_dim=(256, 256, 256, 256),
346
+ random_dim=100,
347
+ num_channels=64,
348
+ l2scale=1e-5,
349
+ batch_size=500,
350
+ epochs=150,
351
+ lr=2e-4,
352
+ device="cpu"):
353
+
354
+
355
+ self.random_dim = random_dim
356
+ self.class_dim = class_dim
357
+ self.num_channels = num_channels
358
+ self.dside = None
359
+ self.gside = None
360
+ self.l2scale = l2scale
361
+ self.lr = lr
362
+ self.batch_size = batch_size
363
+ self.epochs = epochs
364
+ self.device = torch.device(device)
365
+
366
+ def fit(self, train_data=pd.DataFrame, categorical=[], mixed={}, general=[], non_categorical=[], type={}):
367
+
368
+ problem_type = None
369
+ target_index=None
370
+ if type:
371
+ problem_type = list(type.keys())[0]
372
+ if problem_type:
373
+ target_index = train_data.columns.get_loc(type[problem_type])
374
+
375
+ self.transformer = DataTransformer(train_data=train_data, categorical_list=categorical, mixed_dict=mixed, general_list=general, non_categorical_list=non_categorical)
376
+ self.transformer.fit()
377
+ train_data = self.transformer.transform(train_data.values)
378
+ data_sampler = Sampler(train_data, self.transformer.output_info)
379
+ data_dim = self.transformer.output_dim
380
+ self.cond_generator = Cond(train_data, self.transformer.output_info)
381
+
382
+ sides = [4, 8, 16, 24, 32]
383
+ col_size_d = data_dim + self.cond_generator.n_opt
384
+ for i in sides:
385
+ if i * i >= col_size_d:
386
+ self.dside = i
387
+ break
388
+
389
+ sides = [4, 8, 16, 24, 32]
390
+ col_size_g = data_dim
391
+ for i in sides:
392
+ if i * i >= col_size_g:
393
+ self.gside = i
394
+ break
395
+
396
+
397
+ layers_G = determine_layers_gen(self.gside, self.random_dim+self.cond_generator.n_opt, self.num_channels)
398
+ layers_D = determine_layers_disc(self.dside, self.num_channels)
399
+
400
+ self.generator = Generator(self.gside, layers_G).to(self.device)
401
+ discriminator = Discriminator(self.dside, layers_D).to(self.device)
402
+ optimizer_params = dict(lr=self.lr, betas=(0.5, 0.9), eps=1e-3, weight_decay=self.l2scale)
403
+ optimizerG = Adam(self.generator.parameters(), **optimizer_params)
404
+ optimizerD = Adam(discriminator.parameters(), **optimizer_params)
405
+
406
+ st_ed = None
407
+ classifier=None
408
+ optimizerC= None
409
+ if target_index != None:
410
+ st_ed= get_st_ed(target_index,self.transformer.output_info)
411
+ classifier = Classifier(data_dim,self.class_dim,st_ed).to(self.device)
412
+ optimizerC = optim.Adam(classifier.parameters(),**optimizer_params)
413
+
414
+
415
+ self.generator.apply(weights_init)
416
+ discriminator.apply(weights_init)
417
+
418
+ self.Gtransformer = ImageTransformer(self.gside)
419
+ self.Dtransformer = ImageTransformer(self.dside)
420
+
421
+ epsilon = 0
422
+ epoch = 0
423
+ steps = 0
424
+ ci = 1
425
+
426
+ for i in tqdm(range(self.epochs)):
427
+
428
+
429
+ for _ in range(ci):
430
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
431
+ condvec = self.cond_generator.sample_train(self.batch_size)
432
+
433
+ c, m, col, opt = condvec
434
+ c = torch.from_numpy(c).to(self.device)
435
+ m = torch.from_numpy(m).to(self.device)
436
+ noisez = torch.cat([noisez, c], dim=1)
437
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
438
+
439
+ perm = np.arange(self.batch_size)
440
+ np.random.shuffle(perm)
441
+ real = data_sampler.sample(self.batch_size, col[perm], opt[perm])
442
+ c_perm = c[perm]
443
+
444
+ real = torch.from_numpy(real.astype('float32')).to(self.device)
445
+
446
+ fake = self.generator(noisez)
447
+ faket = self.Gtransformer.inverse_transform(fake)
448
+ fakeact = apply_activate(faket, self.transformer.output_info)
449
+
450
+ fake_cat = torch.cat([fakeact, c], dim=1)
451
+ real_cat = torch.cat([real, c_perm], dim=1)
452
+
453
+ real_cat_d = self.Dtransformer.transform(real_cat)
454
+ fake_cat_d = self.Dtransformer.transform(fake_cat)
455
+
456
+ optimizerD.zero_grad()
457
+
458
+ d_real,_ = discriminator(real_cat_d)
459
+
460
+
461
+ d_real = -torch.mean(d_real)
462
+ d_real.backward()
463
+
464
+
465
+ d_fake,_ = discriminator(fake_cat_d)
466
+
467
+ d_fake = torch.mean(d_fake)
468
+
469
+ d_fake.backward()
470
+
471
+ pen = calc_gradient_penalty_slerp(discriminator, real_cat, fake_cat, self.Dtransformer , self.device)
472
+
473
+ pen.backward()
474
+
475
+ optimizerD.step()
476
+
477
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
478
+
479
+ condvec = self.cond_generator.sample_train(self.batch_size)
480
+
481
+ c, m, col, opt = condvec
482
+ c = torch.from_numpy(c).to(self.device)
483
+ m = torch.from_numpy(m).to(self.device)
484
+ noisez = torch.cat([noisez, c], dim=1)
485
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
486
+
487
+ optimizerG.zero_grad()
488
+
489
+ fake = self.generator(noisez)
490
+ faket = self.Gtransformer.inverse_transform(fake)
491
+ fakeact = apply_activate(faket, self.transformer.output_info)
492
+
493
+ fake_cat = torch.cat([fakeact, c], dim=1)
494
+ fake_cat = self.Dtransformer.transform(fake_cat)
495
+
496
+ y_fake,info_fake = discriminator(fake_cat)
497
+
498
+ cross_entropy = cond_loss(faket, self.transformer.output_info, c, m)
499
+
500
+ _,info_real = discriminator(real_cat_d)
501
+
502
+
503
+ g = -torch.mean(y_fake) + cross_entropy
504
+ g.backward(retain_graph=True)
505
+ loss_mean = torch.norm(torch.mean(info_fake.view(self.batch_size,-1), dim=0) - torch.mean(info_real.view(self.batch_size,-1), dim=0), 1)
506
+ loss_std = torch.norm(torch.std(info_fake.view(self.batch_size,-1), dim=0) - torch.std(info_real.view(self.batch_size,-1), dim=0), 1)
507
+ loss_info = loss_mean + loss_std
508
+ loss_info.backward()
509
+ optimizerG.step()
510
+
511
+
512
+ if problem_type:
513
+
514
+ fake = self.generator(noisez)
515
+
516
+ faket = self.Gtransformer.inverse_transform(fake)
517
+
518
+ fakeact = apply_activate(faket, self.transformer.output_info)
519
+
520
+ real_pre, real_label = classifier(real)
521
+ fake_pre, fake_label = classifier(fakeact)
522
+
523
+ c_loss = CrossEntropyLoss()
524
+
525
+ if (st_ed[1] - st_ed[0])==1:
526
+ c_loss= SmoothL1Loss()
527
+ real_label = real_label.type_as(real_pre)
528
+ fake_label = fake_label.type_as(fake_pre)
529
+ real_label = torch.reshape(real_label,real_pre.size())
530
+ fake_label = torch.reshape(fake_label,fake_pre.size())
531
+
532
+
533
+ elif (st_ed[1] - st_ed[0])==2:
534
+ c_loss = BCELoss()
535
+ real_label = real_label.type_as(real_pre)
536
+ fake_label = fake_label.type_as(fake_pre)
537
+
538
+ loss_cc = c_loss(real_pre, real_label)
539
+ loss_cg = c_loss(fake_pre, fake_label)
540
+
541
+ optimizerG.zero_grad()
542
+ loss_cg.backward()
543
+ optimizerG.step()
544
+
545
+ optimizerC.zero_grad()
546
+ loss_cc.backward()
547
+ optimizerC.step()
548
+
549
+
550
+
551
+
552
+ @torch.no_grad()
553
+ def sample(self, n, seed=0):
554
+ print(n)
555
+ torch.manual_seed(seed)
556
+ torch.cuda.manual_seed(seed)
557
+ sample_batch_size = 8092
558
+ self.generator.eval()
559
+
560
+ output_info = self.transformer.output_info
561
+ steps = n // sample_batch_size + 1
562
+
563
+ data = []
564
+
565
+ for i in range(steps):
566
+ noisez = torch.randn(sample_batch_size, self.random_dim, device=self.device)
567
+ condvec = self.cond_generator.sample(sample_batch_size)
568
+ c = condvec
569
+ c = torch.from_numpy(c).to(self.device)
570
+ noisez = torch.cat([noisez, c], dim=1)
571
+ noisez = noisez.view(sample_batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
572
+
573
+ fake = self.generator(noisez)
574
+ faket = self.Gtransformer.inverse_transform(fake)
575
+ fakeact = apply_activate(faket,output_info)
576
+ data.append(fakeact.detach().cpu().numpy())
577
+
578
+ data = np.concatenate(data, axis=0)
579
+ result,resample = self.transformer.inverse_transform(data)
580
+
581
+ t0 = time.time()
582
+ while len(result) < n and (time.time() - t0) <= 600:
583
+ data_resample = []
584
+ steps_left = resample// sample_batch_size + 1
585
+ # print(f"Sampling: {len(result)}/{n}")
586
+ for i in range(steps_left):
587
+ noisez = torch.randn(sample_batch_size, self.random_dim, device=self.device)
588
+ condvec = self.cond_generator.sample(sample_batch_size)
589
+ c = condvec
590
+ c = torch.from_numpy(c).to(self.device)
591
+ noisez = torch.cat([noisez, c], dim=1)
592
+ noisez = noisez.view(sample_batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
593
+
594
+ fake = self.generator(noisez)
595
+ faket = self.Gtransformer.inverse_transform(fake)
596
+ fakeact = apply_activate(faket, output_info)
597
+ data_resample.append(fakeact.detach().cpu().numpy())
598
+
599
+ data_resample = np.concatenate(data_resample, axis=0)
600
+
601
+ res,resample = self.transformer.inverse_transform(data_resample)
602
+ result = np.concatenate([result,res],axis=0)
603
+
604
+ return result[0:n]
605
+
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/transformer.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import torch
4
+ from sklearn.mixture import BayesianGaussianMixture
5
+
6
+ class DataTransformer():
7
+
8
+ def __init__(self, train_data=pd.DataFrame, categorical_list=[], mixed_dict={}, general_list=[], non_categorical_list=[], n_clusters=10, eps=0.005):
9
+ self.meta = None
10
+ self.n_clusters = n_clusters
11
+ self.eps = eps
12
+ self.train_data = train_data
13
+ self.categorical_columns= categorical_list
14
+ self.mixed_columns= mixed_dict
15
+ self.general_columns = general_list
16
+ self.non_categorical_columns= non_categorical_list
17
+
18
+ def get_metadata(self):
19
+
20
+ meta = []
21
+
22
+ for index in range(self.train_data.shape[1]):
23
+ column = self.train_data.iloc[:,index]
24
+ if index in self.categorical_columns:
25
+ if index in self.non_categorical_columns:
26
+ meta.append({
27
+ "name": index,
28
+ "type": "continuous",
29
+ "min": column.min(),
30
+ "max": column.max(),
31
+ })
32
+ else:
33
+ mapper = column.value_counts().index.tolist()
34
+ meta.append({
35
+ "name": index,
36
+ "type": "categorical",
37
+ "size": len(mapper),
38
+ "i2s": mapper
39
+ })
40
+
41
+ elif index in self.mixed_columns.keys():
42
+ meta.append({
43
+ "name": index,
44
+ "type": "mixed",
45
+ "min": column.min(),
46
+ "max": column.max(),
47
+ "modal": self.mixed_columns[index]
48
+ })
49
+ else:
50
+ meta.append({
51
+ "name": index,
52
+ "type": "continuous",
53
+ "min": column.min(),
54
+ "max": column.max(),
55
+ })
56
+
57
+ return meta
58
+
59
+ def fit(self):
60
+ data = self.train_data.values
61
+ self.meta = self.get_metadata()
62
+ model = []
63
+ self.ordering = []
64
+ self.output_info = []
65
+ self.output_dim = 0
66
+ self.components = []
67
+ self.filter_arr = []
68
+ for id_, info in enumerate(self.meta):
69
+ if info['type'] == "continuous":
70
+ if id_ not in self.general_columns:
71
+ gm = BayesianGaussianMixture(
72
+ n_components = self.n_clusters,
73
+ weight_concentration_prior_type='dirichlet_process',
74
+ weight_concentration_prior=0.001,
75
+ max_iter=100,n_init=1, random_state=42)
76
+ gm.fit(data[:, id_].reshape([-1, 1]))
77
+ mode_freq = (pd.Series(gm.predict(data[:, id_].reshape([-1, 1]))).value_counts().keys())
78
+ model.append(gm)
79
+ old_comp = gm.weights_ > self.eps
80
+ comp = []
81
+ for i in range(self.n_clusters):
82
+ if (i in (mode_freq)) & old_comp[i]:
83
+ comp.append(True)
84
+ else:
85
+ comp.append(False)
86
+ self.components.append(comp)
87
+ self.output_info += [(1, 'tanh','no_g'), (np.sum(comp), 'softmax')]
88
+ self.output_dim += 1 + np.sum(comp)
89
+ else:
90
+ model.append(None)
91
+ self.components.append(None)
92
+ self.output_info += [(1, 'tanh','yes_g')]
93
+ self.output_dim += 1
94
+
95
+ elif info['type'] == "mixed":
96
+
97
+ gm1 = BayesianGaussianMixture(
98
+ n_components = self.n_clusters,
99
+ weight_concentration_prior_type='dirichlet_process',
100
+ weight_concentration_prior=0.001, max_iter=100,
101
+ n_init=1,random_state=42)
102
+ gm2 = BayesianGaussianMixture(
103
+ n_components = self.n_clusters,
104
+ weight_concentration_prior_type='dirichlet_process',
105
+ weight_concentration_prior=0.001, max_iter=100,
106
+ n_init=1,random_state=42)
107
+
108
+ gm1.fit(data[:, id_].reshape([-1, 1]))
109
+
110
+ filter_arr = []
111
+ for element in data[:, id_]:
112
+ if element not in info['modal']:
113
+ filter_arr.append(True)
114
+ else:
115
+ filter_arr.append(False)
116
+
117
+ gm2.fit(data[:, id_][filter_arr].reshape([-1, 1]))
118
+ mode_freq = (pd.Series(gm2.predict(data[:, id_][filter_arr].reshape([-1, 1]))).value_counts().keys())
119
+ self.filter_arr.append(filter_arr)
120
+ model.append((gm1,gm2))
121
+
122
+ old_comp = gm2.weights_ > self.eps
123
+
124
+ comp = []
125
+
126
+ for i in range(self.n_clusters):
127
+ if (i in (mode_freq)) & old_comp[i]:
128
+ comp.append(True)
129
+ else:
130
+ comp.append(False)
131
+
132
+ self.components.append(comp)
133
+
134
+ self.output_info += [(1, 'tanh',"no_g"), (np.sum(comp) + len(info['modal']), 'softmax')]
135
+ self.output_dim += 1 + np.sum(comp) + len(info['modal'])
136
+ else:
137
+ model.append(None)
138
+ self.components.append(None)
139
+ self.output_info += [(info['size'], 'softmax')]
140
+ self.output_dim += info['size']
141
+ self.model = model
142
+
143
+ def transform(self, data, ispositive = False, positive_list = None):
144
+ values = []
145
+ mixed_counter = 0
146
+ for id_, info in enumerate(self.meta):
147
+ current = data[:, id_]
148
+ if info['type'] == "continuous":
149
+ if id_ not in self.general_columns:
150
+ current = current.reshape([-1, 1])
151
+ means = self.model[id_].means_.reshape((1, self.n_clusters))
152
+ stds = np.sqrt(self.model[id_].covariances_).reshape((1, self.n_clusters))
153
+ features = np.empty(shape=(len(current),self.n_clusters))
154
+ if ispositive == True:
155
+ if id_ in positive_list:
156
+ features = np.abs(current - means) / (4 * stds)
157
+ else:
158
+ features = (current - means) / (4 * stds)
159
+
160
+ probs = self.model[id_].predict_proba(current.reshape([-1, 1]))
161
+ n_opts = sum(self.components[id_])
162
+ features = features[:, self.components[id_]]
163
+ probs = probs[:, self.components[id_]]
164
+
165
+ opt_sel = np.zeros(len(data), dtype='int')
166
+ for i in range(len(data)):
167
+ pp = probs[i] + 1e-6
168
+ pp = pp / sum(pp)
169
+ opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp)
170
+
171
+ idx = np.arange((len(features)))
172
+ features = features[idx, opt_sel].reshape([-1, 1])
173
+ features = np.clip(features, -.99, .99)
174
+ probs_onehot = np.zeros_like(probs)
175
+ probs_onehot[np.arange(len(probs)), opt_sel] = 1
176
+
177
+ re_ordered_phot = np.zeros_like(probs_onehot)
178
+
179
+ col_sums = probs_onehot.sum(axis=0)
180
+
181
+
182
+ n = probs_onehot.shape[1]
183
+ largest_indices = np.argsort(-1*col_sums)[:n]
184
+ self.ordering.append(largest_indices)
185
+ for id,val in enumerate(largest_indices):
186
+ re_ordered_phot[:,id] = probs_onehot[:,val]
187
+
188
+
189
+ values += [features, re_ordered_phot]
190
+
191
+ else:
192
+
193
+ self.ordering.append(None)
194
+
195
+ if id_ in self.non_categorical_columns:
196
+ info['min'] = -1e-3
197
+ info['max'] = info['max'] + 1e-3
198
+
199
+ current = (current - (info['min'])) / (info['max'] - info['min'])
200
+ current = current * 2 - 1
201
+ current = current.reshape([-1, 1])
202
+ values.append(current)
203
+
204
+ elif info['type'] == "mixed":
205
+
206
+ means_0 = self.model[id_][0].means_.reshape([-1])
207
+ stds_0 = np.sqrt(self.model[id_][0].covariances_).reshape([-1])
208
+
209
+ zero_std_list = []
210
+ means_needed = []
211
+ stds_needed = []
212
+
213
+ for mode in info['modal']:
214
+ if mode!=-9999999:
215
+ dist = []
216
+ for idx,val in enumerate(list(means_0.flatten())):
217
+ dist.append(abs(mode-val))
218
+ index_min = np.argmin(np.array(dist))
219
+ zero_std_list.append(index_min)
220
+ else: continue
221
+
222
+ for idx in zero_std_list:
223
+ means_needed.append(means_0[idx])
224
+ stds_needed.append(stds_0[idx])
225
+
226
+
227
+ mode_vals = []
228
+
229
+ for i,j,k in zip(info['modal'],means_needed,stds_needed):
230
+ this_val = np.abs(i - j) / (4*k)
231
+ mode_vals.append(this_val)
232
+
233
+ if -9999999 in info["modal"]:
234
+ mode_vals.append(0)
235
+
236
+ current = current.reshape([-1, 1])
237
+ filter_arr = self.filter_arr[mixed_counter]
238
+ current = current[filter_arr]
239
+
240
+ means = self.model[id_][1].means_.reshape((1, self.n_clusters))
241
+ stds = np.sqrt(self.model[id_][1].covariances_).reshape((1, self.n_clusters))
242
+ features = np.empty(shape=(len(current),self.n_clusters))
243
+ if ispositive == True:
244
+ if id_ in positive_list:
245
+ features = np.abs(current - means) / (4 * stds)
246
+ else:
247
+ features = (current - means) / (4 * stds)
248
+
249
+ probs = self.model[id_][1].predict_proba(current.reshape([-1, 1]))
250
+
251
+ n_opts = sum(self.components[id_]) # 8
252
+ features = features[:, self.components[id_]]
253
+ probs = probs[:, self.components[id_]]
254
+
255
+ opt_sel = np.zeros(len(current), dtype='int')
256
+ for i in range(len(current)):
257
+ pp = probs[i] + 1e-6
258
+ pp = pp / sum(pp)
259
+ opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp)
260
+ idx = np.arange((len(features)))
261
+ features = features[idx, opt_sel].reshape([-1, 1])
262
+ features = np.clip(features, -.99, .99)
263
+ probs_onehot = np.zeros_like(probs)
264
+ probs_onehot[np.arange(len(probs)), opt_sel] = 1
265
+ extra_bits = np.zeros([len(current), len(info['modal'])])
266
+ temp_probs_onehot = np.concatenate([extra_bits,probs_onehot], axis = 1)
267
+ final = np.zeros([len(data), 1 + probs_onehot.shape[1] + len(info['modal'])])
268
+ features_curser = 0
269
+ for idx, val in enumerate(data[:, id_]):
270
+ if val in info['modal']:
271
+ category_ = list(map(info['modal'].index, [val]))[0]
272
+ final[idx, 0] = mode_vals[category_]
273
+ final[idx, (category_+1)] = 1
274
+
275
+ else:
276
+ final[idx, 0] = features[features_curser]
277
+ final[idx, (1+len(info['modal'])):] = temp_probs_onehot[features_curser][len(info['modal']):]
278
+ features_curser = features_curser + 1
279
+
280
+ just_onehot = final[:,1:]
281
+ re_ordered_jhot= np.zeros_like(just_onehot)
282
+ n = just_onehot.shape[1]
283
+ col_sums = just_onehot.sum(axis=0)
284
+ largest_indices = np.argsort(-1*col_sums)[:n]
285
+ self.ordering.append(largest_indices)
286
+ for id,val in enumerate(largest_indices):
287
+ re_ordered_jhot[:,id] = just_onehot[:,val]
288
+ final_features = final[:,0].reshape([-1, 1])
289
+ values += [final_features, re_ordered_jhot]
290
+ mixed_counter = mixed_counter + 1
291
+
292
+ else:
293
+ self.ordering.append(None)
294
+ col_t = np.zeros([len(data), info['size']])
295
+ idx = list(map(info['i2s'].index, current))
296
+ col_t[np.arange(len(data)), idx] = 1
297
+ values.append(col_t)
298
+
299
+ return np.concatenate(values, axis=1)
300
+
301
+ def inverse_transform(self, data):
302
+ data_t = np.zeros([len(data), len(self.meta)])
303
+ invalid_ids = []
304
+ st = 0
305
+ for id_, info in enumerate(self.meta):
306
+ if info['type'] == "continuous":
307
+ if id_ not in self.general_columns:
308
+ u = data[:, st]
309
+ v = data[:, st + 1:st + 1 + np.sum(self.components[id_])]
310
+ order = self.ordering[id_]
311
+ v_re_ordered = np.zeros_like(v)
312
+
313
+ for id,val in enumerate(order):
314
+ v_re_ordered[:,val] = v[:,id]
315
+
316
+ v = v_re_ordered
317
+
318
+ u = np.clip(u, -1, 1)
319
+ v_t = np.ones((data.shape[0], self.n_clusters)) * -100
320
+ v_t[:, self.components[id_]] = v
321
+ v = v_t
322
+ st += 1 + np.sum(self.components[id_])
323
+ means = self.model[id_].means_.reshape([-1])
324
+ stds = np.sqrt(self.model[id_].covariances_).reshape([-1])
325
+ p_argmax = np.argmax(v, axis=1)
326
+ std_t = stds[p_argmax]
327
+ mean_t = means[p_argmax]
328
+ tmp = u * 4 * std_t + mean_t
329
+
330
+ for idx,val in enumerate(tmp):
331
+ if (val < info["min"]) | (val > info['max']):
332
+ invalid_ids.append(idx)
333
+
334
+ if id_ in self.non_categorical_columns:
335
+
336
+ tmp = np.round(tmp)
337
+
338
+ data_t[:, id_] = tmp
339
+
340
+ else:
341
+ u = data[:, st]
342
+ u = (u + 1) / 2
343
+ u = np.clip(u, 0, 1)
344
+ u = u * (info['max'] - info['min']) + info['min']
345
+ if id_ in self.non_categorical_columns:
346
+ data_t[:, id_] = np.round(u)
347
+ else: data_t[:, id_] = u
348
+
349
+ st += 1
350
+
351
+ elif info['type'] == "mixed":
352
+
353
+ u = data[:, st]
354
+ full_v = data[:,(st+1):(st+1)+len(info['modal'])+np.sum(self.components[id_])]
355
+ order = self.ordering[id_]
356
+ full_v_re_ordered = np.zeros_like(full_v)
357
+
358
+ for id,val in enumerate(order):
359
+ full_v_re_ordered[:,val] = full_v[:,id]
360
+
361
+ full_v = full_v_re_ordered
362
+
363
+
364
+ mixed_v = full_v[:,:len(info['modal'])]
365
+ v = full_v[:,-np.sum(self.components[id_]):]
366
+
367
+ u = np.clip(u, -1, 1)
368
+ v_t = np.ones((data.shape[0], self.n_clusters)) * -100
369
+ v_t[:, self.components[id_]] = v
370
+ v = np.concatenate([mixed_v,v_t], axis=1)
371
+
372
+ st += 1 + np.sum(self.components[id_]) + len(info['modal'])
373
+ means = self.model[id_][1].means_.reshape([-1])
374
+ stds = np.sqrt(self.model[id_][1].covariances_).reshape([-1])
375
+ p_argmax = np.argmax(v, axis=1)
376
+
377
+ result = np.zeros_like(u)
378
+
379
+ for idx in range(len(data)):
380
+ if p_argmax[idx] < len(info['modal']):
381
+ argmax_value = p_argmax[idx]
382
+ result[idx] = float(list(map(info['modal'].__getitem__, [argmax_value]))[0])
383
+ else:
384
+ std_t = stds[(p_argmax[idx]-len(info['modal']))]
385
+ mean_t = means[(p_argmax[idx]-len(info['modal']))]
386
+ result[idx] = u[idx] * 4 * std_t + mean_t
387
+
388
+ for idx,val in enumerate(result):
389
+ if (val < info["min"]) | (val > info['max']):
390
+ invalid_ids.append(idx)
391
+
392
+ data_t[:, id_] = result
393
+
394
+ else:
395
+ current = data[:, st:st + info['size']]
396
+ st += info['size']
397
+ idx = np.argmax(current, axis=1)
398
+ data_t[:, id_] = list(map(info['i2s'].__getitem__, idx))
399
+
400
+
401
+ invalid_ids = np.unique(np.array(invalid_ids))
402
+ all_ids = np.arange(0,len(data))
403
+ valid_ids = list(set(all_ids) - set(invalid_ids))
404
+
405
+ return data_t[valid_ids],len(invalid_ids)
406
+
407
+
408
+ class ImageTransformer():
409
+
410
+ def __init__(self, side):
411
+
412
+ self.height = side
413
+
414
+ def transform(self, data):
415
+
416
+ if self.height * self.height > len(data[0]):
417
+
418
+ padding = torch.zeros((len(data), self.height * self.height - len(data[0]))).to(data.device)
419
+ data = torch.cat([data, padding], axis=1)
420
+
421
+ return data.view(-1, 1, self.height, self.height)
422
+
423
+ def inverse_transform(self, data):
424
+
425
+ data = data.view(-1, self.height * self.height)
426
+
427
+ return data
428
+
429
+
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tomli
2
+ import shutil
3
+ import os
4
+ import argparse
5
+ from train_sample_ctabganp import train_ctabgan, sample_ctabgan
6
+ from scripts.eval_catboost import train_catboost
7
+ import zero
8
+ import lib
9
+ from model.ctabgan import CTABGAN
10
+
11
+ def load_config(path) :
12
+ with open(path, 'rb') as f:
13
+ return tomli.load(f)
14
+
15
+ def save_file(parent_dir, config_path):
16
+ try:
17
+ dst = os.path.join(parent_dir)
18
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
19
+ shutil.copyfile(os.path.abspath(config_path), dst)
20
+ except shutil.SameFileError:
21
+ pass
22
+
23
+ def main():
24
+ parser = argparse.ArgumentParser()
25
+ parser.add_argument('--config', metavar='FILE')
26
+ parser.add_argument('--train', action='store_true', default=False)
27
+ parser.add_argument('--sample', action='store_true', default=False)
28
+ parser.add_argument('--eval', action='store_true', default=False)
29
+ parser.add_argument('--change_val', action='store_true', default=False)
30
+
31
+ args = parser.parse_args()
32
+ raw_config = lib.load_config(args.config)
33
+ timer = zero.Timer()
34
+ timer.run()
35
+ save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
36
+ ctabgan = None
37
+ if args.train:
38
+ ctabgan = train_ctabgan(
39
+ parent_dir=raw_config['parent_dir'],
40
+ real_data_path=raw_config['real_data_path'],
41
+ train_params=raw_config['train_params'],
42
+ change_val=args.change_val,
43
+ device=raw_config['device']
44
+ )
45
+ if args.sample:
46
+ sample_ctabgan(
47
+ synthesizer=ctabgan,
48
+ parent_dir=raw_config['parent_dir'],
49
+ real_data_path=raw_config['real_data_path'],
50
+ num_samples=raw_config['sample']['num_samples'],
51
+ train_params=raw_config['train_params'],
52
+ change_val=args.change_val,
53
+ seed=raw_config['sample']['seed'],
54
+ device=raw_config['device']
55
+ )
56
+
57
+ save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
58
+ if args.eval:
59
+ if raw_config['eval']['type']['eval_model'] == 'catboost':
60
+ train_catboost(
61
+ parent_dir=raw_config['parent_dir'],
62
+ real_data_path=raw_config['real_data_path'],
63
+ eval_type=raw_config['eval']['type']['eval_type'],
64
+ T_dict=raw_config['eval']['T'],
65
+ seed=raw_config['seed'],
66
+ change_val=args.change_val
67
+ )
68
+ # elif raw_config['eval']['type']['eval_model'] == 'mlp':
69
+ # train_mlp(
70
+ # parent_dir=raw_config['parent_dir'],
71
+ # real_data_path=raw_config['real_data_path'],
72
+ # eval_type=raw_config['eval']['type']['eval_type'],
73
+ # T_dict=raw_config['eval']['T'],
74
+ # seed=raw_config['seed'],
75
+ # change_val=args.change_val
76
+ # )
77
+
78
+ print(f'Elapsed time: {str(timer)}')
79
+
80
+ if __name__ == '__main__':
81
+ main()
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import lib
2
+ import os
3
+ import numpy as np
4
+ import argparse
5
+ from model.ctabgan import CTABGAN
6
+ from pathlib import Path
7
+ import torch
8
+ import pickle
9
+
10
+
11
+ def train_ctabgan(
12
+ parent_dir,
13
+ real_data_path,
14
+ train_params = {"batch_size": 512},
15
+ change_val=False,
16
+ device = "cpu"
17
+ ):
18
+ real_data_path = Path(real_data_path)
19
+ parent_dir = Path(parent_dir)
20
+ device = torch.device(device)
21
+
22
+ if change_val:
23
+ X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
24
+ else:
25
+ X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
26
+
27
+ X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
28
+
29
+ X.columns = [str(_) for _ in X.columns]
30
+
31
+ ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name]
32
+ train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
33
+
34
+ print(train_params)
35
+ synthesizer = CTABGAN(
36
+ df = X,
37
+ test_ratio = 0.0,
38
+ **ctabgan_params,
39
+ **train_params,
40
+ device=device
41
+ )
42
+
43
+ synthesizer.fit()
44
+
45
+ # save_ctabgan(synthesizer, parent_dir)
46
+ with open(parent_dir / "ctabgan.obj", "wb") as f:
47
+ pickle.dump(synthesizer, f)
48
+
49
+ return synthesizer
50
+
51
+ def sample_ctabgan(
52
+ synthesizer,
53
+ parent_dir,
54
+ real_data_path,
55
+ num_samples,
56
+ train_params = {"batch_size": 512},
57
+ change_val=False,
58
+ device="cpu",
59
+ seed=0
60
+ ):
61
+ real_data_path = Path(real_data_path)
62
+ parent_dir = Path(parent_dir)
63
+ device = torch.device(device)
64
+
65
+ if change_val:
66
+ X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
67
+ else:
68
+ X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
69
+
70
+ X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
71
+
72
+ X.columns = [str(_) for _ in X.columns]
73
+
74
+ ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name]
75
+
76
+ cat_features = ctabgan_params["categorical_columns"]
77
+ # if synthesizer is None:
78
+ # synthesizer = load_ctabgan(X, ctabgan_params, train_params, parent_dir)
79
+ with open(parent_dir / "ctabgan.obj", 'rb') as f:
80
+ synthesizer = pickle.load(f)
81
+ synthesizer.synthesizer.generator = synthesizer.synthesizer.generator.to(device)
82
+ gen_data = synthesizer.generate_samples(num_samples, seed)
83
+
84
+ y = gen_data['y'].values
85
+ if len(np.unique(y)) == 1:
86
+ y[0] = 0
87
+ y[1] = 1
88
+
89
+ X_cat = gen_data[cat_features].drop('y', axis=1, errors="ignore").values if len(cat_features) else None
90
+ X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
91
+
92
+ if X_num_train is not None:
93
+ np.save(parent_dir / 'X_num_train', X_num.astype(float))
94
+ if X_cat_train is not None:
95
+ np.save(parent_dir / 'X_cat_train', X_cat.astype(str))
96
+ np.save(parent_dir / 'y_train', y.astype(float).astype(int)) # only clf !!!
97
+
98
+ def main():
99
+ parser = argparse.ArgumentParser()
100
+ parser.add_argument('real_data_path', type=str)
101
+ parser.add_argument('parent_dir', type=str)
102
+ parser.add_argument('train_size', type=int)
103
+ args = parser.parse_args()
104
+
105
+ ctabgan = train_ctabgan(args.parent_dir, args.real_data_path, change_val=True)
106
+ sample_ctabgan(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
107
+
108
+
109
+ if __name__ == '__main__':
110
+ main()
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from multiprocessing.sharedctypes import RawValue
2
+ from random import random
3
+ import tempfile
4
+ import subprocess
5
+ import lib
6
+ import os
7
+ import optuna
8
+ import argparse
9
+ from pathlib import Path
10
+ from train_sample_ctabganp import train_ctabgan, sample_ctabgan
11
+ from scripts.eval_catboost import train_catboost
12
+
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument('data_path', type=str)
15
+ parser.add_argument('train_size', type=int)
16
+ parser.add_argument('eval_type', type=str)
17
+ parser.add_argument('device', type=str)
18
+
19
+ args = parser.parse_args()
20
+ real_data_path = args.data_path
21
+ eval_type = args.eval_type
22
+ train_size = args.train_size
23
+ device = args.device
24
+ assert eval_type in ('merged', 'synthetic')
25
+
26
+ def objective(trial):
27
+
28
+ lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
29
+
30
+ def suggest_dim(name):
31
+ t = trial.suggest_int(name, d_min, d_max)
32
+ return 2 ** t
33
+
34
+ # construct model
35
+ min_n_layers, max_n_layers, d_min, d_max = 1, 4, 6, 8
36
+ n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers)
37
+ d_first = [suggest_dim('d_first')] if n_layers else []
38
+ d_middle = (
39
+ [suggest_dim('d_middle')] * (n_layers - 2)
40
+ if n_layers > 2
41
+ else []
42
+ )
43
+ d_last = [suggest_dim('d_last')] if n_layers > 1 else []
44
+ d_layers = d_first + d_middle + d_last
45
+ ####
46
+
47
+ steps = trial.suggest_categorical('steps', [1000, 5000, 10000])
48
+ # steps = trial.suggest_categorical('steps', [10])
49
+ batch_size = 2 ** trial.suggest_int('batch_size', 9, 11)
50
+ random_dim = 2 ** trial.suggest_int('random_dim', 4, 7)
51
+ num_channels = 2 ** trial.suggest_int('num_channels', 4, 6)
52
+
53
+ # steps = trial.suggest_categorical('steps', [1000])
54
+
55
+ num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3)))
56
+
57
+ train_params = {
58
+ "lr": lr,
59
+ "epochs": steps,
60
+ "class_dim": d_layers,
61
+ "batch_size": batch_size,
62
+ "random_dim": random_dim,
63
+ "num_channels": num_channels
64
+ }
65
+ trial.set_user_attr("train_params", train_params)
66
+ trial.set_user_attr("num_samples", num_samples)
67
+
68
+ score = 0.0
69
+ with tempfile.TemporaryDirectory() as dir_:
70
+ dir_ = Path(dir_)
71
+ ctabgan = train_ctabgan(
72
+ parent_dir=dir_,
73
+ real_data_path=real_data_path,
74
+ train_params=train_params,
75
+ change_val=True,
76
+ device=device
77
+ )
78
+
79
+ for sample_seed in range(5):
80
+ sample_ctabgan(
81
+ ctabgan,
82
+ parent_dir=dir_,
83
+ real_data_path=real_data_path,
84
+ num_samples=num_samples,
85
+ train_params=train_params,
86
+ change_val=True,
87
+ seed=sample_seed,
88
+ device=device
89
+ )
90
+
91
+ T_dict = {
92
+ "seed": 0,
93
+ "normalization": None,
94
+ "num_nan_policy": None,
95
+ "cat_nan_policy": None,
96
+ "cat_min_frequency": None,
97
+ "cat_encoding": None,
98
+ "y_policy": "default"
99
+ }
100
+ metrics = train_catboost(
101
+ parent_dir=dir_,
102
+ real_data_path=real_data_path,
103
+ eval_type=eval_type,
104
+ T_dict=T_dict,
105
+ change_val=True,
106
+ seed = 0
107
+ )
108
+
109
+ score += metrics.get_val_score()
110
+ return score / 5
111
+
112
+
113
+ study = optuna.create_study(
114
+ direction='maximize',
115
+ sampler=optuna.samplers.TPESampler(seed=0),
116
+ )
117
+
118
+ study.optimize(objective, n_trials=35, show_progress_bar=True)
119
+
120
+ os.makedirs(f"exp/{Path(real_data_path).name}/ctabgan-plus/", exist_ok=True)
121
+ config = {
122
+ "parent_dir": f"exp/{Path(real_data_path).name}/ctabgan-plus/",
123
+ "real_data_path": real_data_path,
124
+ "seed": 0,
125
+ "device": args.device,
126
+ "train_params": study.best_trial.user_attrs["train_params"],
127
+ "sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]},
128
+ "eval": {
129
+ "type": {"eval_model": "catboost", "eval_type": eval_type},
130
+ "T": {
131
+ "seed": 0,
132
+ "normalization": None,
133
+ "num_nan_policy": None,
134
+ "cat_nan_policy": None,
135
+ "cat_min_frequency": None,
136
+ "cat_encoding": None,
137
+ "y_policy": "default"
138
+ },
139
+ }
140
+ }
141
+
142
+ train_ctabgan(
143
+ parent_dir=f"exp/{Path(real_data_path).name}/ctabgan-plus/",
144
+ real_data_path=real_data_path,
145
+ train_params=study.best_trial.user_attrs["train_params"],
146
+ change_val=False,
147
+ device=device
148
+ )
149
+
150
+ lib.dump_config(config, config["parent_dir"]+"config.toml")
151
+
152
+ subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}',
153
+ '10', "ctabgan-plus", eval_type, "catboost", "5"], check=True)
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ **/**.csv
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/License.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Distributed learning systems Lab at TU Delft & Generatrix, hereby disclaims all copyright interest in the program "CTAB-GAN" (which synthesizes tabular data)
2
+
3
+ Copyright 2020-2022 Distributed learning systems Lab at TU Delft & Generatrix.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ https://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/README.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CTAB-GAN
2
+ This is the official git paper [CTAB-GAN: Effective Table Data Synthesizing](https://proceedings.mlr.press/v157/zhao21a.html). The paper is published on Asian Conference on Machine Learning (ACML 2021), please check our pdf on PMLR website for our newest version of [paper](https://proceedings.mlr.press/v157/zhao21a.html), it adds more content on time consumption analysis of training CTAB-GAN. If you have any question, please contact `z.zhao-8@tudelft.nl` for more information.
3
+
4
+
5
+ ## Prerequisite
6
+
7
+ The required package version
8
+ ```
9
+ numpy==1.21.0
10
+ torch==1.9.1
11
+ pandas==1.2.4
12
+ sklearn==0.24.1
13
+ dython==0.6.4.post1
14
+ scipy==1.4.1
15
+ ```
16
+
17
+ ## Example
18
+ `Experiment_Script_Adult.ipynb` is an example notebook for training CTAB-GAN with Adult dataset. The dataset is alread under `Real_Datasets` folder.
19
+ The evaluation code is also provided.
20
+
21
+ ## For large dataset
22
+
23
+ If your dataset has large number of column, you may encounter the problem that our currnet code cannot encode all of your data since CTAB-GAN will wrap the encoded data into an image-like format. What you can do is changing the line 341 and 348 in `model/synthesizer/ctabgan_synthesizer.py`. The number in the `slide` list
24
+ ```
25
+ sides = [4, 8, 16, 24, 32]
26
+ ```
27
+ is the side size of image. You can enlarge the list to [4, 8, 16, 24, 32, 64] or [4, 8, 16, 24, 32, 64, 128] for accepting larger dataset.
28
+
29
+ ## Bibtex
30
+
31
+ To cite this paper, you could use this bibtex
32
+
33
+ ```
34
+ @InProceedings{zhao21,
35
+ title = {CTAB-GAN: Effective Table Data Synthesizing},
36
+ author = {Zhao, Zilong and Kunar, Aditya and Birke, Robert and Chen, Lydia Y.},
37
+ booktitle = {Proceedings of The 13th Asian Conference on Machine Learning},
38
+ pages = {97--112},
39
+ year = {2021},
40
+ editor = {Balasubramanian, Vineeth N. and Tsang, Ivor},
41
+ volume = {157},
42
+ series = {Proceedings of Machine Learning Research},
43
+ month = {17--19 Nov},
44
+ publisher = {PMLR},
45
+ pdf = {https://proceedings.mlr.press/v157/zhao21a/zhao21a.pdf},
46
+ url = {https://proceedings.mlr.press/v157/zhao21a.html}
47
+ }
48
+
49
+
50
+ ```
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/columns.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "churn2": {
3
+ "categorical_columns": ["7", "8", "9", "10", "y"],
4
+ "mixed_columns": {"0": [850.0], "3": [0.0]},
5
+ "integer_columns": ["1", "2", "4"],
6
+ "problem_type": {"Classification": "y"}
7
+ },
8
+ "adult": {
9
+ "categorical_columns": ["6", "7", "8", "9", "10", "11", "12", "13", "y"],
10
+ "mixed_columns": {"3": [0.0], "4": [0.0]},
11
+ "integer_columns": ["0", "2", "5"],
12
+ "problem_type": {"Classification": "y"}
13
+ },
14
+ "buddy": {
15
+ "categorical_columns": ["4", "5", "6", "7", "8", "y"],
16
+ "mixed_columns": {},
17
+ "integer_columns": ["0", "1"],
18
+ "problem_type": {"Classification": "y"}
19
+ },
20
+ "gesture": {
21
+ "categorical_columns": ["y"],
22
+ "mixed_columns": {},
23
+ "integer_columns": [],
24
+ "problem_type": {"Classification": "y"}
25
+ },
26
+ "wilt": {
27
+ "categorical_columns": ["y"],
28
+ "mixed_columns": {},
29
+ "integer_columns": [],
30
+ "problem_type": {"Classification": "y"}
31
+ },
32
+ "satellite": {
33
+ "categorical_columns": ["y"],
34
+ "mixed_columns": {},
35
+ "integer_columns": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35"],
36
+ "problem_type": {"Classification": "y"}
37
+ },
38
+ "higgs-small": {
39
+ "categorical_columns": ["y"],
40
+ "mixed_columns": {},
41
+ "integer_columns": [],
42
+ "problem_type": {"Classification": "y"}
43
+ },
44
+ "diabetes": {
45
+ "categorical_columns": ["y"],
46
+ "mixed_columns": {"3": [0.0], "4": [0.0]},
47
+ "integer_columns": ["0", "1", "2", "5", "7"],
48
+ "problem_type": {"Classification": "y"}
49
+ },
50
+ "default": {
51
+ "categorical_columns": ["20", "21", "22", "y"],
52
+ "mixed_columns": {},
53
+ "integer_columns": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19"],
54
+ "problem_type": {"Classification": "y"}
55
+ },
56
+ "otto": {
57
+ "categorical_columns": ["y"],
58
+ "mixed_columns": {},
59
+ "integer_columns": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90", "91", "92"],
60
+ "problem_type": {"Classification": "y"}
61
+ },
62
+ "cardio": {
63
+ "categorical_columns": ["5", "6", "7", "8", "9", "10", "y"],
64
+ "mixed_columns": {},
65
+ "integer_columns": ["0", "1", "3", "4"],
66
+ "problem_type": {"Classification": "y"}
67
+ },
68
+ "miniboone": {
69
+ "categorical_columns": ["y"],
70
+ "mixed_columns": {},
71
+ "integer_columns": [],
72
+ "problem_type": {"Classification": "y"}
73
+ }
74
+ }
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/model/__init__.py ADDED
File without changes
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generative model training algorithm based on the CTABGANSynthesiser
3
+
4
+ """
5
+ import pandas as pd
6
+ import time
7
+ from model.pipeline.data_preparation import DataPrep
8
+ from model.synthesizer.ctabgan_synthesizer import CTABGANSynthesizer
9
+
10
+ import warnings
11
+
12
+ warnings.filterwarnings("ignore")
13
+
14
+ class CTABGAN():
15
+
16
+ def __init__(self,
17
+ df,
18
+ test_ratio = 0.20,
19
+ categorical_columns = [ 'workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'gender', 'native-country', 'income'],
20
+ log_columns = [],
21
+ mixed_columns= {'capital-loss':[0.0],'capital-gain':[0.0]},
22
+ integer_columns = ['age', 'fnlwgt','capital-gain', 'capital-loss','hours-per-week'],
23
+ problem_type= {"Classification": 'income'},
24
+ batch_size = 512,
25
+ class_dim = (256, 256, 256, 256),
26
+ lr = 2e-4,
27
+ epochs = 10,
28
+ device=None):
29
+
30
+ self.__name__ = 'CTABGAN'
31
+
32
+ self.synthesizer = CTABGANSynthesizer(lr = lr, epochs = epochs, batch_size = batch_size, class_dim = class_dim, device = device)
33
+ self.raw_df = df
34
+ print(self.raw_df.shape)
35
+ self.test_ratio = test_ratio
36
+ self.categorical_columns = categorical_columns
37
+ self.log_columns = log_columns
38
+ self.mixed_columns = mixed_columns
39
+ self.integer_columns = integer_columns
40
+ self.problem_type = problem_type
41
+
42
+ def fit(self, no_train=False):
43
+ print("-"*100)
44
+ start_time = time.time()
45
+ self.data_prep = DataPrep(self.raw_df,self.categorical_columns,self.log_columns,self.mixed_columns,self.integer_columns,self.problem_type,self.test_ratio)
46
+ self.synthesizer.fit(train_data=self.data_prep.df, categorical = self.data_prep.column_types["categorical"],
47
+ mixed = self.data_prep.column_types["mixed"],type=self.problem_type, no_train=no_train)
48
+ end_time = time.time()
49
+ print('Finished training in',end_time-start_time," seconds.")
50
+ print("-"*100)
51
+
52
+
53
+ def generate_samples(self, num_samples, seed=0):
54
+
55
+ sample = self.synthesizer.sample(num_samples, seed)
56
+ sample_df = self.data_prep.inverse_prep(sample)
57
+
58
+ return sample_df
syntheticFail/m12/tabddpm/tabddpm-m12-20260510_223642/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn import metrics
4
+ from sklearn import model_selection
5
+ from sklearn.preprocessing import MinMaxScaler,StandardScaler
6
+ from sklearn.neural_network import MLPClassifier
7
+ from sklearn.linear_model import LogisticRegression
8
+ from sklearn import svm,tree
9
+ from sklearn.ensemble import RandomForestClassifier
10
+ from dython.nominal import compute_associations
11
+ from scipy.stats import wasserstein_distance
12
+ from scipy.spatial import distance
13
+ import warnings
14
+
15
+ warnings.filterwarnings("ignore")
16
+
17
+ def supervised_model_training(x_train, y_train, x_test,
18
+ y_test, model_name):
19
+
20
+ if model_name == 'lr':
21
+ model = LogisticRegression(random_state=42,max_iter=500)
22
+ elif model_name == 'svm':
23
+ model = svm.SVC(random_state=42,probability=True)
24
+ elif model_name == 'dt':
25
+ model = tree.DecisionTreeClassifier(random_state=42)
26
+ elif model_name == 'rf':
27
+ model = RandomForestClassifier(random_state=42)
28
+ elif model_name == "mlp":
29
+ model = MLPClassifier(random_state=42,max_iter=100)
30
+
31
+ model.fit(x_train, y_train)
32
+ pred = model.predict(x_test)
33
+
34
+ if len(np.unique(y_train))>2:
35
+ predict = model.predict_proba(x_test)
36
+ acc = metrics.accuracy_score(y_test,pred)*100
37
+ auc = metrics.roc_auc_score(y_test, predict,average="weighted",multi_class="ovr")
38
+ f1_score = metrics.precision_recall_fscore_support(y_test, pred,average="weighted")[2]
39
+ return [acc, auc,f1_score]
40
+
41
+ else:
42
+ predict = model.predict_proba(x_test)[:,1]
43
+ acc = metrics.accuracy_score(y_test,pred)*100
44
+ auc = metrics.roc_auc_score(y_test, predict)
45
+ f1_score = metrics.precision_recall_fscore_support(y_test,pred)[2].mean()
46
+ return [acc, auc,f1_score]
47
+
48
+
49
+ def get_utility_metrics(real_path,fake_paths,scaler="MinMax",classifiers=["lr","dt","rf","mlp"],test_ratio=.20):
50
+
51
+ data_real = pd.read_csv(real_path).to_numpy()
52
+ data_dim = data_real.shape[1]
53
+
54
+ data_real_y = data_real[:,-1]
55
+ data_real_X = data_real[:,:data_dim-1]
56
+ X_train_real, X_test_real, y_train_real, y_test_real = model_selection.train_test_split(data_real_X ,data_real_y, test_size=test_ratio, stratify=data_real_y,random_state=42)
57
+
58
+ if scaler=="MinMax":
59
+ scaler_real = MinMaxScaler()
60
+ else:
61
+ scaler_real = StandardScaler()
62
+
63
+ scaler_real.fit(X_train_real)
64
+ X_train_real_scaled = scaler_real.transform(X_train_real)
65
+ X_test_real_scaled = scaler_real.transform(X_test_real)
66
+
67
+ all_real_results = []
68
+ for classifier in classifiers:
69
+ real_results = supervised_model_training(X_train_real_scaled,y_train_real,X_test_real_scaled,y_test_real,classifier)
70
+ all_real_results.append(real_results)
71
+
72
+ all_fake_results_avg = []
73
+
74
+ for fake_path in fake_paths:
75
+ data_fake = pd.read_csv(fake_path).to_numpy()
76
+ data_fake_y = data_fake[:,-1]
77
+ data_fake_X = data_fake[:,:data_dim-1]
78
+ X_train_fake, _ , y_train_fake, _ = model_selection.train_test_split(data_fake_X ,data_fake_y, test_size=test_ratio, stratify=data_fake_y,random_state=42)
79
+
80
+ if scaler=="MinMax":
81
+ scaler_fake = MinMaxScaler()
82
+ else:
83
+ scaler_fake = StandardScaler()
84
+
85
+ scaler_fake.fit(data_fake_X)
86
+
87
+ X_train_fake_scaled = scaler_fake.transform(X_train_fake)
88
+
89
+ all_fake_results = []
90
+ for classifier in classifiers:
91
+ fake_results = supervised_model_training(X_train_fake_scaled,y_train_fake,X_test_real_scaled,y_test_real,classifier)
92
+ all_fake_results.append(fake_results)
93
+
94
+ all_fake_results_avg.append(all_fake_results)
95
+
96
+ diff_results = np.array(all_real_results)- np.array(all_fake_results_avg).mean(axis=0)
97
+
98
+ return diff_results
99
+
100
+ def stat_sim(real_path,fake_path,cat_cols=None):
101
+
102
+ Stat_dict={}
103
+
104
+ real = pd.read_csv(real_path)
105
+ fake = pd.read_csv(fake_path)
106
+
107
+ really = real.copy()
108
+ fakey = fake.copy()
109
+
110
+ real_corr = compute_associations(real, nominal_columns=cat_cols)
111
+
112
+ fake_corr = compute_associations(fake, nominal_columns=cat_cols)
113
+
114
+ corr_dist = np.linalg.norm(real_corr - fake_corr)
115
+
116
+ cat_stat = []
117
+ num_stat = []
118
+
119
+ for column in real.columns:
120
+
121
+ if column in cat_cols:
122
+ real_pdf=(really[column].value_counts()/really[column].value_counts().sum())
123
+ fake_pdf=(fakey[column].value_counts()/fakey[column].value_counts().sum())
124
+ categories = (fakey[column].value_counts()/fakey[column].value_counts().sum()).keys().tolist()
125
+ sorted_categories = sorted(categories)
126
+
127
+ real_pdf_values = []
128
+ fake_pdf_values = []
129
+
130
+ for i in sorted_categories:
131
+ real_pdf_values.append(real_pdf[i])
132
+ fake_pdf_values.append(fake_pdf[i])
133
+
134
+ if len(real_pdf)!=len(fake_pdf):
135
+ zero_cats = set(really[column].value_counts().keys())-set(fakey[column].value_counts().keys())
136
+ for z in zero_cats:
137
+ real_pdf_values.append(real_pdf[z])
138
+ fake_pdf_values.append(0)
139
+ Stat_dict[column]=(distance.jensenshannon(real_pdf_values,fake_pdf_values, 2.0))
140
+ cat_stat.append(Stat_dict[column])
141
+ else:
142
+ scaler = MinMaxScaler()
143
+ scaler.fit(real[column].values.reshape(-1,1))
144
+ l1 = scaler.transform(real[column].values.reshape(-1,1)).flatten()
145
+ l2 = scaler.transform(fake[column].values.reshape(-1,1)).flatten()
146
+ Stat_dict[column]= (wasserstein_distance(l1,l2))
147
+ num_stat.append(Stat_dict[column])
148
+
149
+ return [np.mean(num_stat),np.mean(cat_stat),corr_dist]
150
+
151
+ def privacy_metrics(real_path,fake_path,data_percent=15):
152
+
153
+ real = pd.read_csv(real_path).drop_duplicates(keep=False)
154
+ fake = pd.read_csv(fake_path).drop_duplicates(keep=False)
155
+
156
+ real_refined = real.sample(n=int(len(real)*(.01*data_percent)), random_state=42).to_numpy()
157
+ fake_refined = fake.sample(n=int(len(fake)*(.01*data_percent)), random_state=42).to_numpy()
158
+
159
+ scalerR = StandardScaler()
160
+ scalerR.fit(real_refined)
161
+ scalerF = StandardScaler()
162
+ scalerF.fit(fake_refined)
163
+ df_real_scaled = scalerR.transform(real_refined)
164
+ df_fake_scaled = scalerF.transform(fake_refined)
165
+
166
+ dist_rf = metrics.pairwise_distances(df_real_scaled, Y=df_fake_scaled, metric='minkowski', n_jobs=-1)
167
+ dist_rr = metrics.pairwise_distances(df_real_scaled, Y=None, metric='minkowski', n_jobs=-1)
168
+ rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1)
169
+ dist_ff = metrics.pairwise_distances(df_fake_scaled, Y=None, metric='minkowski', n_jobs=-1)
170
+ rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1)
171
+ smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))]
172
+ smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))]
173
+ smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))]
174
+ smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))]
175
+ smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))]
176
+ smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))]
177
+ nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr])
178
+ nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff])
179
+ nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf])
180
+ nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5)
181
+ nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5)
182
+ nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5)
183
+
184
+ min_dist_rf = np.array([i[0] for i in smallest_two_rf])
185
+ fifth_perc_rf = np.percentile(min_dist_rf,5)
186
+ min_dist_rr = np.array([i[0] for i in smallest_two_rr])
187
+ fifth_perc_rr = np.percentile(min_dist_rr,5)
188
+ min_dist_ff = np.array([i[0] for i in smallest_two_ff])
189
+ fifth_perc_ff = np.percentile(min_dist_ff,5)
190
+
191
+ return np.array([fifth_perc_rf,fifth_perc_rr,fifth_perc_ff,nn_fifth_perc_rf,nn_fifth_perc_rr,nn_fifth_perc_ff]).reshape(1,6)