jialinzhang commited on
Commit
c03b8ec
·
1 Parent(s): 34399c2

Add syntheticFail c16

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/c16/tabddpm/tabddpm-c16-20260510_215505/_tabddpm_train.py +32 -0
  2. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/config.toml +39 -0
  3. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/data/X_cat_train.npy +3 -0
  4. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/data/X_num_train.npy +3 -0
  5. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/data/info.json +42 -0
  6. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/data/y_train.npy +3 -0
  7. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/input_snapshot.json +36 -0
  8. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/normalized_schema_snapshot.json +270 -0
  9. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/public_gate_report.json +37 -0
  10. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/staged_input_manifest.json +275 -0
  11. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/run_config.json +45 -0
  12. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/runtime_result.json +24 -0
  13. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/staged_features.json +67 -0
  14. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/test.csv +3 -0
  15. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/train.csv +3 -0
  16. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/val.csv +3 -0
  17. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/tabddpm/adapter_report.json +7 -0
  18. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/tabddpm/adapter_transforms_applied.json +1 -0
  19. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/tabddpm/model_input_manifest.json +277 -0
  20. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/train_20260510_215505.log +3 -0
  21. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/._data +0 -0
  22. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/.gitignore +22 -0
  23. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/.gitmodules +9 -0
  24. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CONFIG_DESCRIPTION.md +78 -0
  25. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/.gitignore +1 -0
  26. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/README.md +49 -0
  27. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/columns.json +119 -0
  28. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model copy/ctabgan.py +70 -0
  29. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model copy/eval/evaluation.py +193 -0
  30. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model copy/pipeline/data_preparation.py +130 -0
  31. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model copy/privacy_utils/rdp_accountant.py +280 -0
  32. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/ctabgan_synthesizer.py +601 -0
  33. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/transformer.py +429 -0
  34. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py +72 -0
  35. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model/eval/evaluation.py +193 -0
  36. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model/pipeline/data_preparation.py +131 -0
  37. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model/privacy_utils/rdp_accountant.py +280 -0
  38. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/ctabgan_synthesizer.py +605 -0
  39. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/transformer.py +429 -0
  40. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py +81 -0
  41. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py +110 -0
  42. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py +153 -0
  43. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/.gitignore +1 -0
  44. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/LICENSE +201 -0
  45. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/License.txt +15 -0
  46. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/README.md +50 -0
  47. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/columns.json +74 -0
  48. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/model/__init__.py +0 -0
  49. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py +58 -0
  50. syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py +191 -0
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/_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/c16/tabddpm/tabddpm-c16-20260510_215505/config.toml")
23
+ ret = subprocess.run(
24
+ [sys.executable, wrapper, "scripts/pipeline.py",
25
+ "--config", "/work/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/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/c16/tabddpm/tabddpm-c16-20260510_215505/config.toml ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ seed = 0
2
+ parent_dir = "/work/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/output"
3
+ real_data_path = "/work/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/data"
4
+ model_type = "mlp"
5
+ num_numerical_features = 3
6
+ device = "cuda:0"
7
+
8
+ [model_params]
9
+ d_in = 12
10
+ num_classes = 18
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/c16/tabddpm/tabddpm-c16-20260510_215505/data/X_cat_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:643d97a2d0aefc22fb4dad18c0ee20b395aa5eb6996f96dd4dbf81f5908233b2
3
+ size 397280
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/data/X_num_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:92d84bcd604a199c51954f21470cea5ae8161dd3d4c7c9c93bcfcff63a50b515
3
+ size 66320
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/data/info.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "benchmark_dataset",
3
+ "task_type": "multiclass",
4
+ "n_num_features": 3,
5
+ "n_cat_features": 9,
6
+ "train_size": 5516,
7
+ "num_col_idx": [
8
+ 0,
9
+ 1,
10
+ 2
11
+ ],
12
+ "cat_col_idx": [
13
+ 3,
14
+ 4,
15
+ 5,
16
+ 6,
17
+ 7,
18
+ 8,
19
+ 9,
20
+ 10,
21
+ 11
22
+ ],
23
+ "target_col_idx": [
24
+ 12
25
+ ],
26
+ "column_names": [
27
+ "page_id",
28
+ "APPEARANCES",
29
+ "YEAR",
30
+ "name",
31
+ "urlslug",
32
+ "ID",
33
+ "ALIGN",
34
+ "HAIR",
35
+ "SEX",
36
+ "GSM",
37
+ "ALIVE",
38
+ "FIRST APPEARANCE",
39
+ "EYE"
40
+ ],
41
+ "num_classes": 18
42
+ }
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/data/y_train.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:73e575b826bc438fb6b59efa96d6e0511f660fd54b2c9a8266968437df980ed7
3
+ size 44256
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/input_snapshot.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "c16",
3
+ "model": "tabddpm",
4
+ "inputs": {
5
+ "train_csv": {
6
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/c16/c16-train.csv",
7
+ "exists": true,
8
+ "size": 889767,
9
+ "sha256": "d87fe8c15e5364335255aabe0e5ac068dc98c8c772bcbbc52861739ec34e0914"
10
+ },
11
+ "val_csv": {
12
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/c16/c16-val.csv",
13
+ "exists": true,
14
+ "size": 111085,
15
+ "sha256": "149f25d0314c83ff898ddfd9550fd9b048af51daa289673d6bb491653dd89d83"
16
+ },
17
+ "test_csv": {
18
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/c16/c16-test.csv",
19
+ "exists": true,
20
+ "size": 111822,
21
+ "sha256": "bf819d88a0bc2a2659f0a25aacfe0d15ca1b9d59b498ece178817ba81f76d3bf"
22
+ },
23
+ "profile_json": {
24
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/artifacts/data_core/tabular/c16/c16-dataset_profile.json",
25
+ "exists": true,
26
+ "size": 6130,
27
+ "sha256": "a01e7504e986616f132cc5da119064b3fe1a68c4b0475fe60628cdb608071157"
28
+ },
29
+ "contract_json": {
30
+ "path": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/artifacts/data_core/tabular/c16/c16-dataset_contract_v1.json",
31
+ "exists": true,
32
+ "size": 7074,
33
+ "sha256": "773f9641fef4054eef8038ec0bd570c990be631ca4c9748324249d2c92645ba6"
34
+ }
35
+ }
36
+ }
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/normalized_schema_snapshot.json ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "c16",
3
+ "target_column": "EYE",
4
+ "task_type": "classification",
5
+ "columns": [
6
+ {
7
+ "name": "page_id",
8
+ "role": "feature",
9
+ "semantic_type": "numeric",
10
+ "nullable": false,
11
+ "missing_tokens": [],
12
+ "parse_format": null,
13
+ "impute_strategy": "median",
14
+ "profile_stats": {
15
+ "missing_rate": 0.0,
16
+ "unique_count": 5516,
17
+ "unique_ratio": 1.0,
18
+ "example_values": [
19
+ "1941",
20
+ "127435",
21
+ "268584",
22
+ "144619",
23
+ "132754"
24
+ ]
25
+ }
26
+ },
27
+ {
28
+ "name": "name",
29
+ "role": "id",
30
+ "semantic_type": "id",
31
+ "nullable": false,
32
+ "missing_tokens": [],
33
+ "parse_format": null,
34
+ "impute_strategy": "keep_raw",
35
+ "profile_stats": {
36
+ "missing_rate": 0.0,
37
+ "unique_count": 5516,
38
+ "unique_ratio": 1.0,
39
+ "example_values": [
40
+ "Jeremy Tell (New Earth)",
41
+ "Thomas Jarred (New Earth)",
42
+ "Kusanagi (New Earth)",
43
+ "Cecile O'Malley (New Earth)",
44
+ "Rori Stroh (New Earth)"
45
+ ]
46
+ }
47
+ },
48
+ {
49
+ "name": "urlslug",
50
+ "role": "id",
51
+ "semantic_type": "id",
52
+ "nullable": false,
53
+ "missing_tokens": [],
54
+ "parse_format": null,
55
+ "impute_strategy": "keep_raw",
56
+ "profile_stats": {
57
+ "missing_rate": 0.0,
58
+ "unique_count": 5516,
59
+ "unique_ratio": 1.0,
60
+ "example_values": [
61
+ "\\/wiki\\/Jeremy_Tell_(New_Earth)",
62
+ "\\/wiki\\/Thomas_Jarred_(New_Earth)",
63
+ "\\/wiki\\/Kusanagi_(New_Earth)",
64
+ "\\/wiki\\/Cecile_O%27Malley_(New_Earth)",
65
+ "\\/wiki\\/Rori_Stroh_(New_Earth)"
66
+ ]
67
+ }
68
+ },
69
+ {
70
+ "name": "ID",
71
+ "role": "feature",
72
+ "semantic_type": "text",
73
+ "nullable": true,
74
+ "missing_tokens": [],
75
+ "parse_format": null,
76
+ "impute_strategy": "keep_raw",
77
+ "profile_stats": {
78
+ "missing_rate": 0.292422,
79
+ "unique_count": 3,
80
+ "unique_ratio": 0.000769,
81
+ "example_values": [
82
+ "Public Identity",
83
+ "Secret Identity",
84
+ "Identity Unknown"
85
+ ]
86
+ }
87
+ },
88
+ {
89
+ "name": "ALIGN",
90
+ "role": "feature",
91
+ "semantic_type": "text",
92
+ "nullable": true,
93
+ "missing_tokens": [],
94
+ "parse_format": null,
95
+ "impute_strategy": "keep_raw",
96
+ "profile_stats": {
97
+ "missing_rate": 0.087563,
98
+ "unique_count": 4,
99
+ "unique_ratio": 0.000795,
100
+ "example_values": [
101
+ "Bad Characters",
102
+ "Good Characters",
103
+ "Neutral Characters",
104
+ "Reformed Criminals"
105
+ ]
106
+ }
107
+ },
108
+ {
109
+ "name": "EYE",
110
+ "role": "target",
111
+ "semantic_type": "text",
112
+ "nullable": true,
113
+ "missing_tokens": [],
114
+ "parse_format": null,
115
+ "impute_strategy": "keep_raw",
116
+ "profile_stats": {
117
+ "missing_rate": 0.525381,
118
+ "unique_count": 17,
119
+ "unique_ratio": 0.006494,
120
+ "example_values": [
121
+ "Black Eyes",
122
+ "Blue Eyes",
123
+ "Grey Eyes",
124
+ "Green Eyes",
125
+ "Brown Eyes"
126
+ ]
127
+ }
128
+ },
129
+ {
130
+ "name": "HAIR",
131
+ "role": "feature",
132
+ "semantic_type": "text",
133
+ "nullable": true,
134
+ "missing_tokens": [],
135
+ "parse_format": null,
136
+ "impute_strategy": "keep_raw",
137
+ "profile_stats": {
138
+ "missing_rate": 0.3314,
139
+ "unique_count": 17,
140
+ "unique_ratio": 0.00461,
141
+ "example_values": [
142
+ "Brown Hair",
143
+ "Grey Hair",
144
+ "Red Hair",
145
+ "Black Hair",
146
+ "White Hair"
147
+ ]
148
+ }
149
+ },
150
+ {
151
+ "name": "SEX",
152
+ "role": "feature",
153
+ "semantic_type": "text",
154
+ "nullable": true,
155
+ "missing_tokens": [],
156
+ "parse_format": null,
157
+ "impute_strategy": "keep_raw",
158
+ "profile_stats": {
159
+ "missing_rate": 0.018673,
160
+ "unique_count": 4,
161
+ "unique_ratio": 0.000739,
162
+ "example_values": [
163
+ "Male Characters",
164
+ "Female Characters",
165
+ "Genderless Characters",
166
+ "Transgender Characters"
167
+ ]
168
+ }
169
+ },
170
+ {
171
+ "name": "GSM",
172
+ "role": "feature",
173
+ "semantic_type": "text",
174
+ "nullable": true,
175
+ "missing_tokens": [],
176
+ "parse_format": null,
177
+ "impute_strategy": "keep_raw",
178
+ "profile_stats": {
179
+ "missing_rate": 0.990392,
180
+ "unique_count": 2,
181
+ "unique_ratio": 0.037736,
182
+ "example_values": [
183
+ "Homosexual Characters",
184
+ "Bisexual Characters"
185
+ ]
186
+ }
187
+ },
188
+ {
189
+ "name": "ALIVE",
190
+ "role": "feature",
191
+ "semantic_type": "text",
192
+ "nullable": true,
193
+ "missing_tokens": [],
194
+ "parse_format": null,
195
+ "impute_strategy": "keep_raw",
196
+ "profile_stats": {
197
+ "missing_rate": 0.000544,
198
+ "unique_count": 2,
199
+ "unique_ratio": 0.000363,
200
+ "example_values": [
201
+ "Living Characters",
202
+ "Deceased Characters"
203
+ ]
204
+ }
205
+ },
206
+ {
207
+ "name": "APPEARANCES",
208
+ "role": "feature",
209
+ "semantic_type": "numeric",
210
+ "nullable": true,
211
+ "missing_tokens": [],
212
+ "parse_format": null,
213
+ "impute_strategy": "median",
214
+ "profile_stats": {
215
+ "missing_rate": 0.051305,
216
+ "unique_count": 263,
217
+ "unique_ratio": 0.050258,
218
+ "example_values": [
219
+ "14",
220
+ "3",
221
+ "4",
222
+ "7",
223
+ "1"
224
+ ]
225
+ }
226
+ },
227
+ {
228
+ "name": "FIRST APPEARANCE",
229
+ "role": "feature",
230
+ "semantic_type": "datetime",
231
+ "nullable": true,
232
+ "missing_tokens": [],
233
+ "parse_format": "%Y-%m-%d",
234
+ "impute_strategy": "keep_raw",
235
+ "profile_stats": {
236
+ "missing_rate": 0.009608,
237
+ "unique_count": 758,
238
+ "unique_ratio": 0.138752,
239
+ "example_values": [
240
+ "2001, August",
241
+ "1990, February",
242
+ "2008, July",
243
+ "1984, April",
244
+ "1961, December"
245
+ ]
246
+ }
247
+ },
248
+ {
249
+ "name": "YEAR",
250
+ "role": "feature",
251
+ "semantic_type": "numeric",
252
+ "nullable": true,
253
+ "missing_tokens": [],
254
+ "parse_format": null,
255
+ "impute_strategy": "median",
256
+ "profile_stats": {
257
+ "missing_rate": 0.009608,
258
+ "unique_count": 79,
259
+ "unique_ratio": 0.014461,
260
+ "example_values": [
261
+ "2001",
262
+ "1990",
263
+ "2008",
264
+ "1984",
265
+ "1961"
266
+ ]
267
+ }
268
+ }
269
+ ]
270
+ }
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/public_gate_report.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "c16",
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": "EYE",
31
+ "task_type": "classification",
32
+ "input_splits": {
33
+ "train": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/c16/c16-train.csv",
34
+ "val": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/c16/c16-val.csv",
35
+ "test": "/data/jialinzhang/SynthesizePipeline-server/DatasetNew/c16/c16-test.csv"
36
+ }
37
+ }
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/staged_input_manifest.json ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "c16",
3
+ "target_column": "EYE",
4
+ "task_type": "classification",
5
+ "train_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/train.csv",
6
+ "val_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/val.csv",
7
+ "test_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/test.csv",
8
+ "features_json": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/staged_features.json",
9
+ "public_gate_report": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/public_gate_report.json",
10
+ "column_schema": [
11
+ {
12
+ "name": "page_id",
13
+ "role": "feature",
14
+ "semantic_type": "numeric",
15
+ "nullable": false,
16
+ "missing_tokens": [],
17
+ "parse_format": null,
18
+ "impute_strategy": "median",
19
+ "profile_stats": {
20
+ "missing_rate": 0.0,
21
+ "unique_count": 5516,
22
+ "unique_ratio": 1.0,
23
+ "example_values": [
24
+ "1941",
25
+ "127435",
26
+ "268584",
27
+ "144619",
28
+ "132754"
29
+ ]
30
+ }
31
+ },
32
+ {
33
+ "name": "name",
34
+ "role": "id",
35
+ "semantic_type": "id",
36
+ "nullable": false,
37
+ "missing_tokens": [],
38
+ "parse_format": null,
39
+ "impute_strategy": "keep_raw",
40
+ "profile_stats": {
41
+ "missing_rate": 0.0,
42
+ "unique_count": 5516,
43
+ "unique_ratio": 1.0,
44
+ "example_values": [
45
+ "Jeremy Tell (New Earth)",
46
+ "Thomas Jarred (New Earth)",
47
+ "Kusanagi (New Earth)",
48
+ "Cecile O'Malley (New Earth)",
49
+ "Rori Stroh (New Earth)"
50
+ ]
51
+ }
52
+ },
53
+ {
54
+ "name": "urlslug",
55
+ "role": "id",
56
+ "semantic_type": "id",
57
+ "nullable": false,
58
+ "missing_tokens": [],
59
+ "parse_format": null,
60
+ "impute_strategy": "keep_raw",
61
+ "profile_stats": {
62
+ "missing_rate": 0.0,
63
+ "unique_count": 5516,
64
+ "unique_ratio": 1.0,
65
+ "example_values": [
66
+ "\\/wiki\\/Jeremy_Tell_(New_Earth)",
67
+ "\\/wiki\\/Thomas_Jarred_(New_Earth)",
68
+ "\\/wiki\\/Kusanagi_(New_Earth)",
69
+ "\\/wiki\\/Cecile_O%27Malley_(New_Earth)",
70
+ "\\/wiki\\/Rori_Stroh_(New_Earth)"
71
+ ]
72
+ }
73
+ },
74
+ {
75
+ "name": "ID",
76
+ "role": "feature",
77
+ "semantic_type": "text",
78
+ "nullable": true,
79
+ "missing_tokens": [],
80
+ "parse_format": null,
81
+ "impute_strategy": "keep_raw",
82
+ "profile_stats": {
83
+ "missing_rate": 0.292422,
84
+ "unique_count": 3,
85
+ "unique_ratio": 0.000769,
86
+ "example_values": [
87
+ "Public Identity",
88
+ "Secret Identity",
89
+ "Identity Unknown"
90
+ ]
91
+ }
92
+ },
93
+ {
94
+ "name": "ALIGN",
95
+ "role": "feature",
96
+ "semantic_type": "text",
97
+ "nullable": true,
98
+ "missing_tokens": [],
99
+ "parse_format": null,
100
+ "impute_strategy": "keep_raw",
101
+ "profile_stats": {
102
+ "missing_rate": 0.087563,
103
+ "unique_count": 4,
104
+ "unique_ratio": 0.000795,
105
+ "example_values": [
106
+ "Bad Characters",
107
+ "Good Characters",
108
+ "Neutral Characters",
109
+ "Reformed Criminals"
110
+ ]
111
+ }
112
+ },
113
+ {
114
+ "name": "EYE",
115
+ "role": "target",
116
+ "semantic_type": "text",
117
+ "nullable": true,
118
+ "missing_tokens": [],
119
+ "parse_format": null,
120
+ "impute_strategy": "keep_raw",
121
+ "profile_stats": {
122
+ "missing_rate": 0.525381,
123
+ "unique_count": 17,
124
+ "unique_ratio": 0.006494,
125
+ "example_values": [
126
+ "Black Eyes",
127
+ "Blue Eyes",
128
+ "Grey Eyes",
129
+ "Green Eyes",
130
+ "Brown Eyes"
131
+ ]
132
+ }
133
+ },
134
+ {
135
+ "name": "HAIR",
136
+ "role": "feature",
137
+ "semantic_type": "text",
138
+ "nullable": true,
139
+ "missing_tokens": [],
140
+ "parse_format": null,
141
+ "impute_strategy": "keep_raw",
142
+ "profile_stats": {
143
+ "missing_rate": 0.3314,
144
+ "unique_count": 17,
145
+ "unique_ratio": 0.00461,
146
+ "example_values": [
147
+ "Brown Hair",
148
+ "Grey Hair",
149
+ "Red Hair",
150
+ "Black Hair",
151
+ "White Hair"
152
+ ]
153
+ }
154
+ },
155
+ {
156
+ "name": "SEX",
157
+ "role": "feature",
158
+ "semantic_type": "text",
159
+ "nullable": true,
160
+ "missing_tokens": [],
161
+ "parse_format": null,
162
+ "impute_strategy": "keep_raw",
163
+ "profile_stats": {
164
+ "missing_rate": 0.018673,
165
+ "unique_count": 4,
166
+ "unique_ratio": 0.000739,
167
+ "example_values": [
168
+ "Male Characters",
169
+ "Female Characters",
170
+ "Genderless Characters",
171
+ "Transgender Characters"
172
+ ]
173
+ }
174
+ },
175
+ {
176
+ "name": "GSM",
177
+ "role": "feature",
178
+ "semantic_type": "text",
179
+ "nullable": true,
180
+ "missing_tokens": [],
181
+ "parse_format": null,
182
+ "impute_strategy": "keep_raw",
183
+ "profile_stats": {
184
+ "missing_rate": 0.990392,
185
+ "unique_count": 2,
186
+ "unique_ratio": 0.037736,
187
+ "example_values": [
188
+ "Homosexual Characters",
189
+ "Bisexual Characters"
190
+ ]
191
+ }
192
+ },
193
+ {
194
+ "name": "ALIVE",
195
+ "role": "feature",
196
+ "semantic_type": "text",
197
+ "nullable": true,
198
+ "missing_tokens": [],
199
+ "parse_format": null,
200
+ "impute_strategy": "keep_raw",
201
+ "profile_stats": {
202
+ "missing_rate": 0.000544,
203
+ "unique_count": 2,
204
+ "unique_ratio": 0.000363,
205
+ "example_values": [
206
+ "Living Characters",
207
+ "Deceased Characters"
208
+ ]
209
+ }
210
+ },
211
+ {
212
+ "name": "APPEARANCES",
213
+ "role": "feature",
214
+ "semantic_type": "numeric",
215
+ "nullable": true,
216
+ "missing_tokens": [],
217
+ "parse_format": null,
218
+ "impute_strategy": "median",
219
+ "profile_stats": {
220
+ "missing_rate": 0.051305,
221
+ "unique_count": 263,
222
+ "unique_ratio": 0.050258,
223
+ "example_values": [
224
+ "14",
225
+ "3",
226
+ "4",
227
+ "7",
228
+ "1"
229
+ ]
230
+ }
231
+ },
232
+ {
233
+ "name": "FIRST APPEARANCE",
234
+ "role": "feature",
235
+ "semantic_type": "datetime",
236
+ "nullable": true,
237
+ "missing_tokens": [],
238
+ "parse_format": "%Y-%m-%d",
239
+ "impute_strategy": "keep_raw",
240
+ "profile_stats": {
241
+ "missing_rate": 0.009608,
242
+ "unique_count": 758,
243
+ "unique_ratio": 0.138752,
244
+ "example_values": [
245
+ "2001, August",
246
+ "1990, February",
247
+ "2008, July",
248
+ "1984, April",
249
+ "1961, December"
250
+ ]
251
+ }
252
+ },
253
+ {
254
+ "name": "YEAR",
255
+ "role": "feature",
256
+ "semantic_type": "numeric",
257
+ "nullable": true,
258
+ "missing_tokens": [],
259
+ "parse_format": null,
260
+ "impute_strategy": "median",
261
+ "profile_stats": {
262
+ "missing_rate": 0.009608,
263
+ "unique_count": 79,
264
+ "unique_ratio": 0.014461,
265
+ "example_values": [
266
+ "2001",
267
+ "1990",
268
+ "2008",
269
+ "1984",
270
+ "1961"
271
+ ]
272
+ }
273
+ }
274
+ ]
275
+ }
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/run_config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "recorded_at": "2026-05-10T21:55:05",
4
+ "dataset_id": "c16",
5
+ "model": "tabddpm",
6
+ "work_dir": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505",
7
+ "dataset_source_requested": "new",
8
+ "dataset_source_resolved": "new",
9
+ "cli_args": {
10
+ "model": "tabddpm",
11
+ "dataset": "c16",
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": 5516,
25
+ "model_path": null,
26
+ "output_csv": null
27
+ },
28
+ "input_artifacts": {
29
+ "public_gate_report": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/public_gate_report.json",
30
+ "public_manifest": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/staged_input_manifest.json",
31
+ "model_manifest": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/tabddpm/model_input_manifest.json",
32
+ "train_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/train.csv",
33
+ "features_json": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/staged_features.json",
34
+ "target_column": "EYE",
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/c16/tabddpm/tabddpm-c16-20260510_215505/runtime_result.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "c16",
3
+ "model": "tabddpm",
4
+ "run_id": "tabddpm-c16-20260510_215505",
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_55okq9zk/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/c16/tabddpm/tabddpm-c16-20260510_215505/_tabddpm_train.py']' returned non-zero exit status 1.",
11
+ "artifacts": {},
12
+ "timings": {
13
+ "train": {
14
+ "started_at": "2026-05-10T21:55:05",
15
+ "ended_at": "2026-05-10T21:55:06",
16
+ "duration_sec": 0.75
17
+ },
18
+ "generate": {
19
+ "started_at": null,
20
+ "ended_at": null,
21
+ "duration_sec": null
22
+ }
23
+ }
24
+ }
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/staged_features.json ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "feature_name": "page_id",
4
+ "data_type": "continuous",
5
+ "is_target": false
6
+ },
7
+ {
8
+ "feature_name": "name",
9
+ "data_type": "ID",
10
+ "is_target": false
11
+ },
12
+ {
13
+ "feature_name": "urlslug",
14
+ "data_type": "ID",
15
+ "is_target": false
16
+ },
17
+ {
18
+ "feature_name": "ID",
19
+ "data_type": "categorical",
20
+ "is_target": false
21
+ },
22
+ {
23
+ "feature_name": "ALIGN",
24
+ "data_type": "categorical",
25
+ "is_target": false
26
+ },
27
+ {
28
+ "feature_name": "EYE",
29
+ "data_type": "categorical",
30
+ "is_target": true
31
+ },
32
+ {
33
+ "feature_name": "HAIR",
34
+ "data_type": "categorical",
35
+ "is_target": false
36
+ },
37
+ {
38
+ "feature_name": "SEX",
39
+ "data_type": "categorical",
40
+ "is_target": false
41
+ },
42
+ {
43
+ "feature_name": "GSM",
44
+ "data_type": "categorical",
45
+ "is_target": false
46
+ },
47
+ {
48
+ "feature_name": "ALIVE",
49
+ "data_type": "categorical",
50
+ "is_target": false
51
+ },
52
+ {
53
+ "feature_name": "APPEARANCES",
54
+ "data_type": "continuous",
55
+ "is_target": false
56
+ },
57
+ {
58
+ "feature_name": "FIRST APPEARANCE",
59
+ "data_type": "timestamp",
60
+ "is_target": false
61
+ },
62
+ {
63
+ "feature_name": "YEAR",
64
+ "data_type": "continuous",
65
+ "is_target": false
66
+ }
67
+ ]
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/test.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:507d848740a1690656f8cdb841697266450f944c4a567ba0bcf3186a4e58b754
3
+ size 113806
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/train.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:be0950091b8a4c774fc54ff9926cf4e8b86b23efd5ec8e83b5592c72658ae351
3
+ size 905642
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/val.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5a1815f0bdd0db2721a9d7bc2f1f0008829eaf9ff3d07e3d1975b42002cf744
3
+ size 113063
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/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/c16/tabddpm/tabddpm-c16-20260510_215505/staged/tabddpm/model_input_manifest.json"
7
+ }
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/tabddpm/adapter_transforms_applied.json ADDED
@@ -0,0 +1 @@
 
 
1
+ []
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/staged/tabddpm/model_input_manifest.json ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "dataset_id": "c16",
3
+ "model": "tabddpm",
4
+ "target_column": "EYE",
5
+ "task_type": "classification",
6
+ "column_schema": [
7
+ {
8
+ "name": "page_id",
9
+ "role": "feature",
10
+ "semantic_type": "numeric",
11
+ "nullable": false,
12
+ "missing_tokens": [],
13
+ "parse_format": null,
14
+ "impute_strategy": "median",
15
+ "profile_stats": {
16
+ "missing_rate": 0.0,
17
+ "unique_count": 5516,
18
+ "unique_ratio": 1.0,
19
+ "example_values": [
20
+ "1941",
21
+ "127435",
22
+ "268584",
23
+ "144619",
24
+ "132754"
25
+ ]
26
+ }
27
+ },
28
+ {
29
+ "name": "name",
30
+ "role": "id",
31
+ "semantic_type": "id",
32
+ "nullable": false,
33
+ "missing_tokens": [],
34
+ "parse_format": null,
35
+ "impute_strategy": "keep_raw",
36
+ "profile_stats": {
37
+ "missing_rate": 0.0,
38
+ "unique_count": 5516,
39
+ "unique_ratio": 1.0,
40
+ "example_values": [
41
+ "Jeremy Tell (New Earth)",
42
+ "Thomas Jarred (New Earth)",
43
+ "Kusanagi (New Earth)",
44
+ "Cecile O'Malley (New Earth)",
45
+ "Rori Stroh (New Earth)"
46
+ ]
47
+ }
48
+ },
49
+ {
50
+ "name": "urlslug",
51
+ "role": "id",
52
+ "semantic_type": "id",
53
+ "nullable": false,
54
+ "missing_tokens": [],
55
+ "parse_format": null,
56
+ "impute_strategy": "keep_raw",
57
+ "profile_stats": {
58
+ "missing_rate": 0.0,
59
+ "unique_count": 5516,
60
+ "unique_ratio": 1.0,
61
+ "example_values": [
62
+ "\\/wiki\\/Jeremy_Tell_(New_Earth)",
63
+ "\\/wiki\\/Thomas_Jarred_(New_Earth)",
64
+ "\\/wiki\\/Kusanagi_(New_Earth)",
65
+ "\\/wiki\\/Cecile_O%27Malley_(New_Earth)",
66
+ "\\/wiki\\/Rori_Stroh_(New_Earth)"
67
+ ]
68
+ }
69
+ },
70
+ {
71
+ "name": "ID",
72
+ "role": "feature",
73
+ "semantic_type": "text",
74
+ "nullable": true,
75
+ "missing_tokens": [],
76
+ "parse_format": null,
77
+ "impute_strategy": "keep_raw",
78
+ "profile_stats": {
79
+ "missing_rate": 0.292422,
80
+ "unique_count": 3,
81
+ "unique_ratio": 0.000769,
82
+ "example_values": [
83
+ "Public Identity",
84
+ "Secret Identity",
85
+ "Identity Unknown"
86
+ ]
87
+ }
88
+ },
89
+ {
90
+ "name": "ALIGN",
91
+ "role": "feature",
92
+ "semantic_type": "text",
93
+ "nullable": true,
94
+ "missing_tokens": [],
95
+ "parse_format": null,
96
+ "impute_strategy": "keep_raw",
97
+ "profile_stats": {
98
+ "missing_rate": 0.087563,
99
+ "unique_count": 4,
100
+ "unique_ratio": 0.000795,
101
+ "example_values": [
102
+ "Bad Characters",
103
+ "Good Characters",
104
+ "Neutral Characters",
105
+ "Reformed Criminals"
106
+ ]
107
+ }
108
+ },
109
+ {
110
+ "name": "EYE",
111
+ "role": "target",
112
+ "semantic_type": "text",
113
+ "nullable": true,
114
+ "missing_tokens": [],
115
+ "parse_format": null,
116
+ "impute_strategy": "keep_raw",
117
+ "profile_stats": {
118
+ "missing_rate": 0.525381,
119
+ "unique_count": 17,
120
+ "unique_ratio": 0.006494,
121
+ "example_values": [
122
+ "Black Eyes",
123
+ "Blue Eyes",
124
+ "Grey Eyes",
125
+ "Green Eyes",
126
+ "Brown Eyes"
127
+ ]
128
+ }
129
+ },
130
+ {
131
+ "name": "HAIR",
132
+ "role": "feature",
133
+ "semantic_type": "text",
134
+ "nullable": true,
135
+ "missing_tokens": [],
136
+ "parse_format": null,
137
+ "impute_strategy": "keep_raw",
138
+ "profile_stats": {
139
+ "missing_rate": 0.3314,
140
+ "unique_count": 17,
141
+ "unique_ratio": 0.00461,
142
+ "example_values": [
143
+ "Brown Hair",
144
+ "Grey Hair",
145
+ "Red Hair",
146
+ "Black Hair",
147
+ "White Hair"
148
+ ]
149
+ }
150
+ },
151
+ {
152
+ "name": "SEX",
153
+ "role": "feature",
154
+ "semantic_type": "text",
155
+ "nullable": true,
156
+ "missing_tokens": [],
157
+ "parse_format": null,
158
+ "impute_strategy": "keep_raw",
159
+ "profile_stats": {
160
+ "missing_rate": 0.018673,
161
+ "unique_count": 4,
162
+ "unique_ratio": 0.000739,
163
+ "example_values": [
164
+ "Male Characters",
165
+ "Female Characters",
166
+ "Genderless Characters",
167
+ "Transgender Characters"
168
+ ]
169
+ }
170
+ },
171
+ {
172
+ "name": "GSM",
173
+ "role": "feature",
174
+ "semantic_type": "text",
175
+ "nullable": true,
176
+ "missing_tokens": [],
177
+ "parse_format": null,
178
+ "impute_strategy": "keep_raw",
179
+ "profile_stats": {
180
+ "missing_rate": 0.990392,
181
+ "unique_count": 2,
182
+ "unique_ratio": 0.037736,
183
+ "example_values": [
184
+ "Homosexual Characters",
185
+ "Bisexual Characters"
186
+ ]
187
+ }
188
+ },
189
+ {
190
+ "name": "ALIVE",
191
+ "role": "feature",
192
+ "semantic_type": "text",
193
+ "nullable": true,
194
+ "missing_tokens": [],
195
+ "parse_format": null,
196
+ "impute_strategy": "keep_raw",
197
+ "profile_stats": {
198
+ "missing_rate": 0.000544,
199
+ "unique_count": 2,
200
+ "unique_ratio": 0.000363,
201
+ "example_values": [
202
+ "Living Characters",
203
+ "Deceased Characters"
204
+ ]
205
+ }
206
+ },
207
+ {
208
+ "name": "APPEARANCES",
209
+ "role": "feature",
210
+ "semantic_type": "numeric",
211
+ "nullable": true,
212
+ "missing_tokens": [],
213
+ "parse_format": null,
214
+ "impute_strategy": "median",
215
+ "profile_stats": {
216
+ "missing_rate": 0.051305,
217
+ "unique_count": 263,
218
+ "unique_ratio": 0.050258,
219
+ "example_values": [
220
+ "14",
221
+ "3",
222
+ "4",
223
+ "7",
224
+ "1"
225
+ ]
226
+ }
227
+ },
228
+ {
229
+ "name": "FIRST APPEARANCE",
230
+ "role": "feature",
231
+ "semantic_type": "datetime",
232
+ "nullable": true,
233
+ "missing_tokens": [],
234
+ "parse_format": "%Y-%m-%d",
235
+ "impute_strategy": "keep_raw",
236
+ "profile_stats": {
237
+ "missing_rate": 0.009608,
238
+ "unique_count": 758,
239
+ "unique_ratio": 0.138752,
240
+ "example_values": [
241
+ "2001, August",
242
+ "1990, February",
243
+ "2008, July",
244
+ "1984, April",
245
+ "1961, December"
246
+ ]
247
+ }
248
+ },
249
+ {
250
+ "name": "YEAR",
251
+ "role": "feature",
252
+ "semantic_type": "numeric",
253
+ "nullable": true,
254
+ "missing_tokens": [],
255
+ "parse_format": null,
256
+ "impute_strategy": "median",
257
+ "profile_stats": {
258
+ "missing_rate": 0.009608,
259
+ "unique_count": 79,
260
+ "unique_ratio": 0.014461,
261
+ "example_values": [
262
+ "2001",
263
+ "1990",
264
+ "2008",
265
+ "1984",
266
+ "1961"
267
+ ]
268
+ }
269
+ }
270
+ ],
271
+ "public_manifest": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/staged_input_manifest.json",
272
+ "train_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/train.csv",
273
+ "val_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/val.csv",
274
+ "test_csv": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/test.csv",
275
+ "features_json": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/staged/public/staged_features.json",
276
+ "public_gate_report": "/data/jialinzhang/SynthesizePipeline-server/output-Benchmark-trainonly-v1/c16/tabddpm/tabddpm-c16-20260510_215505/public_gate/public_gate_report.json"
277
+ }
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_215505/train_20260510_215505.log ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:eab80524902776080d3e23974baea6b713c4dc17de9afecc5aa6ff29a677e071
3
+ size 577
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/._data ADDED
Binary file (220 Bytes). View file
 
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN-Plus/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ **/**.csv
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ **/**.csv
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_tabddpm_runtime/CTAB-GAN/model/__init__.py ADDED
File without changes
syntheticFail/c16/tabddpm/tabddpm-c16-20260510_223930/_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/c16/tabddpm/tabddpm-c16-20260510_223930/_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)