TabQueryBench commited on
Commit
2d5956c
·
verified ·
1 Parent(s): eb0c332

Resume SynthData0523 main/c6 batch 5

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/transformer.py +429 -0
  3. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py +72 -0
  4. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/eval/evaluation.py +193 -0
  5. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/pipeline/data_preparation.py +131 -0
  6. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/privacy_utils/rdp_accountant.py +280 -0
  7. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/ctabgan_synthesizer.py +605 -0
  8. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/transformer.py +429 -0
  9. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py +81 -0
  10. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py +110 -0
  11. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py +153 -0
  12. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/.gitignore +1 -0
  13. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/LICENSE +201 -0
  14. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/License.txt +15 -0
  15. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/README.md +50 -0
  16. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json +3 -0
  17. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/__init__.py +0 -0
  18. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py +58 -0
  19. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py +191 -0
  20. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/pipeline/data_preparation.py +114 -0
  21. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/ctabgan_synthesizer.py +526 -0
  22. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/transformer.py +363 -0
  23. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/pipeline_ctabgan.py +80 -0
  24. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/requirements.txt +6 -0
  25. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/train_sample_ctabgan.py +108 -0
  26. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/tune_ctabgan.py +150 -0
  27. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.editorconfig +24 -0
  28. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/CODEOWNERS +2 -0
  29. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/bug_report.md +33 -0
  30. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/feature_request.md +24 -0
  31. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/question.md +33 -0
  32. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/integration.yml +31 -0
  33. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/lint.yml +21 -0
  34. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/minimum.yml +31 -0
  35. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/readme.yml +25 -0
  36. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/unit.yml +34 -0
  37. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.gitignore +107 -0
  38. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.travis.yml +15 -0
  39. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/AUTHORS.rst +13 -0
  40. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/CONTRIBUTING.rst +237 -0
  41. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/HISTORY.md +147 -0
  42. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/LICENSE +22 -0
  43. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/MANIFEST.in +11 -0
  44. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/Makefile +240 -0
  45. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/README.md +182 -0
  46. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/README.md +29 -0
  47. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/meta.yaml +51 -0
  48. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__init__.py +17 -0
  49. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__main__.py +102 -0
  50. SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data.py +94 -0
.gitattributes CHANGED
@@ -4774,3 +4774,4 @@ SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/tabular_bundle/pipe
4774
  SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/tabular_bundle/pipeline_ds/y_val.npy filter=lfs diff=lfs merge=lfs -text
4775
  SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/train_20260420_063042.log filter=lfs diff=lfs merge=lfs -text
4776
  SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/columns.json filter=lfs diff=lfs merge=lfs -text
 
 
4774
  SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/tabular_bundle/pipeline_ds/y_val.npy filter=lfs diff=lfs merge=lfs -text
4775
  SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/train_20260420_063042.log filter=lfs diff=lfs merge=lfs -text
4776
  SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/columns.json filter=lfs diff=lfs merge=lfs -text
4777
+ SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json filter=lfs diff=lfs merge=lfs -text
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_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
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_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
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_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)
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_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
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_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
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_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
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_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
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tomli
2
+ import shutil
3
+ import os
4
+ import argparse
5
+ from train_sample_ctabganp import train_ctabgan, sample_ctabgan
6
+ from scripts.eval_catboost import train_catboost
7
+ import zero
8
+ import lib
9
+ from model.ctabgan import CTABGAN
10
+
11
+ def load_config(path) :
12
+ with open(path, 'rb') as f:
13
+ return tomli.load(f)
14
+
15
+ def save_file(parent_dir, config_path):
16
+ try:
17
+ dst = os.path.join(parent_dir)
18
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
19
+ shutil.copyfile(os.path.abspath(config_path), dst)
20
+ except shutil.SameFileError:
21
+ pass
22
+
23
+ def main():
24
+ parser = argparse.ArgumentParser()
25
+ parser.add_argument('--config', metavar='FILE')
26
+ parser.add_argument('--train', action='store_true', default=False)
27
+ parser.add_argument('--sample', action='store_true', default=False)
28
+ parser.add_argument('--eval', action='store_true', default=False)
29
+ parser.add_argument('--change_val', action='store_true', default=False)
30
+
31
+ args = parser.parse_args()
32
+ raw_config = lib.load_config(args.config)
33
+ timer = zero.Timer()
34
+ timer.run()
35
+ save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
36
+ ctabgan = None
37
+ if args.train:
38
+ ctabgan = train_ctabgan(
39
+ parent_dir=raw_config['parent_dir'],
40
+ real_data_path=raw_config['real_data_path'],
41
+ train_params=raw_config['train_params'],
42
+ change_val=args.change_val,
43
+ device=raw_config['device']
44
+ )
45
+ if args.sample:
46
+ sample_ctabgan(
47
+ synthesizer=ctabgan,
48
+ parent_dir=raw_config['parent_dir'],
49
+ real_data_path=raw_config['real_data_path'],
50
+ num_samples=raw_config['sample']['num_samples'],
51
+ train_params=raw_config['train_params'],
52
+ change_val=args.change_val,
53
+ seed=raw_config['sample']['seed'],
54
+ device=raw_config['device']
55
+ )
56
+
57
+ save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
58
+ if args.eval:
59
+ if raw_config['eval']['type']['eval_model'] == 'catboost':
60
+ train_catboost(
61
+ parent_dir=raw_config['parent_dir'],
62
+ real_data_path=raw_config['real_data_path'],
63
+ eval_type=raw_config['eval']['type']['eval_type'],
64
+ T_dict=raw_config['eval']['T'],
65
+ seed=raw_config['seed'],
66
+ change_val=args.change_val
67
+ )
68
+ # elif raw_config['eval']['type']['eval_model'] == 'mlp':
69
+ # train_mlp(
70
+ # parent_dir=raw_config['parent_dir'],
71
+ # real_data_path=raw_config['real_data_path'],
72
+ # eval_type=raw_config['eval']['type']['eval_type'],
73
+ # T_dict=raw_config['eval']['T'],
74
+ # seed=raw_config['seed'],
75
+ # change_val=args.change_val
76
+ # )
77
+
78
+ print(f'Elapsed time: {str(timer)}')
79
+
80
+ if __name__ == '__main__':
81
+ main()
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import lib
2
+ import os
3
+ import numpy as np
4
+ import argparse
5
+ from model.ctabgan import CTABGAN
6
+ from pathlib import Path
7
+ import torch
8
+ import pickle
9
+
10
+
11
+ def train_ctabgan(
12
+ parent_dir,
13
+ real_data_path,
14
+ train_params = {"batch_size": 512},
15
+ change_val=False,
16
+ device = "cpu"
17
+ ):
18
+ real_data_path = Path(real_data_path)
19
+ parent_dir = Path(parent_dir)
20
+ device = torch.device(device)
21
+
22
+ if change_val:
23
+ X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
24
+ else:
25
+ X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
26
+
27
+ X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
28
+
29
+ X.columns = [str(_) for _ in X.columns]
30
+
31
+ ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name]
32
+ train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
33
+
34
+ print(train_params)
35
+ synthesizer = CTABGAN(
36
+ df = X,
37
+ test_ratio = 0.0,
38
+ **ctabgan_params,
39
+ **train_params,
40
+ device=device
41
+ )
42
+
43
+ synthesizer.fit()
44
+
45
+ # save_ctabgan(synthesizer, parent_dir)
46
+ with open(parent_dir / "ctabgan.obj", "wb") as f:
47
+ pickle.dump(synthesizer, f)
48
+
49
+ return synthesizer
50
+
51
+ def sample_ctabgan(
52
+ synthesizer,
53
+ parent_dir,
54
+ real_data_path,
55
+ num_samples,
56
+ train_params = {"batch_size": 512},
57
+ change_val=False,
58
+ device="cpu",
59
+ seed=0
60
+ ):
61
+ real_data_path = Path(real_data_path)
62
+ parent_dir = Path(parent_dir)
63
+ device = torch.device(device)
64
+
65
+ if change_val:
66
+ X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
67
+ else:
68
+ X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
69
+
70
+ X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
71
+
72
+ X.columns = [str(_) for _ in X.columns]
73
+
74
+ ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name]
75
+
76
+ cat_features = ctabgan_params["categorical_columns"]
77
+ # if synthesizer is None:
78
+ # synthesizer = load_ctabgan(X, ctabgan_params, train_params, parent_dir)
79
+ with open(parent_dir / "ctabgan.obj", 'rb') as f:
80
+ synthesizer = pickle.load(f)
81
+ synthesizer.synthesizer.generator = synthesizer.synthesizer.generator.to(device)
82
+ gen_data = synthesizer.generate_samples(num_samples, seed)
83
+
84
+ y = gen_data['y'].values
85
+ if len(np.unique(y)) == 1:
86
+ y[0] = 0
87
+ y[1] = 1
88
+
89
+ X_cat = gen_data[cat_features].drop('y', axis=1, errors="ignore").values if len(cat_features) else None
90
+ X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
91
+
92
+ if X_num_train is not None:
93
+ np.save(parent_dir / 'X_num_train', X_num.astype(float))
94
+ if X_cat_train is not None:
95
+ np.save(parent_dir / 'X_cat_train', X_cat.astype(str))
96
+ np.save(parent_dir / 'y_train', y.astype(float).astype(int)) # only clf !!!
97
+
98
+ def main():
99
+ parser = argparse.ArgumentParser()
100
+ parser.add_argument('real_data_path', type=str)
101
+ parser.add_argument('parent_dir', type=str)
102
+ parser.add_argument('train_size', type=int)
103
+ args = parser.parse_args()
104
+
105
+ ctabgan = train_ctabgan(args.parent_dir, args.real_data_path, change_val=True)
106
+ sample_ctabgan(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
107
+
108
+
109
+ if __name__ == '__main__':
110
+ main()
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from multiprocessing.sharedctypes import RawValue
2
+ from random import random
3
+ import tempfile
4
+ import subprocess
5
+ import lib
6
+ import os
7
+ import optuna
8
+ import argparse
9
+ from pathlib import Path
10
+ from train_sample_ctabganp import train_ctabgan, sample_ctabgan
11
+ from scripts.eval_catboost import train_catboost
12
+
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument('data_path', type=str)
15
+ parser.add_argument('train_size', type=int)
16
+ parser.add_argument('eval_type', type=str)
17
+ parser.add_argument('device', type=str)
18
+
19
+ args = parser.parse_args()
20
+ real_data_path = args.data_path
21
+ eval_type = args.eval_type
22
+ train_size = args.train_size
23
+ device = args.device
24
+ assert eval_type in ('merged', 'synthetic')
25
+
26
+ def objective(trial):
27
+
28
+ lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
29
+
30
+ def suggest_dim(name):
31
+ t = trial.suggest_int(name, d_min, d_max)
32
+ return 2 ** t
33
+
34
+ # construct model
35
+ min_n_layers, max_n_layers, d_min, d_max = 1, 4, 6, 8
36
+ n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers)
37
+ d_first = [suggest_dim('d_first')] if n_layers else []
38
+ d_middle = (
39
+ [suggest_dim('d_middle')] * (n_layers - 2)
40
+ if n_layers > 2
41
+ else []
42
+ )
43
+ d_last = [suggest_dim('d_last')] if n_layers > 1 else []
44
+ d_layers = d_first + d_middle + d_last
45
+ ####
46
+
47
+ steps = trial.suggest_categorical('steps', [1000, 5000, 10000])
48
+ # steps = trial.suggest_categorical('steps', [10])
49
+ batch_size = 2 ** trial.suggest_int('batch_size', 9, 11)
50
+ random_dim = 2 ** trial.suggest_int('random_dim', 4, 7)
51
+ num_channels = 2 ** trial.suggest_int('num_channels', 4, 6)
52
+
53
+ # steps = trial.suggest_categorical('steps', [1000])
54
+
55
+ num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3)))
56
+
57
+ train_params = {
58
+ "lr": lr,
59
+ "epochs": steps,
60
+ "class_dim": d_layers,
61
+ "batch_size": batch_size,
62
+ "random_dim": random_dim,
63
+ "num_channels": num_channels
64
+ }
65
+ trial.set_user_attr("train_params", train_params)
66
+ trial.set_user_attr("num_samples", num_samples)
67
+
68
+ score = 0.0
69
+ with tempfile.TemporaryDirectory() as dir_:
70
+ dir_ = Path(dir_)
71
+ ctabgan = train_ctabgan(
72
+ parent_dir=dir_,
73
+ real_data_path=real_data_path,
74
+ train_params=train_params,
75
+ change_val=True,
76
+ device=device
77
+ )
78
+
79
+ for sample_seed in range(5):
80
+ sample_ctabgan(
81
+ ctabgan,
82
+ parent_dir=dir_,
83
+ real_data_path=real_data_path,
84
+ num_samples=num_samples,
85
+ train_params=train_params,
86
+ change_val=True,
87
+ seed=sample_seed,
88
+ device=device
89
+ )
90
+
91
+ T_dict = {
92
+ "seed": 0,
93
+ "normalization": None,
94
+ "num_nan_policy": None,
95
+ "cat_nan_policy": None,
96
+ "cat_min_frequency": None,
97
+ "cat_encoding": None,
98
+ "y_policy": "default"
99
+ }
100
+ metrics = train_catboost(
101
+ parent_dir=dir_,
102
+ real_data_path=real_data_path,
103
+ eval_type=eval_type,
104
+ T_dict=T_dict,
105
+ change_val=True,
106
+ seed = 0
107
+ )
108
+
109
+ score += metrics.get_val_score()
110
+ return score / 5
111
+
112
+
113
+ study = optuna.create_study(
114
+ direction='maximize',
115
+ sampler=optuna.samplers.TPESampler(seed=0),
116
+ )
117
+
118
+ study.optimize(objective, n_trials=35, show_progress_bar=True)
119
+
120
+ os.makedirs(f"exp/{Path(real_data_path).name}/ctabgan-plus/", exist_ok=True)
121
+ config = {
122
+ "parent_dir": f"exp/{Path(real_data_path).name}/ctabgan-plus/",
123
+ "real_data_path": real_data_path,
124
+ "seed": 0,
125
+ "device": args.device,
126
+ "train_params": study.best_trial.user_attrs["train_params"],
127
+ "sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]},
128
+ "eval": {
129
+ "type": {"eval_model": "catboost", "eval_type": eval_type},
130
+ "T": {
131
+ "seed": 0,
132
+ "normalization": None,
133
+ "num_nan_policy": None,
134
+ "cat_nan_policy": None,
135
+ "cat_min_frequency": None,
136
+ "cat_encoding": None,
137
+ "y_policy": "default"
138
+ },
139
+ }
140
+ }
141
+
142
+ train_ctabgan(
143
+ parent_dir=f"exp/{Path(real_data_path).name}/ctabgan-plus/",
144
+ real_data_path=real_data_path,
145
+ train_params=study.best_trial.user_attrs["train_params"],
146
+ change_val=False,
147
+ device=device
148
+ )
149
+
150
+ lib.dump_config(config, config["parent_dir"]+"config.toml")
151
+
152
+ subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}',
153
+ '10', "ctabgan-plus", eval_type, "catboost", "5"], check=True)
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ **/**.csv
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/License.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Distributed learning systems Lab at TU Delft & Generatrix, hereby disclaims all copyright interest in the program "CTAB-GAN" (which synthesizes tabular data)
2
+
3
+ Copyright 2020-2022 Distributed learning systems Lab at TU Delft & Generatrix.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ https://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/README.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # CTAB-GAN
2
+ This is the official git paper [CTAB-GAN: Effective Table Data Synthesizing](https://proceedings.mlr.press/v157/zhao21a.html). The paper is published on Asian Conference on Machine Learning (ACML 2021), please check our pdf on PMLR website for our newest version of [paper](https://proceedings.mlr.press/v157/zhao21a.html), it adds more content on time consumption analysis of training CTAB-GAN. If you have any question, please contact `z.zhao-8@tudelft.nl` for more information.
3
+
4
+
5
+ ## Prerequisite
6
+
7
+ The required package version
8
+ ```
9
+ numpy==1.21.0
10
+ torch==1.9.1
11
+ pandas==1.2.4
12
+ sklearn==0.24.1
13
+ dython==0.6.4.post1
14
+ scipy==1.4.1
15
+ ```
16
+
17
+ ## Example
18
+ `Experiment_Script_Adult.ipynb` is an example notebook for training CTAB-GAN with Adult dataset. The dataset is alread under `Real_Datasets` folder.
19
+ The evaluation code is also provided.
20
+
21
+ ## For large dataset
22
+
23
+ If your dataset has large number of column, you may encounter the problem that our currnet code cannot encode all of your data since CTAB-GAN will wrap the encoded data into an image-like format. What you can do is changing the line 341 and 348 in `model/synthesizer/ctabgan_synthesizer.py`. The number in the `slide` list
24
+ ```
25
+ sides = [4, 8, 16, 24, 32]
26
+ ```
27
+ is the side size of image. You can enlarge the list to [4, 8, 16, 24, 32, 64] or [4, 8, 16, 24, 32, 64, 128] for accepting larger dataset.
28
+
29
+ ## Bibtex
30
+
31
+ To cite this paper, you could use this bibtex
32
+
33
+ ```
34
+ @InProceedings{zhao21,
35
+ title = {CTAB-GAN: Effective Table Data Synthesizing},
36
+ author = {Zhao, Zilong and Kunar, Aditya and Birke, Robert and Chen, Lydia Y.},
37
+ booktitle = {Proceedings of The 13th Asian Conference on Machine Learning},
38
+ pages = {97--112},
39
+ year = {2021},
40
+ editor = {Balasubramanian, Vineeth N. and Tsang, Ivor},
41
+ volume = {157},
42
+ series = {Proceedings of Machine Learning Research},
43
+ month = {17--19 Nov},
44
+ publisher = {PMLR},
45
+ pdf = {https://proceedings.mlr.press/v157/zhao21a/zhao21a.pdf},
46
+ url = {https://proceedings.mlr.press/v157/zhao21a.html}
47
+ }
48
+
49
+
50
+ ```
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c59fb02cb7f4a153aecb9e18dd81bbbb6946e55c3e6928c748811fcf5a85ad79
3
+ size 3179
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/__init__.py ADDED
File without changes
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_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
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_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)
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/pipeline/data_preparation.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, 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.integer_columns = integer
15
+ self.column_types = dict()
16
+ self.column_types["categorical"] = []
17
+ self.column_types["mixed"] = {}
18
+ self.lower_bounds = {}
19
+ self.label_encoder_list = []
20
+
21
+
22
+ target_col = list(type.values())[0]
23
+ y_real = raw_df[target_col]
24
+ X_real = raw_df.drop(columns=[target_col])
25
+ # 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)
26
+ X_train_real, y_train_real = X_real, y_real
27
+ X_train_real[target_col]= y_train_real
28
+
29
+ self.df = X_train_real
30
+
31
+ self.df = self.df.replace(r' ', np.nan)
32
+ self.df = self.df.fillna('empty')
33
+
34
+ all_columns= set(self.df.columns)
35
+ irrelevant_missing_columns = set(self.categorical_columns)
36
+ relevant_missing_columns = list(all_columns - irrelevant_missing_columns)
37
+
38
+ for i in relevant_missing_columns:
39
+ if i in self.log_columns:
40
+ if "empty" in list(self.df[i].values):
41
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x)
42
+ self.mixed_columns[i] = [-9999999]
43
+ elif i in list(self.mixed_columns.keys()):
44
+ if "empty" in list(self.df[i].values):
45
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x )
46
+ self.mixed_columns[i].append(-9999999)
47
+ else:
48
+ if "empty" in list(self.df[i].values):
49
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x)
50
+ self.mixed_columns[i] = [-9999999]
51
+
52
+ if self.log_columns:
53
+ for log_column in self.log_columns:
54
+ valid_indices = []
55
+ for idx,val in enumerate(self.df[log_column].values):
56
+ if val!=-9999999:
57
+ valid_indices.append(idx)
58
+ eps = 1
59
+ lower = np.min(self.df[log_column].iloc[valid_indices].values)
60
+ self.lower_bounds[log_column] = lower
61
+ if lower>0:
62
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x) if x!=-9999999 else -9999999)
63
+ elif lower == 0:
64
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x+eps) if x!=-9999999 else -9999999)
65
+ else:
66
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x-lower+eps) if x!=-9999999 else -9999999)
67
+
68
+ for column_index, column in enumerate(self.df.columns):
69
+ if column in self.categorical_columns:
70
+ label_encoder = preprocessing.LabelEncoder()
71
+ self.df[column] = self.df[column].astype(str)
72
+ label_encoder.fit(self.df[column])
73
+ current_label_encoder = dict()
74
+ current_label_encoder['column'] = column
75
+ current_label_encoder['label_encoder'] = label_encoder
76
+ transformed_column = label_encoder.transform(self.df[column])
77
+ self.df[column] = transformed_column
78
+ self.label_encoder_list.append(current_label_encoder)
79
+ self.column_types["categorical"].append(column_index)
80
+
81
+ elif column in self.mixed_columns:
82
+ self.column_types["mixed"][column_index] = self.mixed_columns[column]
83
+
84
+ super().__init__()
85
+
86
+ def inverse_prep(self, data, eps=1):
87
+
88
+ df_sample = pd.DataFrame(data,columns=self.df.columns)
89
+
90
+ for i in range(len(self.label_encoder_list)):
91
+ le = self.label_encoder_list[i]["label_encoder"]
92
+ df_sample[self.label_encoder_list[i]["column"]] = df_sample[self.label_encoder_list[i]["column"]].astype(int)
93
+ df_sample[self.label_encoder_list[i]["column"]] = le.inverse_transform(df_sample[self.label_encoder_list[i]["column"]])
94
+
95
+ if self.log_columns:
96
+ for i in df_sample:
97
+ if i in self.log_columns:
98
+ lower_bound = self.lower_bounds[i]
99
+ if lower_bound>0:
100
+ df_sample[i].apply(lambda x: np.exp(x))
101
+ elif lower_bound==0:
102
+ 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))
103
+ else:
104
+ df_sample[i] = df_sample[i].apply(lambda x: np.exp(x)-eps+lower_bound)
105
+
106
+ if self.integer_columns:
107
+ for column in self.integer_columns:
108
+ df_sample[column]= (np.round(df_sample[column].values))
109
+ df_sample[column] = df_sample[column].astype(int)
110
+
111
+ df_sample.replace(-9999999, np.nan,inplace=True)
112
+ df_sample.replace('empty', np.nan,inplace=True)
113
+
114
+ return df_sample
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/ctabgan_synthesizer.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, BatchNorm2d, Sigmoid, init, BCELoss, CrossEntropyLoss,SmoothL1Loss)
10
+ from model.synthesizer.transformer import ImageTransformer,DataTransformer
11
+ from tqdm import tqdm
12
+
13
+
14
+ class Classifier(Module):
15
+ def __init__(self,input_dim, dis_dims,st_ed):
16
+ super(Classifier,self).__init__()
17
+ dim = input_dim-(st_ed[1]-st_ed[0])
18
+ seq = []
19
+ self.str_end = st_ed
20
+ for item in list(dis_dims):
21
+ seq += [
22
+ Linear(dim, item),
23
+ LeakyReLU(0.2),
24
+ Dropout(0.5)
25
+ ]
26
+ dim = item
27
+
28
+ if (st_ed[1]-st_ed[0])==1:
29
+ seq += [Linear(dim, 1)]
30
+
31
+ elif (st_ed[1]-st_ed[0])==2:
32
+ seq += [Linear(dim, 1),Sigmoid()]
33
+ else:
34
+ seq += [Linear(dim,(st_ed[1]-st_ed[0]))]
35
+
36
+ self.seq = Sequential(*seq)
37
+
38
+ def forward(self, input):
39
+
40
+ label=None
41
+
42
+ if (self.str_end[1]-self.str_end[0])==1:
43
+ label = input[:, self.str_end[0]:self.str_end[1]]
44
+ else:
45
+ label = torch.argmax(input[:, self.str_end[0]:self.str_end[1]], axis=-1)
46
+
47
+ new_imp = torch.cat((input[:,:self.str_end[0]],input[:,self.str_end[1]:]),1)
48
+
49
+ if ((self.str_end[1]-self.str_end[0])==2) | ((self.str_end[1]-self.str_end[0])==1):
50
+ return self.seq(new_imp).view(-1), label
51
+ else:
52
+ return self.seq(new_imp), label
53
+
54
+ def apply_activate(data, output_info):
55
+ data_t = []
56
+ st = 0
57
+ for item in output_info:
58
+ if item[1] == 'tanh':
59
+ ed = st + item[0]
60
+ data_t.append(torch.tanh(data[:, st:ed]))
61
+ st = ed
62
+ elif item[1] == 'softmax':
63
+ ed = st + item[0]
64
+ data_t.append(F.gumbel_softmax(data[:, st:ed], tau=0.2))
65
+ st = ed
66
+ return torch.cat(data_t, dim=1)
67
+
68
+ def get_st_ed(target_col_index,output_info):
69
+ st = 0
70
+ c= 0
71
+ tc= 0
72
+ for item in output_info:
73
+ if c==target_col_index:
74
+ break
75
+ if item[1]=='tanh':
76
+ st += item[0]
77
+ elif item[1] == 'softmax':
78
+ st += item[0]
79
+ c+=1
80
+ tc+=1
81
+ ed= st+output_info[tc][0]
82
+ return (st,ed)
83
+
84
+ def random_choice_prob_index_sampling(probs,col_idx):
85
+ option_list = []
86
+ for i in col_idx:
87
+ pp = probs[i]
88
+ option_list.append(np.random.choice(np.arange(len(probs[i])), p=pp))
89
+
90
+ return np.array(option_list).reshape(col_idx.shape)
91
+
92
+ def random_choice_prob_index(a, axis=1):
93
+ r = np.expand_dims(np.random.rand(a.shape[1 - axis]), axis=axis)
94
+ return (a.cumsum(axis=axis) > r).argmax(axis=axis)
95
+
96
+ def maximum_interval(output_info):
97
+ max_interval = 0
98
+ for item in output_info:
99
+ max_interval = max(max_interval, item[0])
100
+ return max_interval
101
+
102
+ class Cond(object):
103
+ def __init__(self, data, output_info):
104
+
105
+ self.model = []
106
+ st = 0
107
+ counter = 0
108
+ for item in output_info:
109
+
110
+ if item[1] == 'tanh':
111
+ st += item[0]
112
+ continue
113
+ elif item[1] == 'softmax':
114
+ ed = st + item[0]
115
+ counter += 1
116
+ self.model.append(np.argmax(data[:, st:ed], axis=-1))
117
+ st = ed
118
+
119
+ self.interval = []
120
+ self.n_col = 0
121
+ self.n_opt = 0
122
+ st = 0
123
+ self.p = np.zeros((counter, maximum_interval(output_info)))
124
+ self.p_sampling = []
125
+ for item in output_info:
126
+ if item[1] == 'tanh':
127
+ st += item[0]
128
+ continue
129
+ elif item[1] == 'softmax':
130
+ ed = st + item[0]
131
+ tmp = np.sum(data[:, st:ed], axis=0)
132
+ tmp_sampling = np.sum(data[:, st:ed], axis=0)
133
+ tmp = np.log(tmp + 1)
134
+ tmp = tmp / np.sum(tmp)
135
+ tmp_sampling = tmp_sampling / np.sum(tmp_sampling)
136
+ self.p_sampling.append(tmp_sampling)
137
+ self.p[self.n_col, :item[0]] = tmp
138
+ self.interval.append((self.n_opt, item[0]))
139
+ self.n_opt += item[0]
140
+ self.n_col += 1
141
+ st = ed
142
+
143
+ self.interval = np.asarray(self.interval)
144
+
145
+ def sample_train(self, batch):
146
+ if self.n_col == 0:
147
+ return None
148
+ batch = batch
149
+
150
+ idx = np.random.choice(np.arange(self.n_col), batch)
151
+
152
+ vec = np.zeros((batch, self.n_opt), dtype='float32')
153
+ mask = np.zeros((batch, self.n_col), dtype='float32')
154
+ mask[np.arange(batch), idx] = 1
155
+ opt1prime = random_choice_prob_index(self.p[idx])
156
+ for i in np.arange(batch):
157
+ vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1
158
+
159
+ return vec, mask, idx, opt1prime
160
+
161
+ def sample(self, batch):
162
+ if self.n_col == 0:
163
+ return None
164
+ batch = batch
165
+
166
+ idx = np.random.choice(np.arange(self.n_col), batch)
167
+
168
+ vec = np.zeros((batch, self.n_opt), dtype='float32')
169
+ opt1prime = random_choice_prob_index_sampling(self.p_sampling,idx)
170
+
171
+ for i in np.arange(batch):
172
+ vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1
173
+
174
+ return vec
175
+
176
+ def cond_loss(data, output_info, c, m):
177
+ loss = []
178
+ st = 0
179
+ st_c = 0
180
+ for item in output_info:
181
+ if item[1] == 'tanh':
182
+ st += item[0]
183
+ continue
184
+
185
+ elif item[1] == 'softmax':
186
+ ed = st + item[0]
187
+ ed_c = st_c + item[0]
188
+ tmp = F.cross_entropy(
189
+ data[:, st:ed],
190
+ torch.argmax(c[:, st_c:ed_c], dim=1),
191
+ reduction='none')
192
+ loss.append(tmp)
193
+ st = ed
194
+ st_c = ed_c
195
+
196
+ loss = torch.stack(loss, dim=1)
197
+ return (loss * m).sum() / data.size()[0]
198
+
199
+ class Sampler(object):
200
+ def __init__(self, data, output_info):
201
+ super(Sampler, self).__init__()
202
+ self.data = data
203
+ self.model = []
204
+ self.n = len(data)
205
+ st = 0
206
+ for item in output_info:
207
+ if item[1] == 'tanh':
208
+ st += item[0]
209
+ continue
210
+ elif item[1] == 'softmax':
211
+ ed = st + item[0]
212
+ tmp = []
213
+ for j in range(item[0]):
214
+ tmp.append(np.nonzero(data[:, st + j])[0])
215
+ self.model.append(tmp)
216
+ st = ed
217
+
218
+ def sample(self, n, col, opt):
219
+ if col is None:
220
+ idx = np.random.choice(np.arange(self.n), n)
221
+ return self.data[idx]
222
+ idx = []
223
+ for c, o in zip(col, opt):
224
+ idx.append(np.random.choice(self.model[c][o]))
225
+ return self.data[idx]
226
+
227
+ class Discriminator(Module):
228
+ def __init__(self, side, layers):
229
+ super(Discriminator, self).__init__()
230
+ self.side = side
231
+ info = len(layers)-2
232
+ self.seq = Sequential(*layers)
233
+ self.seq_info = Sequential(*layers[:info])
234
+
235
+ def forward(self, input):
236
+ return (self.seq(input)), self.seq_info(input)
237
+
238
+ class Generator(Module):
239
+ def __init__(self, side, layers):
240
+ super(Generator, self).__init__()
241
+ self.side = side
242
+ self.seq = Sequential(*layers)
243
+
244
+ def forward(self, input_):
245
+ return self.seq(input_)
246
+
247
+ def determine_layers_disc(side, num_channels):
248
+ assert side >= 4 and side <= 32
249
+
250
+ layer_dims = [(1, side), (num_channels, side // 2)]
251
+
252
+ while layer_dims[-1][1] > 3 and len(layer_dims) < 4:
253
+ layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2))
254
+
255
+ layers_D = []
256
+ for prev, curr in zip(layer_dims, layer_dims[1:]):
257
+ layers_D += [
258
+ Conv2d(prev[0], curr[0], 4, 2, 1, bias=False),
259
+ BatchNorm2d(curr[0]),
260
+ LeakyReLU(0.2, inplace=True)
261
+ ]
262
+ print()
263
+ layers_D += [
264
+
265
+ Conv2d(layer_dims[-1][0], 1, layer_dims[-1][1], 1, 0),
266
+ Sigmoid()
267
+ ]
268
+
269
+ return layers_D
270
+
271
+ def determine_layers_gen(side, random_dim, num_channels):
272
+ assert side >= 4 and side <= 32
273
+
274
+ layer_dims = [(1, side), (num_channels, side // 2)]
275
+
276
+ while layer_dims[-1][1] > 3 and len(layer_dims) < 4:
277
+ layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2))
278
+
279
+ layers_G = [
280
+ ConvTranspose2d(
281
+ random_dim, layer_dims[-1][0], layer_dims[-1][1], 1, 0, output_padding=0, bias=False)
282
+ ]
283
+
284
+ for prev, curr in zip(reversed(layer_dims), reversed(layer_dims[:-1])):
285
+ layers_G += [
286
+ BatchNorm2d(prev[0]),
287
+ ReLU(True),
288
+ ConvTranspose2d(prev[0], curr[0], 4, 2, 1, output_padding=0, bias=True)
289
+ ]
290
+ return layers_G
291
+
292
+
293
+ def weights_init(m):
294
+ classname = m.__class__.__name__
295
+
296
+ if classname.find('Conv') != -1:
297
+ init.normal_(m.weight.data, 0.0, 0.02)
298
+
299
+ elif classname.find('BatchNorm') != -1:
300
+ init.normal_(m.weight.data, 1.0, 0.02)
301
+ init.constant_(m.bias.data, 0)
302
+
303
+ class CTABGANSynthesizer:
304
+ def __init__(self,
305
+ lr=2e-4,
306
+ class_dim=(256, 256, 256, 256),
307
+ random_dim=128,
308
+ num_channels=64,
309
+ l2scale=1e-5,
310
+ batch_size=1024,
311
+ epochs=1,
312
+ device=torch.device("cpu")):
313
+
314
+
315
+ self.random_dim = random_dim
316
+ self.class_dim = class_dim
317
+ self.num_channels = num_channels
318
+ self.dside = None
319
+ self.gside = None
320
+ self.l2scale = l2scale
321
+ self.lr = lr
322
+ self.batch_size = batch_size
323
+ self.epochs = epochs
324
+ self.device = device
325
+
326
+ def fit(self, train_data=pd.DataFrame, categorical=[], mixed={}, type={}, no_train=False):
327
+ print("Fit started.")
328
+ problem_type = None
329
+ target_index=None
330
+ if type:
331
+ problem_type = list(type.keys())[0]
332
+ if problem_type:
333
+ target_index = train_data.columns.get_loc(type[problem_type])
334
+
335
+ self.transformer = DataTransformer(train_data=train_data, categorical_list=categorical, mixed_dict=mixed)
336
+ self.transformer.fit()
337
+
338
+ train_data = self.transformer.transform(train_data.values)
339
+
340
+ data_sampler = Sampler(train_data, self.transformer.output_info)
341
+ data_dim = self.transformer.output_dim
342
+ self.cond_generator = Cond(train_data, self.transformer.output_info)
343
+
344
+ sides = [4, 8, 16, 24, 32]
345
+ col_size_d = data_dim + self.cond_generator.n_opt
346
+ for i in sides:
347
+ if i * i >= col_size_d:
348
+ self.dside = i
349
+ break
350
+
351
+ sides = [4, 8, 16, 24, 32]
352
+ col_size_g = data_dim
353
+ for i in sides:
354
+ if i * i >= col_size_g:
355
+ self.gside = i
356
+ break
357
+
358
+ layers_G = determine_layers_gen(self.gside, self.random_dim+self.cond_generator.n_opt, self.num_channels)
359
+ layers_D = determine_layers_disc(self.dside, self.num_channels)
360
+
361
+ self.generator = Generator(self.gside, layers_G).to(self.device)
362
+ discriminator = Discriminator(self.dside, layers_D).to(self.device)
363
+ optimizer_params = dict(lr=self.lr, betas=(0.5, 0.9), eps=1e-3, weight_decay=self.l2scale)
364
+ optimizerG = Adam(self.generator.parameters(), **optimizer_params)
365
+ optimizerD = Adam(discriminator.parameters(), **optimizer_params)
366
+
367
+ st_ed = None
368
+ classifier=None
369
+ optimizerC= None
370
+ if target_index != None:
371
+ st_ed= get_st_ed(target_index,self.transformer.output_info)
372
+ classifier = Classifier(data_dim,self.class_dim,st_ed).to(self.device)
373
+ optimizerC = optim.Adam(classifier.parameters(),**optimizer_params)
374
+
375
+
376
+ self.generator.apply(weights_init)
377
+ discriminator.apply(weights_init)
378
+
379
+ self.Gtransformer = ImageTransformer(self.gside)
380
+ self.Dtransformer = ImageTransformer(self.dside)
381
+
382
+
383
+ if no_train: return
384
+
385
+ print("Training started.")
386
+ for i in range(self.epochs):
387
+ # for _ in range(steps_per_epoch):
388
+
389
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
390
+ condvec = self.cond_generator.sample_train(self.batch_size)
391
+
392
+ c, m, col, opt = condvec
393
+ c = torch.from_numpy(c).to(self.device)
394
+ m = torch.from_numpy(m).to(self.device)
395
+ noisez = torch.cat([noisez, c], dim=1)
396
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
397
+
398
+ perm = np.arange(self.batch_size)
399
+ np.random.shuffle(perm)
400
+ real = data_sampler.sample(self.batch_size, col[perm], opt[perm])
401
+ c_perm = c[perm]
402
+
403
+ real = torch.from_numpy(real.astype('float32')).to(self.device)
404
+
405
+ fake = self.generator(noisez)
406
+ faket = self.Gtransformer.inverse_transform(fake)
407
+ fakeact = apply_activate(faket, self.transformer.output_info)
408
+
409
+ fake_cat = torch.cat([fakeact, c], dim=1)
410
+ real_cat = torch.cat([real, c_perm], dim=1)
411
+
412
+ real_cat_d = self.Dtransformer.transform(real_cat)
413
+ fake_cat_d = self.Dtransformer.transform(fake_cat)
414
+
415
+ optimizerD.zero_grad()
416
+ y_real,_ = discriminator(real_cat_d)
417
+ y_fake,_ = discriminator(fake_cat_d)
418
+ loss_d = (-(torch.log(y_real + 1e-4).mean()) - (torch.log(1. - y_fake + 1e-4).mean()))
419
+ loss_d.backward()
420
+ optimizerD.step()
421
+
422
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
423
+
424
+ condvec = self.cond_generator.sample_train(self.batch_size)
425
+
426
+ c, m, col, opt = condvec
427
+ c = torch.from_numpy(c).to(self.device)
428
+ m = torch.from_numpy(m).to(self.device)
429
+ noisez = torch.cat([noisez, c], dim=1)
430
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
431
+
432
+ optimizerG.zero_grad()
433
+
434
+ fake = self.generator(noisez)
435
+ faket = self.Gtransformer.inverse_transform(fake)
436
+ fakeact = apply_activate(faket, self.transformer.output_info)
437
+
438
+ fake_cat = torch.cat([fakeact, c], dim=1)
439
+ fake_cat = self.Dtransformer.transform(fake_cat)
440
+
441
+ y_fake,info_fake = discriminator(fake_cat)
442
+
443
+ cross_entropy = cond_loss(faket, self.transformer.output_info, c, m)
444
+
445
+ _,info_real = discriminator(real_cat_d)
446
+
447
+ g = -(torch.log(y_fake + 1e-4).mean()) + cross_entropy
448
+ g.backward(retain_graph=True)
449
+ 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)
450
+ 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)
451
+ loss_info = loss_mean + loss_std
452
+ loss_info.backward()
453
+ optimizerG.step()
454
+
455
+ if (i + 1) % 500 == 0:
456
+ print(f"Step: {i}/{self.epochs} Loss: {loss_mean:.4f}")
457
+
458
+ if problem_type:
459
+
460
+ fake = self.generator(noisez)
461
+
462
+ faket = self.Gtransformer.inverse_transform(fake)
463
+
464
+ fakeact = apply_activate(faket, self.transformer.output_info)
465
+
466
+ real_pre, real_label = classifier(real)
467
+ fake_pre, fake_label = classifier(fakeact)
468
+
469
+ c_loss = CrossEntropyLoss()
470
+
471
+ if (st_ed[1] - st_ed[0])==1:
472
+ c_loss= SmoothL1Loss()
473
+ real_label = real_label.type_as(real_pre)
474
+ fake_label = fake_label.type_as(fake_pre)
475
+ real_label = torch.reshape(real_label,real_pre.size())
476
+ fake_label = torch.reshape(fake_label,fake_pre.size())
477
+
478
+
479
+ elif (st_ed[1] - st_ed[0])==2:
480
+ c_loss = BCELoss()
481
+ real_label = real_label.type_as(real_pre)
482
+ fake_label = fake_label.type_as(fake_pre)
483
+
484
+ loss_cc = c_loss(real_pre, real_label)
485
+ loss_cg = c_loss(fake_pre, fake_label)
486
+
487
+ optimizerG.zero_grad()
488
+ loss_cg.backward()
489
+ optimizerG.step()
490
+
491
+ optimizerC.zero_grad()
492
+ loss_cc.backward()
493
+ optimizerC.step()
494
+
495
+ @torch.no_grad()
496
+ def sample(self, n, seed=0):
497
+
498
+ torch.manual_seed(seed)
499
+ torch.cuda.manual_seed(seed)
500
+ sample_batch_size = 8092
501
+ self.generator.eval()
502
+
503
+ output_info = self.transformer.output_info
504
+ steps = n // sample_batch_size + 1
505
+
506
+ data = []
507
+
508
+ for i in range(steps):
509
+ noisez = torch.randn(sample_batch_size, self.random_dim, device=self.device)
510
+ condvec = self.cond_generator.sample(sample_batch_size)
511
+ c = condvec
512
+ c = torch.from_numpy(c).to(self.device)
513
+ noisez = torch.cat([noisez, c], dim=1)
514
+ noisez = noisez.view(sample_batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
515
+
516
+ fake = self.generator(noisez)
517
+ faket = self.Gtransformer.inverse_transform(fake)
518
+ fakeact = apply_activate(faket,output_info)
519
+ # print(len(data))
520
+ data.append(fakeact.detach().cpu().numpy())
521
+
522
+ data = np.concatenate(data, axis=0)
523
+ result = self.transformer.inverse_transform(data)
524
+
525
+ return result[0:n]
526
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/transformer.py ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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={}, 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
+
16
+ def get_metadata(self):
17
+
18
+ meta = []
19
+
20
+ for index in range(self.train_data.shape[1]):
21
+ column = self.train_data.iloc[:,index]
22
+ if index in self.categorical_columns:
23
+ mapper = column.value_counts().index.tolist()
24
+ meta.append({
25
+ "name": index,
26
+ "type": "categorical",
27
+ "size": len(mapper),
28
+ "i2s": mapper
29
+ })
30
+ elif index in self.mixed_columns.keys():
31
+ meta.append({
32
+ "name": index,
33
+ "type": "mixed",
34
+ "min": column.min(),
35
+ "max": column.max(),
36
+ "modal": self.mixed_columns[index]
37
+ })
38
+ else:
39
+ meta.append({
40
+ "name": index,
41
+ "type": "continuous",
42
+ "min": column.min(),
43
+ "max": column.max(),
44
+ })
45
+
46
+ return meta
47
+
48
+ def fit(self):
49
+ data = self.train_data.values
50
+ self.meta = self.get_metadata()
51
+ model = []
52
+ self.ordering = []
53
+ self.output_info = []
54
+ self.output_dim = 0
55
+ self.components = []
56
+ self.filter_arr = []
57
+ for id_, info in enumerate(self.meta):
58
+ if info['type'] == "continuous":
59
+ gm = BayesianGaussianMixture(n_components=self.n_clusters,
60
+ weight_concentration_prior_type='dirichlet_process',
61
+ weight_concentration_prior=0.001,
62
+ max_iter=100,n_init=1, random_state=42)
63
+ gm.fit(data[:, id_].reshape([-1, 1]))
64
+ mode_freq = (pd.Series(gm.predict(data[:, id_].reshape([-1, 1]))).value_counts().keys())
65
+ model.append(gm)
66
+ old_comp = gm.weights_ > self.eps
67
+ comp = []
68
+ for i in range(self.n_clusters):
69
+ if (i in (mode_freq)) & old_comp[i]:
70
+ comp.append(True)
71
+ else:
72
+ comp.append(False)
73
+ self.components.append(comp)
74
+ self.output_info += [(1, 'tanh'), (np.sum(comp), 'softmax')]
75
+ self.output_dim += 1 + np.sum(comp)
76
+
77
+ elif info['type'] == "mixed":
78
+
79
+ gm1 = BayesianGaussianMixture(n_components=self.n_clusters,
80
+ weight_concentration_prior_type='dirichlet_process',
81
+ weight_concentration_prior=0.001, max_iter=100,
82
+ n_init=1,random_state=42)
83
+ gm2 = BayesianGaussianMixture(n_components=self.n_clusters,
84
+ weight_concentration_prior_type='dirichlet_process',
85
+ weight_concentration_prior=0.001, max_iter=100,
86
+ n_init=1,random_state=42)
87
+
88
+ gm1.fit(data[:, id_].reshape([-1, 1]))
89
+
90
+ filter_arr = []
91
+ for element in data[:, id_]:
92
+ if element not in info['modal']:
93
+ filter_arr.append(True)
94
+ else:
95
+ filter_arr.append(False)
96
+
97
+ gm2.fit(data[:, id_][filter_arr].reshape([-1, 1]))
98
+ mode_freq = (pd.Series(gm2.predict(data[:, id_][filter_arr].reshape([-1, 1]))).value_counts().keys())
99
+ self.filter_arr.append(filter_arr)
100
+ model.append((gm1,gm2))
101
+
102
+ old_comp = gm2.weights_ > self.eps
103
+
104
+ comp = []
105
+
106
+ for i in range(self.n_clusters):
107
+ if (i in (mode_freq)) & old_comp[i]:
108
+ comp.append(True)
109
+ else:
110
+ comp.append(False)
111
+
112
+ self.components.append(comp)
113
+
114
+ self.output_info += [(1, 'tanh'), (np.sum(comp) + len(info['modal']), 'softmax')]
115
+ self.output_dim += 1 + np.sum(comp) + len(info['modal'])
116
+
117
+ else:
118
+ model.append(None)
119
+ self.components.append(None)
120
+ self.output_info += [(info['size'], 'softmax')]
121
+ self.output_dim += info['size']
122
+
123
+ self.model = model
124
+
125
+ def transform(self, data, ispositive = False, positive_list = None):
126
+ values = []
127
+ mixed_counter = 0
128
+ for id_, info in enumerate(self.meta):
129
+ current = data[:, id_]
130
+ if info['type'] == "continuous":
131
+ current = current.reshape([-1, 1])
132
+ means = self.model[id_].means_.reshape((1, self.n_clusters))
133
+ stds = np.sqrt(self.model[id_].covariances_).reshape((1, self.n_clusters))
134
+ features = np.empty(shape=(len(current),self.n_clusters))
135
+ if ispositive == True:
136
+ if id_ in positive_list:
137
+ features = np.abs(current - means) / (4 * stds)
138
+ else:
139
+ features = (current - means) / (4 * stds)
140
+
141
+ probs = self.model[id_].predict_proba(current.reshape([-1, 1]))
142
+ n_opts = sum(self.components[id_])
143
+ features = features[:, self.components[id_]]
144
+ probs = probs[:, self.components[id_]]
145
+
146
+ opt_sel = np.zeros(len(data), dtype='int')
147
+ for i in range(len(data)):
148
+ pp = probs[i] + 1e-6
149
+ pp = pp / sum(pp)
150
+ opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp)
151
+
152
+ idx = np.arange((len(features)))
153
+ features = features[idx, opt_sel].reshape([-1, 1])
154
+ features = np.clip(features, -.99, .99)
155
+ probs_onehot = np.zeros_like(probs)
156
+ probs_onehot[np.arange(len(probs)), opt_sel] = 1
157
+
158
+ re_ordered_phot = np.zeros_like(probs_onehot)
159
+
160
+ col_sums = probs_onehot.sum(axis=0)
161
+
162
+
163
+ n = probs_onehot.shape[1]
164
+ largest_indices = np.argsort(-1*col_sums)[:n]
165
+ self.ordering.append(largest_indices)
166
+ for id,val in enumerate(largest_indices):
167
+ re_ordered_phot[:,id] = probs_onehot[:,val]
168
+
169
+
170
+ values += [features, re_ordered_phot]
171
+
172
+ elif info['type'] == "mixed":
173
+
174
+ means_0 = self.model[id_][0].means_.reshape([-1])
175
+ stds_0 = np.sqrt(self.model[id_][0].covariances_).reshape([-1])
176
+
177
+ zero_std_list = []
178
+ means_needed = []
179
+ stds_needed = []
180
+
181
+ for mode in info['modal']:
182
+ if mode!=-9999999:
183
+ dist = []
184
+ for idx,val in enumerate(list(means_0.flatten())):
185
+ dist.append(abs(mode-val))
186
+ index_min = np.argmin(np.array(dist))
187
+ zero_std_list.append(index_min)
188
+ else: continue
189
+
190
+ for idx in zero_std_list:
191
+ means_needed.append(means_0[idx])
192
+ stds_needed.append(stds_0[idx])
193
+
194
+
195
+ mode_vals = []
196
+
197
+ for i,j,k in zip(info['modal'],means_needed,stds_needed):
198
+ this_val = np.abs(i - j) / (4*k)
199
+ mode_vals.append(this_val)
200
+
201
+ if -9999999 in info["modal"]:
202
+ mode_vals.append(0)
203
+
204
+ current = current.reshape([-1, 1])
205
+ filter_arr = self.filter_arr[mixed_counter]
206
+ current = current[filter_arr]
207
+
208
+ means = self.model[id_][1].means_.reshape((1, self.n_clusters))
209
+ stds = np.sqrt(self.model[id_][1].covariances_).reshape((1, self.n_clusters))
210
+ features = np.empty(shape=(len(current),self.n_clusters))
211
+ if ispositive == True:
212
+ if id_ in positive_list:
213
+ features = np.abs(current - means) / (4 * stds)
214
+ else:
215
+ features = (current - means) / (4 * stds)
216
+
217
+ probs = self.model[id_][1].predict_proba(current.reshape([-1, 1]))
218
+
219
+ n_opts = sum(self.components[id_]) # 8
220
+ features = features[:, self.components[id_]]
221
+ probs = probs[:, self.components[id_]]
222
+
223
+ opt_sel = np.zeros(len(current), dtype='int')
224
+ for i in range(len(current)):
225
+ pp = probs[i] + 1e-6
226
+ pp = pp / sum(pp)
227
+ opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp)
228
+ idx = np.arange((len(features)))
229
+ features = features[idx, opt_sel].reshape([-1, 1])
230
+ features = np.clip(features, -.99, .99)
231
+ probs_onehot = np.zeros_like(probs)
232
+ probs_onehot[np.arange(len(probs)), opt_sel] = 1
233
+ extra_bits = np.zeros([len(current), len(info['modal'])])
234
+ temp_probs_onehot = np.concatenate([extra_bits,probs_onehot], axis = 1)
235
+ final = np.zeros([len(data), 1 + probs_onehot.shape[1] + len(info['modal'])])
236
+ features_curser = 0
237
+ for idx, val in enumerate(data[:, id_]):
238
+ if val in info['modal']:
239
+ category_ = list(map(info['modal'].index, [val]))[0]
240
+ final[idx, 0] = mode_vals[category_]
241
+ final[idx, (category_+1)] = 1
242
+
243
+ else:
244
+ final[idx, 0] = features[features_curser]
245
+ final[idx, (1+len(info['modal'])):] = temp_probs_onehot[features_curser][len(info['modal']):]
246
+ features_curser = features_curser + 1
247
+
248
+ just_onehot = final[:,1:]
249
+ re_ordered_jhot= np.zeros_like(just_onehot)
250
+ n = just_onehot.shape[1]
251
+ col_sums = just_onehot.sum(axis=0)
252
+ largest_indices = np.argsort(-1*col_sums)[:n]
253
+ self.ordering.append(largest_indices)
254
+ for id,val in enumerate(largest_indices):
255
+ re_ordered_jhot[:,id] = just_onehot[:,val]
256
+ final_features = final[:,0].reshape([-1, 1])
257
+ values += [final_features, re_ordered_jhot]
258
+ mixed_counter = mixed_counter + 1
259
+
260
+ else:
261
+ self.ordering.append(None)
262
+ col_t = np.zeros([len(data), info['size']])
263
+ idx = list(map(info['i2s'].index, current))
264
+ col_t[np.arange(len(data)), idx] = 1
265
+ values.append(col_t)
266
+
267
+ return np.concatenate(values, axis=1)
268
+
269
+ def inverse_transform(self, data):
270
+ data_t = np.zeros([len(data), len(self.meta)])
271
+ st = 0
272
+ for id_, info in enumerate(self.meta):
273
+ if info['type'] == "continuous":
274
+ u = data[:, st]
275
+ v = data[:, st + 1:st + 1 + np.sum(self.components[id_])]
276
+ order = self.ordering[id_]
277
+ v_re_ordered = np.zeros_like(v)
278
+
279
+ for id,val in enumerate(order):
280
+ v_re_ordered[:,val] = v[:,id]
281
+
282
+ v = v_re_ordered
283
+
284
+ u = np.clip(u, -1, 1)
285
+ v_t = np.ones((data.shape[0], self.n_clusters)) * -100
286
+ v_t[:, self.components[id_]] = v
287
+ v = v_t
288
+ st += 1 + np.sum(self.components[id_])
289
+ means = self.model[id_].means_.reshape([-1])
290
+ stds = np.sqrt(self.model[id_].covariances_).reshape([-1])
291
+ p_argmax = np.argmax(v, axis=1)
292
+ std_t = stds[p_argmax]
293
+ mean_t = means[p_argmax]
294
+ tmp = u * 4 * std_t + mean_t
295
+ data_t[:, id_] = tmp
296
+
297
+ elif info['type'] == "mixed":
298
+
299
+ u = data[:, st]
300
+ full_v = data[:,(st+1):(st+1)+len(info['modal'])+np.sum(self.components[id_])]
301
+ order = self.ordering[id_]
302
+ full_v_re_ordered = np.zeros_like(full_v)
303
+
304
+ for id,val in enumerate(order):
305
+ full_v_re_ordered[:,val] = full_v[:,id]
306
+
307
+ full_v = full_v_re_ordered
308
+ mixed_v = full_v[:,:len(info['modal'])]
309
+ v = full_v[:,-np.sum(self.components[id_]):]
310
+
311
+ u = np.clip(u, -1, 1)
312
+ v_t = np.ones((data.shape[0], self.n_clusters)) * -100
313
+ v_t[:, self.components[id_]] = v
314
+ v = np.concatenate([mixed_v,v_t], axis=1)
315
+
316
+ st += 1 + np.sum(self.components[id_]) + len(info['modal'])
317
+ means = self.model[id_][1].means_.reshape([-1])
318
+ stds = np.sqrt(self.model[id_][1].covariances_).reshape([-1])
319
+ p_argmax = np.argmax(v, axis=1)
320
+
321
+ result = np.zeros_like(u)
322
+
323
+ for idx in range(len(data)):
324
+ if p_argmax[idx] < len(info['modal']):
325
+ argmax_value = p_argmax[idx]
326
+ result[idx] = float(list(map(info['modal'].__getitem__, [argmax_value]))[0])
327
+ else:
328
+ std_t = stds[(p_argmax[idx]-len(info['modal']))]
329
+ mean_t = means[(p_argmax[idx]-len(info['modal']))]
330
+ result[idx] = u[idx] * 4 * std_t + mean_t
331
+
332
+ data_t[:, id_] = result
333
+
334
+ else:
335
+ current = data[:, st:st + info['size']]
336
+ st += info['size']
337
+ idx = np.argmax(current, axis=1)
338
+ data_t[:, id_] = list(map(info['i2s'].__getitem__, idx))
339
+
340
+ return data_t
341
+
342
+ class ImageTransformer():
343
+
344
+ def __init__(self, side):
345
+
346
+ self.height = side
347
+
348
+ def transform(self, data):
349
+
350
+ if self.height * self.height > len(data[0]):
351
+
352
+ padding = torch.zeros((len(data), self.height * self.height - len(data[0]))).to(data.device)
353
+ data = torch.cat([data, padding], axis=1)
354
+
355
+ return data.view(-1, 1, self.height, self.height)
356
+
357
+ def inverse_transform(self, data):
358
+
359
+ data = data.view(-1, self.height * self.height)
360
+
361
+ return data
362
+
363
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/pipeline_ctabgan.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tomli
2
+ import shutil
3
+ import os
4
+ import argparse
5
+ from train_sample_ctabgan import train_ctabgan, sample_ctabgan
6
+ from scripts.eval_catboost import train_catboost
7
+ import zero
8
+ import lib
9
+
10
+ def load_config(path) :
11
+ with open(path, 'rb') as f:
12
+ return tomli.load(f)
13
+
14
+ def save_file(parent_dir, config_path):
15
+ try:
16
+ dst = os.path.join(parent_dir)
17
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
18
+ shutil.copyfile(os.path.abspath(config_path), dst)
19
+ except shutil.SameFileError:
20
+ pass
21
+
22
+ def main():
23
+ parser = argparse.ArgumentParser()
24
+ parser.add_argument('--config', metavar='FILE')
25
+ parser.add_argument('--train', action='store_true', default=False)
26
+ parser.add_argument('--sample', action='store_true', default=False)
27
+ parser.add_argument('--eval', action='store_true', default=False)
28
+ parser.add_argument('--change_val', action='store_true', default=False)
29
+
30
+ args = parser.parse_args()
31
+ raw_config = lib.load_config(args.config)
32
+ timer = zero.Timer()
33
+ timer.run()
34
+ save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
35
+ ctabgan = None
36
+ if args.train:
37
+ ctabgan = train_ctabgan(
38
+ parent_dir=raw_config['parent_dir'],
39
+ real_data_path=raw_config['real_data_path'],
40
+ train_params=raw_config['train_params'],
41
+ change_val=args.change_val,
42
+ device=raw_config['device']
43
+ )
44
+ if args.sample:
45
+ sample_ctabgan(
46
+ synthesizer=ctabgan,
47
+ parent_dir=raw_config['parent_dir'],
48
+ real_data_path=raw_config['real_data_path'],
49
+ num_samples=raw_config['sample']['num_samples'],
50
+ train_params=raw_config['train_params'],
51
+ change_val=args.change_val,
52
+ seed=raw_config['sample']['seed'],
53
+ device=raw_config['device']
54
+ )
55
+
56
+ save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
57
+ if args.eval:
58
+ if raw_config['eval']['type']['eval_model'] == 'catboost':
59
+ train_catboost(
60
+ parent_dir=raw_config['parent_dir'],
61
+ real_data_path=raw_config['real_data_path'],
62
+ eval_type=raw_config['eval']['type']['eval_type'],
63
+ T_dict=raw_config['eval']['T'],
64
+ seed=raw_config['seed'],
65
+ change_val=args.change_val
66
+ )
67
+ # elif raw_config['eval']['type']['eval_model'] == 'mlp':
68
+ # train_mlp(
69
+ # parent_dir=raw_config['parent_dir'],
70
+ # real_data_path=raw_config['real_data_path'],
71
+ # eval_type=raw_config['eval']['type']['eval_type'],
72
+ # T_dict=raw_config['eval']['T'],
73
+ # seed=raw_config['seed'],
74
+ # change_val=args.change_val
75
+ # )
76
+
77
+ print(f'Elapsed time: {str(timer)}')
78
+
79
+ if __name__ == '__main__':
80
+ main()
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ numpy==1.21.0
2
+ torch==1.9.1
3
+ pandas==1.2.4
4
+ sklearn==0.24.1
5
+ dython==0.6.4.post1
6
+ scipy==1.4.1
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/train_sample_ctabgan.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import lib
2
+ import os
3
+ import numpy as np
4
+ import argparse
5
+ from pathlib import Path
6
+ from model.ctabgan import CTABGAN
7
+ import torch
8
+ import pickle
9
+
10
+ def train_ctabgan(
11
+ parent_dir,
12
+ real_data_path,
13
+ train_params = {"batch_size": 512},
14
+ change_val=False,
15
+ device = "cpu"
16
+ ):
17
+ real_data_path = Path(real_data_path)
18
+ parent_dir = Path(parent_dir)
19
+ device = torch.device(device)
20
+
21
+ if change_val:
22
+ X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
23
+ else:
24
+ X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
25
+
26
+ X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
27
+
28
+ X.columns = [str(_) for _ in X.columns]
29
+
30
+ ctabgan_params = lib.load_json("CTAB-GAN/columns.json")[real_data_path.name]
31
+ train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
32
+
33
+ print(train_params)
34
+ synthesizer = CTABGAN(
35
+ df = X,
36
+ test_ratio = 0.0,
37
+ **ctabgan_params,
38
+ **train_params,
39
+ device=device
40
+ )
41
+
42
+ synthesizer.fit()
43
+
44
+ # save_ctabgan(synthesizer, parent_dir)
45
+ with open(parent_dir / "ctabgan.obj", "wb") as f:
46
+ pickle.dump(synthesizer, f)
47
+
48
+ return synthesizer
49
+
50
+ def sample_ctabgan(
51
+ synthesizer,
52
+ parent_dir,
53
+ real_data_path,
54
+ num_samples,
55
+ train_params = {"batch_size": 512},
56
+ change_val=False,
57
+ device="cpu",
58
+ seed=0
59
+ ):
60
+ real_data_path = Path(real_data_path)
61
+ parent_dir = Path(parent_dir)
62
+ device = torch.device(device)
63
+
64
+ if change_val:
65
+ X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
66
+ else:
67
+ X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
68
+
69
+ X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
70
+
71
+ X.columns = [str(_) for _ in X.columns]
72
+
73
+ ctabgan_params = lib.load_json("CTAB-GAN/columns.json")[real_data_path.name]
74
+
75
+ cat_features = ctabgan_params["categorical_columns"]
76
+ # if synthesizer is None:
77
+ # synthesizer = load_ctabgan(X, ctabgan_params, train_params, parent_dir)
78
+ with open(parent_dir / "ctabgan.obj", 'rb') as f:
79
+ synthesizer = pickle.load(f)
80
+ synthesizer.synthesizer.generator = synthesizer.synthesizer.generator.to(device)
81
+ gen_data = synthesizer.generate_samples(num_samples, seed)
82
+
83
+ y = gen_data['y'].values
84
+ if len(np.unique(y)) == 1:
85
+ y[0] = 1
86
+
87
+ X_cat = gen_data[cat_features].drop('y', axis=1).values if len(cat_features) else None
88
+ X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
89
+
90
+ if X_num_train is not None:
91
+ np.save(parent_dir / 'X_num_train', X_num.astype(float))
92
+ if X_cat_train is not None:
93
+ np.save(parent_dir / 'X_cat_train', X_cat.astype(str))
94
+ np.save(parent_dir / 'y_train', y.astype(float).astype(int)) # only clf !!!
95
+
96
+ def main():
97
+ parser = argparse.ArgumentParser()
98
+ parser.add_argument('real_data_path', type=str)
99
+ parser.add_argument('parent_dir', type=str)
100
+ parser.add_argument('train_size', type=int)
101
+ args = parser.parse_args()
102
+
103
+ ctabgan = train_ctabgan(args.parent_dir, args.real_data_path, change_val=True)
104
+ sample_ctabgan(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
105
+
106
+
107
+ if __name__ == '__main__':
108
+ main()
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/tune_ctabgan.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from multiprocessing.sharedctypes import RawValue
2
+ import tempfile
3
+ import subprocess
4
+ import lib
5
+ import os
6
+ import optuna
7
+ import argparse
8
+ from pathlib import Path
9
+ from train_sample_ctabgan import train_ctabgan, sample_ctabgan
10
+ from scripts.eval_catboost import train_catboost
11
+
12
+ parser = argparse.ArgumentParser()
13
+ parser.add_argument('data_path', type=str)
14
+ parser.add_argument('train_size', type=int)
15
+ parser.add_argument('eval_type', type=str)
16
+ parser.add_argument('device', type=str)
17
+
18
+ args = parser.parse_args()
19
+ real_data_path = args.data_path
20
+ eval_type = args.eval_type
21
+ train_size = args.train_size
22
+ device = args.device
23
+ assert eval_type in ('merged', 'synthetic')
24
+
25
+ def objective(trial):
26
+
27
+ lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
28
+
29
+ def suggest_dim(name):
30
+ t = trial.suggest_int(name, d_min, d_max)
31
+ return 2 ** t
32
+
33
+ # construct model
34
+ min_n_layers, max_n_layers, d_min, d_max = 1, 4, 6, 8
35
+ n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers)
36
+ d_first = [suggest_dim('d_first')] if n_layers else []
37
+ d_middle = (
38
+ [suggest_dim('d_middle')] * (n_layers - 2)
39
+ if n_layers > 2
40
+ else []
41
+ )
42
+ d_last = [suggest_dim('d_last')] if n_layers > 1 else []
43
+ d_layers = d_first + d_middle + d_last
44
+ ####
45
+
46
+ steps = trial.suggest_categorical('steps', [1000, 5000, 10000])
47
+ # steps = trial.suggest_categorical('steps', [10])
48
+ batch_size = 2 ** trial.suggest_int('batch_size', 9, 11)
49
+ random_dim = 2 ** trial.suggest_int('random_dim', 4, 7)
50
+ num_channels = 2 ** trial.suggest_int('num_channels', 4, 6)
51
+
52
+ num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3)))
53
+
54
+ train_params = {
55
+ "lr": lr,
56
+ "epochs": steps,
57
+ "class_dim": d_layers,
58
+ "batch_size": batch_size,
59
+ "random_dim": random_dim,
60
+ "num_channels": num_channels
61
+ }
62
+ trial.set_user_attr("train_params", train_params)
63
+ trial.set_user_attr("num_samples", num_samples)
64
+
65
+ score = 0.0
66
+ with tempfile.TemporaryDirectory() as dir_:
67
+ dir_ = Path(dir_)
68
+ ctabgan = train_ctabgan(
69
+ parent_dir=dir_,
70
+ real_data_path=real_data_path,
71
+ train_params=train_params,
72
+ change_val=True,
73
+ device=device
74
+ )
75
+
76
+ for sample_seed in range(5):
77
+ sample_ctabgan(
78
+ ctabgan,
79
+ parent_dir=dir_,
80
+ real_data_path=real_data_path,
81
+ num_samples=num_samples,
82
+ train_params=train_params,
83
+ change_val=True,
84
+ seed=sample_seed,
85
+ device=device
86
+ )
87
+
88
+ T_dict = {
89
+ "seed": 0,
90
+ "normalization": None,
91
+ "num_nan_policy": None,
92
+ "cat_nan_policy": None,
93
+ "cat_min_frequency": None,
94
+ "cat_encoding": None,
95
+ "y_policy": "default"
96
+ }
97
+ metrics = train_catboost(
98
+ parent_dir=dir_,
99
+ real_data_path=real_data_path,
100
+ eval_type=eval_type,
101
+ T_dict=T_dict,
102
+ change_val=True,
103
+ seed = 0
104
+ )
105
+
106
+ score += metrics.get_val_score()
107
+ return score / 5
108
+
109
+
110
+ study = optuna.create_study(
111
+ direction='maximize',
112
+ sampler=optuna.samplers.TPESampler(seed=0),
113
+ )
114
+
115
+ study.optimize(objective, n_trials=35, show_progress_bar=True)
116
+
117
+ os.makedirs(f"exp/{Path(real_data_path).name}/ctabgan/", exist_ok=True)
118
+ config = {
119
+ "parent_dir": f"exp/{Path(real_data_path).name}/ctabgan/",
120
+ "real_data_path": real_data_path,
121
+ "seed": 0,
122
+ "device": args.device,
123
+ "train_params": study.best_trial.user_attrs["train_params"],
124
+ "sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]},
125
+ "eval": {
126
+ "type": {"eval_model": "catboost", "eval_type": eval_type},
127
+ "T": {
128
+ "seed": 0,
129
+ "normalization": None,
130
+ "num_nan_policy": None,
131
+ "cat_nan_policy": None,
132
+ "cat_min_frequency": None,
133
+ "cat_encoding": None,
134
+ "y_policy": "default"
135
+ },
136
+ }
137
+ }
138
+
139
+ train_ctabgan(
140
+ parent_dir=f"exp/{Path(real_data_path).name}/ctabgan/",
141
+ real_data_path=real_data_path,
142
+ train_params=study.best_trial.user_attrs["train_params"],
143
+ change_val=False,
144
+ device=device
145
+ )
146
+
147
+ lib.dump_config(config, config["parent_dir"]+"config.toml")
148
+
149
+ subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}',
150
+ '10', "ctabgan", eval_type, "catboost", "5"], check=True)
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.editorconfig ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # http://editorconfig.org
2
+
3
+ root = true
4
+
5
+ [*]
6
+ indent_style = space
7
+ indent_size = 4
8
+ trim_trailing_whitespace = true
9
+ insert_final_newline = true
10
+ charset = utf-8
11
+ end_of_line = lf
12
+
13
+ [*.py]
14
+ max_line_length = 99
15
+
16
+ [*.bat]
17
+ indent_style = tab
18
+ end_of_line = crlf
19
+
20
+ [LICENSE]
21
+ insert_final_newline = false
22
+
23
+ [Makefile]
24
+ indent_style = tab
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/CODEOWNERS ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Global rule:
2
+ * @sdv-dev/core-contributors
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/bug_report.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Bug report
3
+ about: Report an error that you found when using CTGAN
4
+ title: ''
5
+ labels: bug, pending review
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ ### Environment Details
11
+
12
+ Please indicate the following details about the environment in which you found the bug:
13
+
14
+ * CTGAN version:
15
+ * Python version:
16
+ * Operating System:
17
+
18
+ ### Error Description
19
+
20
+ <!--Replace this text with a description of what you were trying to get done.
21
+ Tell us what happened, what went wrong, and what you expected to happen.-->
22
+
23
+ ### Steps to reproduce
24
+
25
+ <!--Replace this text with a description of the steps that anyone can follow to
26
+ reproduce the error. If the error happens only on a specific dataset, please
27
+ consider attaching some example data to the issue so that others can use it
28
+ to reproduce the error.-->
29
+
30
+ ```
31
+ Paste the command(s) you ran and the output.
32
+ If there was a crash, please include the traceback here.
33
+ ```
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/feature_request.md ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature request
3
+ about: Request a new feature that you would like to see implemented in CTGAN
4
+ title: ''
5
+ labels: new feature, pending review
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ ### Problem Description
11
+
12
+ <!--Replace this with a description of the problem that you think CTGAN should be able
13
+ to solve and is not solving already-->
14
+
15
+ ### Expected behavior
16
+
17
+ <!--Replace this a clear and concise description of what you would expect CTGAN with regards
18
+ with the described problem. If possible, explain how you would like to interact with CTGAN
19
+ and what the outcome of this interaction would be.-->
20
+
21
+ ### Additional context
22
+
23
+ <!--Please provide any additional context that may be relevant to the issue here. If none,
24
+ please remove this section.-->
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/question.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Question
3
+ about: Doubts about CTGAN usage
4
+ title: ''
5
+ labels: question, pending review
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ ### Environment details
11
+
12
+ If you are already running CTGAN, please indicate the following details about the environment in
13
+ which you are running it:
14
+
15
+ * CTGAN version:
16
+ * Python version:
17
+ * Operating System:
18
+
19
+ ### Problem description
20
+
21
+ <!--Replace this with a description of the problem that you are trying to solve using CTGAN. If
22
+ possible, describe the data that you are using, or consider attaching some example data
23
+ that others can use to propose a working solution for your problem.-->
24
+
25
+ ### What I already tried
26
+
27
+ <!--Replace with a description of what you already tried and what is the behavior that you observe.
28
+ If possible, also add below the exact code that you are running.-->
29
+
30
+ ```
31
+ Paste the command(s) you ran and the output.
32
+ If there was a crash, please include the traceback here.
33
+ ```
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/integration.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Integration Tests
2
+
3
+ on:
4
+ - push
5
+ - pull_request
6
+
7
+ jobs:
8
+ unit:
9
+ runs-on: ${{ matrix.os }}
10
+ strategy:
11
+ matrix:
12
+ python-version: [3.6, 3.7, 3.8, 3.9]
13
+ os: [ubuntu-latest, macos-10.15, windows-latest]
14
+ steps:
15
+ - uses: actions/checkout@v1
16
+ - name: Set up Python ${{ matrix.python-version }}
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - if: matrix.os == 'windows-latest'
21
+ name: Install dependencies - Windows
22
+ run: |
23
+ python -m pip install --upgrade pip
24
+ python -m pip install 'torch>=1.8,<2' -f https://download.pytorch.org/whl/cpu/torch/
25
+ python -m pip install 'torchvision>=0.9.0,<1' -f https://download.pytorch.org/whl/cpu/torchvision/
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ python -m pip install invoke .[test]
30
+ - name: Run integration tests
31
+ run: invoke integration
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/lint.yml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Style Checks
2
+
3
+ on:
4
+ - push
5
+ - pull_request
6
+
7
+ jobs:
8
+ lint:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - uses: actions/checkout@v1
12
+ - name: Set up Python 3.8
13
+ uses: actions/setup-python@v2
14
+ with:
15
+ python-version: 3.8
16
+ - name: Install dependencies
17
+ run: |
18
+ python -m pip install --upgrade pip
19
+ python -m pip install invoke .[dev]
20
+ - name: Run lint checks
21
+ run: invoke lint
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/minimum.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Unit Tests Minimum Versions
2
+
3
+ on:
4
+ - push
5
+ - pull_request
6
+
7
+ jobs:
8
+ minimum:
9
+ runs-on: ${{ matrix.os }}
10
+ strategy:
11
+ matrix:
12
+ python-version: [3.6, 3.7, 3.8, 3.9]
13
+ os: [ubuntu-latest, macos-10.15, windows-latest]
14
+ steps:
15
+ - uses: actions/checkout@v1
16
+ - name: Set up Python ${{ matrix.python-version }}
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - if: matrix.os == 'windows-latest'
21
+ name: Install dependencies - Windows
22
+ run: |
23
+ python -m pip install --upgrade pip
24
+ python -m pip install 'torch==1.8' -f https://download.pytorch.org/whl/cpu/torch/
25
+ python -m pip install 'torchvision==0.9.0' -f https://download.pytorch.org/whl/cpu/torchvision/
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ python -m pip install invoke .[test]
30
+ - name: Test with minimum versions
31
+ run: invoke minimum
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/readme.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Test README
2
+
3
+ on:
4
+ - push
5
+ - pull_request
6
+
7
+ jobs:
8
+ readme:
9
+ runs-on: ${{ matrix.os }}
10
+ strategy:
11
+ matrix:
12
+ python-version: [3.6, 3.7, 3.8, 3.9]
13
+ os: [ubuntu-latest, macos-10.15] # skip windows bc rundoc fails
14
+ steps:
15
+ - uses: actions/checkout@v1
16
+ - name: Set up Python ${{ matrix.python-version }}
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - name: Install dependencies
21
+ run: |
22
+ python -m pip install --upgrade pip
23
+ python -m pip install invoke rundoc .
24
+ - name: Run the README.md
25
+ run: invoke readme
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/unit.yml ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Unit Tests
2
+
3
+ on:
4
+ - push
5
+ - pull_request
6
+
7
+ jobs:
8
+ unit:
9
+ runs-on: ${{ matrix.os }}
10
+ strategy:
11
+ matrix:
12
+ python-version: [3.6, 3.7, 3.8, 3.9]
13
+ os: [ubuntu-latest, macos-10.15, windows-latest]
14
+ steps:
15
+ - uses: actions/checkout@v1
16
+ - name: Set up Python ${{ matrix.python-version }}
17
+ uses: actions/setup-python@v2
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - if: matrix.os == 'windows-latest'
21
+ name: Install dependencies - Windows
22
+ run: |
23
+ python -m pip install --upgrade pip
24
+ python -m pip install 'torch>=1.8,<2' -f https://download.pytorch.org/whl/cpu/torch/
25
+ python -m pip install 'torchvision>=0.9.0,<1' -f https://download.pytorch.org/whl/cpu/torchvision/
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ python -m pip install invoke .[test]
30
+ - name: Run unit tests
31
+ run: invoke unit
32
+ - if: matrix.os == 'ubuntu-latest' && matrix.python-version == 3.8
33
+ name: Upload codecov report
34
+ uses: codecov/codecov-action@v2
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.gitignore ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ env/
12
+ build/
13
+ develop-eggs/
14
+ dist/
15
+ downloads/
16
+ eggs/
17
+ .eggs/
18
+ lib/
19
+ lib64/
20
+ parts/
21
+ sdist/
22
+ var/
23
+ wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+
28
+ # PyInstaller
29
+ # Usually these files are written by a python script from a template
30
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
31
+ *.manifest
32
+ *.spec
33
+
34
+ # Installer logs
35
+ pip-log.txt
36
+ pip-delete-this-directory.txt
37
+
38
+ # Unit test / coverage reports
39
+ htmlcov/
40
+ .tox/
41
+ .coverage
42
+ .coverage.*
43
+ .cache
44
+ nosetests.xml
45
+ coverage.xml
46
+ *.cover
47
+ .hypothesis/
48
+ .pytest_cache/
49
+ tests/readme_test/
50
+
51
+ # Translations
52
+ *.mo
53
+ *.pot
54
+
55
+ # Django stuff:
56
+ *.log
57
+ local_settings.py
58
+
59
+ # Flask stuff:
60
+ instance/
61
+ .webassets-cache
62
+
63
+ # Scrapy stuff:
64
+ .scrapy
65
+
66
+ # Sphinx documentation
67
+ docs/_build/
68
+ docs/api/
69
+
70
+ # PyBuilder
71
+ target/
72
+
73
+ # Jupyter Notebook
74
+ .ipynb_checkpoints
75
+
76
+ # pyenv
77
+ .python-version
78
+
79
+ # celery beat schedule file
80
+ celerybeat-schedule
81
+
82
+ # SageMath parsed files
83
+ *.sage.py
84
+
85
+ # dotenv
86
+ .env
87
+
88
+ # virtualenv
89
+ .venv
90
+ venv/
91
+ ENV/
92
+
93
+ # Spyder project settings
94
+ .spyderproject
95
+ .spyproject
96
+
97
+ # Rope project settings
98
+ .ropeproject
99
+
100
+ # mkdocs documentation
101
+ /site
102
+
103
+ # mypy
104
+ .mypy_cache/
105
+
106
+ # Vim
107
+ .*.swp
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.travis.yml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Config file for automatic testing at travis-ci.org
2
+ dist: bionic
3
+ language: python
4
+ python:
5
+ - 3.8
6
+ - 3.7
7
+ - 3.6
8
+
9
+ # Command to install dependencies
10
+ install: pip install -U tox-travis codecov
11
+
12
+ after_success: codecov
13
+
14
+ # Command to run tests
15
+ script: tox
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/AUTHORS.rst ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Credits
2
+ =======
3
+
4
+ Research and Development Lead
5
+ -----------------------------
6
+
7
+ * Lei Xu <leix@mit.edu>
8
+
9
+ Contributors
10
+ ------------
11
+
12
+ * Carles Sala <csala@csail.mit.edu>
13
+ * Kevin Kuo <kevinykuo@gmail.com>
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/CONTRIBUTING.rst ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .. highlight:: shell
2
+
3
+ ============
4
+ Contributing
5
+ ============
6
+
7
+ Contributions are welcome, and they are greatly appreciated! Every little bit
8
+ helps, and credit will always be given.
9
+
10
+ You can contribute in many ways:
11
+
12
+ Types of Contributions
13
+ ----------------------
14
+
15
+ Report Bugs
16
+ ~~~~~~~~~~~
17
+
18
+ Report bugs at the `GitHub Issues page`_.
19
+
20
+ If you are reporting a bug, please include:
21
+
22
+ * Your operating system name and version.
23
+ * Any details about your local setup that might be helpful in troubleshooting.
24
+ * Detailed steps to reproduce the bug.
25
+
26
+ Fix Bugs
27
+ ~~~~~~~~
28
+
29
+ Look through the GitHub issues for bugs. Anything tagged with "bug" and "help
30
+ wanted" is open to whoever wants to implement it.
31
+
32
+ Implement Features
33
+ ~~~~~~~~~~~~~~~~~~
34
+
35
+ Look through the GitHub issues for features. Anything tagged with "enhancement"
36
+ and "help wanted" is open to whoever wants to implement it.
37
+
38
+ Write Documentation
39
+ ~~~~~~~~~~~~~~~~~~~
40
+
41
+ CTGAN could always use more documentation, whether as part of the
42
+ official CTGAN docs, in docstrings, or even on the web in blog posts,
43
+ articles, and such.
44
+
45
+ Submit Feedback
46
+ ~~~~~~~~~~~~~~~
47
+
48
+ The best way to send feedback is to file an issue at the `GitHub Issues page`_.
49
+
50
+ If you are proposing a feature:
51
+
52
+ * Explain in detail how it would work.
53
+ * Keep the scope as narrow as possible, to make it easier to implement.
54
+ * Remember that this is a volunteer-driven project, and that contributions
55
+ are welcome :)
56
+
57
+ Get Started!
58
+ ------------
59
+
60
+ Ready to contribute? Here's how to set up `CTGAN` for local development.
61
+
62
+ 1. Fork the `CTGAN` repo on GitHub.
63
+ 2. Clone your fork locally::
64
+
65
+ $ git clone git@github.com:your_name_here/CTGAN.git
66
+
67
+ 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed,
68
+ this is how you set up your fork for local development::
69
+
70
+ $ mkvirtualenv CTGAN
71
+ $ cd CTGAN/
72
+ $ make install-develop
73
+
74
+ 4. Create a branch for local development::
75
+
76
+ $ git checkout -b name-of-your-bugfix-or-feature
77
+
78
+ Try to use the naming scheme of prefixing your branch with ``gh-X`` where X is
79
+ the associated issue, such as ``gh-3-fix-foo-bug``. And if you are not
80
+ developing on your own fork, further prefix the branch with your GitHub
81
+ username, like ``githubusername/gh-3-fix-foo-bug``.
82
+
83
+ Now you can make your changes locally.
84
+
85
+ 5. While hacking your changes, make sure to cover all your developments with the required
86
+ unit tests, and that none of the old tests fail as a consequence of your changes.
87
+ For this, make sure to run the tests suite and check the code coverage::
88
+
89
+ $ make lint # Check code styling
90
+ $ make test # Run the tests
91
+ $ make coverage # Get the coverage report
92
+
93
+ 6. When you're done making changes, check that your changes pass all the styling checks and
94
+ tests, including other Python supported versions, using::
95
+
96
+ $ make test-all
97
+
98
+ 7. Make also sure to include the necessary documentation in the code as docstrings following
99
+ the `Google docstrings style`_.
100
+ If you want to view how your documentation will look like when it is published, you can
101
+ generate and view the docs with this command::
102
+
103
+ $ make view-docs
104
+
105
+ 8. Commit your changes and push your branch to GitHub::
106
+
107
+ $ git add .
108
+ $ git commit -m "Your detailed description of your changes."
109
+ $ git push origin name-of-your-bugfix-or-feature
110
+
111
+ 9. Submit a pull request through the GitHub website.
112
+
113
+ Pull Request Guidelines
114
+ -----------------------
115
+
116
+ Before you submit a pull request, check that it meets these guidelines:
117
+
118
+ 1. It resolves an open GitHub Issue and contains its reference in the title or
119
+ the comment. If there is no associated issue, feel free to create one.
120
+ 2. Whenever possible, it resolves only **one** issue. If your PR resolves more than
121
+ one issue, try to split it in more than one pull request.
122
+ 3. The pull request should include unit tests that cover all the changed code
123
+ 4. If the pull request adds functionality, the docs should be updated. Put
124
+ your new functionality into a function with a docstring, and add the
125
+ feature to the documentation in an appropriate place.
126
+ 5. The pull request should work for all the supported Python versions. Check the `Travis Build
127
+ Status page`_ and make sure that all the checks pass.
128
+
129
+ Unit Testing Guidelines
130
+ -----------------------
131
+
132
+ All the Unit Tests should comply with the following requirements:
133
+
134
+ 1. Unit Tests should be based only in unittest and pytest modules.
135
+
136
+ 2. The tests that cover a module called ``ctgan/path/to/a_module.py``
137
+ should be implemented in a separated module called
138
+ ``tests/ctgan/path/to/test_a_module.py``.
139
+ Note that the module name has the ``test_`` prefix and is located in a path similar
140
+ to the one of the tested module, just inside the ``tests`` folder.
141
+
142
+ 3. Each method of the tested module should have at least one associated test method, and
143
+ each test method should cover only **one** use case or scenario.
144
+
145
+ 4. Test case methods should start with the ``test_`` prefix and have descriptive names
146
+ that indicate which scenario they cover.
147
+ Names such as ``test_some_methed_input_none``, ``test_some_method_value_error`` or
148
+ ``test_some_method_timeout`` are right, but names like ``test_some_method_1``,
149
+ ``some_method`` or ``test_error`` are not.
150
+
151
+ 5. Each test should validate only what the code of the method being tested does, and not
152
+ cover the behavior of any third party package or tool being used, which is assumed to
153
+ work properly as far as it is being passed the right values.
154
+
155
+ 6. Any third party tool that may have any kind of random behavior, such as some Machine
156
+ Learning models, databases or Web APIs, will be mocked using the ``mock`` library, and
157
+ the only thing that will be tested is that our code passes the right values to them.
158
+
159
+ 7. Unit tests should not use anything from outside the test and the code being tested. This
160
+ includes not reading or writing to any file system or database, which will be properly
161
+ mocked.
162
+
163
+ Tips
164
+ ----
165
+
166
+ To run a subset of tests::
167
+
168
+ $ python -m pytest tests.test_ctgan
169
+ $ python -m pytest -k 'foo'
170
+
171
+ Release Workflow
172
+ ----------------
173
+
174
+ The process of releasing a new version involves several steps combining both ``git`` and
175
+ ``bumpversion`` which, briefly:
176
+
177
+ 1. Merge what is in ``master`` branch into ``stable`` branch.
178
+ 2. Update the version in ``setup.cfg``, ``ctgan/__init__.py`` and
179
+ ``HISTORY.md`` files.
180
+ 3. Create a new git tag pointing at the corresponding commit in ``stable`` branch.
181
+ 4. Merge the new commit from ``stable`` into ``master``.
182
+ 5. Update the version in ``setup.cfg`` and ``ctgan/__init__.py``
183
+ to open the next development iteration.
184
+
185
+ .. note:: Before starting the process, make sure that ``HISTORY.md`` has been updated with a new
186
+ entry that explains the changes that will be included in the new version.
187
+ Normally this is just a list of the Pull Requests that have been merged to master
188
+ since the last release.
189
+
190
+ Once this is done, run of the following commands:
191
+
192
+ 1. If you are releasing a patch version::
193
+
194
+ make release
195
+
196
+ 2. If you are releasing a minor version::
197
+
198
+ make release-minor
199
+
200
+ 3. If you are releasing a major version::
201
+
202
+ make release-major
203
+
204
+ Release Candidates
205
+ ~~~~~~~~~~~~~~~~~~
206
+
207
+ Sometimes it is necessary or convenient to upload a release candidate to PyPi as a pre-release,
208
+ in order to make some of the new features available for testing on other projects before they
209
+ are included in an actual full-blown release.
210
+
211
+ In order to perform such an action, you can execute::
212
+
213
+ make release-candidate
214
+
215
+ This will perform the following actions:
216
+
217
+ 1. Build and upload the current version to PyPi as a pre-release, with the format ``X.Y.Z.devN``
218
+
219
+ 2. Bump the current version to the next release candidate, ``X.Y.Z.dev(N+1)``
220
+
221
+ After this is done, the new pre-release can be installed by including the ``dev`` section in the
222
+ dependency specification, either in ``setup.py``::
223
+
224
+ install_requires = [
225
+ ...
226
+ 'ctgan>=X.Y.Z.dev',
227
+ ...
228
+ ]
229
+
230
+ or in command line::
231
+
232
+ pip install 'ctgan>=X.Y.Z.dev'
233
+
234
+
235
+ .. _GitHub issues page: https://github.com/sdv-dev/CTGAN/issues
236
+ .. _Travis Build Status page: https://travis-ci.org/sdv-dev/CTGAN/pull_requests
237
+ .. _Google docstrings style: https://google.github.io/styleguide/pyguide.html?showone=Comments#Comments
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/HISTORY.md ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # History
2
+
3
+ ## v0.5.1 - 2022-02-25
4
+
5
+ This release fixes a bug with the decoder instantiation, and also allows users to set a random state for the model
6
+ fitting and sampling.
7
+
8
+ ### Issues closed
9
+
10
+ * Update self.decoder with correct variable name - Issue [#203](https://github.com/sdv-dev/CTGAN/issues/203) by @tejuafonja
11
+ * Add random state - Issue [#204](https://github.com/sdv-dev/CTGAN/issues/204) by @katxiao
12
+
13
+ ## v0.5.0 - 2021-11-18
14
+
15
+ This release adds support for Python 3.9 and updates dependencies to ensure compatibility with the
16
+ rest of the SDV ecosystem, and upgrades to the latests [RDT](https://github.com/sdv-dev/RDT/releases/tag/v0.6.1)
17
+ release.
18
+
19
+ ### Issues closed
20
+
21
+ * Add support for Python 3.9 - Issue [#177](https://github.com/sdv-dev/CTGAN/issues/177) by @pvk-developer
22
+ * Add pip check to CI workflows - Issue [#174](https://github.com/sdv-dev/CTGAN/issues/174) by @pvk-developer
23
+ * Typo in `CTGAN` code - Issue [#158](https://github.com/sdv-dev/CTGAN/issues/158) by @ori-katz100 and @fealho
24
+
25
+ ## v0.4.3 - 2021-07-12
26
+
27
+ Dependency upgrades to ensure compatibility with the rest of the SDV ecosystem.
28
+
29
+ ## v0.4.2 - 2021-04-27
30
+
31
+ In this release, the way in which the loss function of the TVAE model was computed has been fixed.
32
+ In addition, the default value of the `discriminator_decay` has been changed to a more optimal
33
+ value. Also some improvements to the tests were added.
34
+
35
+ ### Issues closed
36
+
37
+ * `TVAE`: loss function - Issue [#143](https://github.com/sdv-dev/CTGAN/issues/143) by @fealho and @DingfanChen
38
+ * Set `discriminator_decay` to `1e-6` - Pull request [#145](https://github.com/sdv-dev/CTGAN/pull/145/) by @fealho
39
+ * Adds unit tests - Pull requests [#140](https://github.com/sdv-dev/CTGAN/pull/140) by @fealho
40
+
41
+ ## v0.4.1 - 2021-03-30
42
+
43
+ This release exposes all the hyperparameters which the user may find useful for both `CTGAN`
44
+ and `TVAE`. Also `TVAE` can now be fitted on datasets that are shorter than the batch
45
+ size and drops the last batch only if the data size is not divisible by the batch size.
46
+
47
+ ### Issues closed
48
+
49
+ * `TVAE`: Adapt `batch_size` to data size - Issue [#135](https://github.com/sdv-dev/CTGAN/issues/135) by @fealho and @csala
50
+ * `ValueError` from `validate_discre_columns` with `uniqueCombinationConstraint` - Issue [133](https://github.com/sdv-dev/CTGAN/issues/133) by @fealho and @MLjungg
51
+
52
+ ## v0.4.0 - 2021-02-24
53
+
54
+ Maintenance relese to upgrade dependencies to ensure compatibility with the rest
55
+ of the SDV libraries.
56
+
57
+ Also add a validation on the CTGAN `condition_column` and `condition_value` inputs.
58
+
59
+ ### Improvements
60
+
61
+ * Validate condition_column and condition_value - Issue [#124](https://github.com/sdv-dev/CTGAN/issues/124) by @fealho
62
+
63
+ ## v0.3.1 - 2021-01-27
64
+
65
+ ### Improvements
66
+
67
+ * Check discrete_columns valid before fitting - [Issue #35](https://github.com/sdv-dev/CTGAN/issues/35) by @fealho
68
+
69
+ ## Bugs fixed
70
+
71
+ * ValueError: max() arg is an empty sequence - [Issue #115](https://github.com/sdv-dev/CTGAN/issues/115) by @fealho
72
+
73
+ ## v0.3.0 - 2020-12-18
74
+
75
+ In this release we add a new TVAE model which was presented in the original CTGAN paper.
76
+ It also exposes more hyperparameters and moves epochs and log_frequency from fit to the constructor.
77
+
78
+ A new verbose argument has been added to optionally disable unnecessary printing, and a new hyperparameter
79
+ called `discriminator_steps` has been added to CTGAN to control the number of optimization steps performed
80
+ in the discriminator for each generator epoch.
81
+
82
+ The code has also been reorganized and cleaned up for better readability and interpretability.
83
+
84
+ Special thanks to @Baukebrenninkmeijer @fealho @leix28 @csala for the contributions!
85
+
86
+ ### Improvements
87
+
88
+ * Add TVAE - [Issue #111](https://github.com/sdv-dev/CTGAN/issues/111) by @fealho
89
+ * Move `log_frequency` to `__init__` - [Issue #102](https://github.com/sdv-dev/CTGAN/issues/102) by @fealho
90
+ * Add discriminator steps hyperparameter - [Issue #101](https://github.com/sdv-dev/CTGAN/issues/101) by @Baukebrenninkmeijer
91
+ * Code cleanup / Expose hyperparameters - [Issue #59](https://github.com/sdv-dev/CTGAN/issues/59) by @fealho and @leix28
92
+ * Publish to conda repo - [Issue #54](https://github.com/sdv-dev/CTGAN/issues/54) by @fealho
93
+
94
+ ### Bugs fixed
95
+
96
+ * Fixed NaN != NaN counting bug. - [Issue #100](https://github.com/sdv-dev/CTGAN/issues/100) by @fealho
97
+ * Update dependencies and testing - [Issue #90](https://github.com/sdv-dev/CTGAN/issues/90) by @csala
98
+
99
+ ## v0.2.2 - 2020-11-13
100
+
101
+ In this release we introduce several minor improvements to make CTGAN more versatile and
102
+ propertly support new types of data, such as categorical NaN values, as well as conditional
103
+ sampling and features to save and load models.
104
+
105
+ Additionally, the dependency ranges and python versions have been updated to support up
106
+ to date runtimes.
107
+
108
+ Many thanks @fealho @leix28 @csala @oregonpillow and @lurosenb for working on making this release possible!
109
+
110
+ ### Improvements
111
+
112
+ * Drop Python 3.5 support - [Issue #79](https://github.com/sdv-dev/CTGAN/issues/79) by @fealho
113
+ * Support NaN values in categorical variables - [Issue #78](https://github.com/sdv-dev/CTGAN/issues/78) by @fealho
114
+ * Sample synthetic data conditioning on a discrete column - [Issue #69](https://github.com/sdv-dev/CTGAN/issues/69) by @leix28
115
+ * Support recent versions of pandas - [Issue #57](https://github.com/sdv-dev/CTGAN/issues/57) by @csala
116
+ * Easy solution for restoring original dtypes - [Issue #26](https://github.com/sdv-dev/CTGAN/issues/26) by @oregonpillow
117
+
118
+ ### Bugs fixed
119
+
120
+ * Loss to nan - [Issue #73](https://github.com/sdv-dev/CTGAN/issues/73) by @fealho
121
+ * Swapped the sklearn utils testing import statement - [Issue #53](https://github.com/sdv-dev/CTGAN/issues/53) by @lurosenb
122
+
123
+ ## v0.2.1 - 2020-01-27
124
+
125
+ Minor version including changes to ensure the logs are properly printed and
126
+ the option to disable the log transformation to the discrete column frequencies.
127
+
128
+ Special thanks to @kevinykuo for the contributions!
129
+
130
+ ### Issues Resolved:
131
+
132
+ * Option to sample from true data frequency instead of logged frequency - [Issue #16](https://github.com/sdv-dev/CTGAN/issues/16) by @kevinykuo
133
+ * Flush stdout buffer for epoch updates - [Issue #14](https://github.com/sdv-dev/CTGAN/issues/14) by @kevinykuo
134
+
135
+ ## v0.2.0 - 2019-12-18
136
+
137
+ Reorganization of the project structure with a new Python API, new Command Line Interface
138
+ and increased data format support.
139
+
140
+ ### Issues Resolved:
141
+
142
+ * Reorganize the project structure - [Issue #10](https://github.com/sdv-dev/CTGAN/issues/10) by @csala
143
+ * Move epochs to the fit method - [Issue #5](https://github.com/sdv-dev/CTGAN/issues/5) by @csala
144
+
145
+ ## v0.1.0 - 2019-11-07
146
+
147
+ First Release - NeurIPS 2019 Version.
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2019, MIT Data To AI Lab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/MANIFEST.in ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ include AUTHORS.rst
2
+ include CONTRIBUTING.rst
3
+ include HISTORY.md
4
+ include LICENSE
5
+ include README.md
6
+
7
+ recursive-include tests *
8
+ recursive-exclude * __pycache__
9
+ recursive-exclude * *.py[co]
10
+
11
+ recursive-include docs *.md *.rst conf.py Makefile make.bat *.jpg *.png *.gif
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/Makefile ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DEFAULT_GOAL := help
2
+
3
+ define BROWSER_PYSCRIPT
4
+ import os, webbrowser, sys
5
+
6
+ try:
7
+ from urllib import pathname2url
8
+ except:
9
+ from urllib.request import pathname2url
10
+
11
+ webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1])))
12
+ endef
13
+ export BROWSER_PYSCRIPT
14
+
15
+ define PRINT_HELP_PYSCRIPT
16
+ import re, sys
17
+
18
+ for line in sys.stdin:
19
+ match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line)
20
+ if match:
21
+ target, help = match.groups()
22
+ print("%-20s %s" % (target, help))
23
+ endef
24
+ export PRINT_HELP_PYSCRIPT
25
+
26
+ BROWSER := python -c "$$BROWSER_PYSCRIPT"
27
+
28
+ .PHONY: help
29
+ help:
30
+ @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST)
31
+
32
+
33
+ # CLEAN TARGETS
34
+
35
+ .PHONY: clean-build
36
+ clean-build: ## remove build artifacts
37
+ rm -fr build/
38
+ rm -fr dist/
39
+ rm -fr .eggs/
40
+ find . -name '*.egg-info' -exec rm -fr {} +
41
+ find . -name '*.egg' -exec rm -f {} +
42
+
43
+ .PHONY: clean-pyc
44
+ clean-pyc: ## remove Python file artifacts
45
+ find . -name '*.pyc' -exec rm -f {} +
46
+ find . -name '*.pyo' -exec rm -f {} +
47
+ find . -name '*~' -exec rm -f {} +
48
+ find . -name '__pycache__' -exec rm -fr {} +
49
+
50
+ .PHONY: clean-coverage
51
+ clean-coverage: ## remove coverage artifacts
52
+ rm -f .coverage
53
+ rm -f .coverage.*
54
+ rm -fr htmlcov/
55
+
56
+ .PHONY: clean-test
57
+ clean-test: ## remove test artifacts
58
+ rm -fr .tox/
59
+ rm -fr .pytest_cache
60
+
61
+ .PHONY: clean
62
+ clean: clean-build clean-pyc clean-test clean-coverage ## remove all build, test, coverage and Python artifacts
63
+
64
+
65
+ # INSTALL TARGETS
66
+
67
+ .PHONY: install
68
+ install: clean-build clean-pyc ## install the package to the active Python's site-packages
69
+ pip install .
70
+
71
+ .PHONY: install-test
72
+ install-test: clean-build clean-pyc ## install the package and test dependencies
73
+ pip install .[test]
74
+
75
+ .PHONY: install-develop
76
+ install-develop: clean-build clean-pyc ## install the package in editable mode and dependencies for development
77
+ pip install -e .[dev]
78
+
79
+ MINIMUM := $(shell sed -n '/install_requires = \[/,/]/p' setup.py | head -n-1 | tail -n+2 | sed 's/ *\(.*\),$?$$/\1/g' | tr '>' '=')
80
+
81
+ .PHONY: install-minimum
82
+ install-minimum: ## install the minimum supported versions of the package dependencies
83
+ pip install $(MINIMUM)
84
+
85
+
86
+ # LINT TARGETS
87
+
88
+
89
+ .PHONY: lint
90
+ lint: ## check style with flake8 and isort
91
+ invoke lint
92
+
93
+ .PHONY: fix-lint
94
+ fix-lint: ## fix lint issues using autoflake, autopep8, and isort
95
+ find ctgan tests -name '*.py' | xargs autoflake --in-place --remove-all-unused-imports --remove-unused-variables
96
+ autopep8 --in-place --recursive --aggressive ctgan tests
97
+ isort --apply --atomic --recursive ctgan tests
98
+
99
+
100
+ # TEST TARGETS
101
+
102
+ .PHONY: test-unit
103
+ test-unit: ## run unit tests using pytest
104
+ invoke unit
105
+
106
+ .PHONY: test-integration
107
+ test-integration: ## run integration tests using pytest
108
+ invoke integration
109
+
110
+ .PHONY: test-readme
111
+ test-readme: ## run the readme snippets
112
+ invoke readme
113
+
114
+ .PHONY: check-dependencies
115
+ check-dependencies: ## test if there are any broken dependencies
116
+ pip check
117
+
118
+ .PHONY: test
119
+ test: test-unit test-integration test-readme ## test everything that needs test dependencies
120
+
121
+ .PHONY: test-devel
122
+ test-devel: lint ## test everything that needs development dependencies
123
+
124
+ .PHONY: test-all
125
+ test-all: ## run tests on every Python version with tox
126
+ tox -r
127
+
128
+
129
+ .PHONY: coverage
130
+ coverage: ## check code coverage quickly with the default Python
131
+ coverage run --source ctgan -m pytest
132
+ coverage report -m
133
+ coverage html
134
+ $(BROWSER) htmlcov/index.html
135
+
136
+
137
+ # RELEASE TARGETS
138
+
139
+ .PHONY: dist
140
+ dist: clean ## builds source and wheel package
141
+ python setup.py sdist
142
+ python setup.py bdist_wheel
143
+ ls -l dist
144
+
145
+ .PHONY: publish-confirm
146
+ publish-confirm:
147
+ @echo "WARNING: This will irreversibly upload a new version to PyPI!"
148
+ @echo -n "Please type 'confirm' to proceed: " \
149
+ && read answer \
150
+ && [ "$${answer}" = "confirm" ]
151
+
152
+ .PHONY: publish-test
153
+ publish-test: dist publish-confirm ## package and upload a release on TestPyPI
154
+ twine upload --repository-url https://test.pypi.org/legacy/ dist/*
155
+
156
+ .PHONY: publish
157
+ publish: dist publish-confirm ## package and upload a release
158
+ twine upload dist/*
159
+
160
+ .PHONY: bumpversion-release
161
+ bumpversion-release: ## Merge master to stable and bumpversion release
162
+ git checkout stable || git checkout -b stable
163
+ git merge --no-ff master -m"make release-tag: Merge branch 'master' into stable"
164
+ bumpversion release
165
+ git push --tags origin stable
166
+
167
+ .PHONY: bumpversion-release-test
168
+ bumpversion-release-test: ## Merge master to stable and bumpversion release
169
+ git checkout stable || git checkout -b stable
170
+ git merge --no-ff master -m"make release-tag: Merge branch 'master' into stable"
171
+ bumpversion release --no-tag
172
+ @echo git push --tags origin stable
173
+
174
+ .PHONY: bumpversion-patch
175
+ bumpversion-patch: ## Merge stable to master and bumpversion patch
176
+ git checkout master
177
+ git merge stable
178
+ bumpversion --no-tag patch
179
+ git push
180
+
181
+ .PHONY: bumpversion-candidate
182
+ bumpversion-candidate: ## Bump the version to the next candidate
183
+ bumpversion candidate --no-tag
184
+
185
+ .PHONY: bumpversion-minor
186
+ bumpversion-minor: ## Bump the version the next minor skipping the release
187
+ bumpversion --no-tag minor
188
+
189
+ .PHONY: bumpversion-major
190
+ bumpversion-major: ## Bump the version the next major skipping the release
191
+ bumpversion --no-tag major
192
+
193
+ .PHONY: bumpversion-revert
194
+ bumpversion-revert: ## Undo a previous bumpversion-release
195
+ git checkout master
196
+ git branch -D stable
197
+
198
+ CLEAN_DIR := $(shell git status --short | grep -v ??)
199
+ CURRENT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null)
200
+ CHANGELOG_LINES := $(shell git diff HEAD..origin/stable HISTORY.md 2>&1 | wc -l)
201
+
202
+ .PHONY: check-clean
203
+ check-clean: ## Check if the directory has uncommitted changes
204
+ ifneq ($(CLEAN_DIR),)
205
+ $(error There are uncommitted changes)
206
+ endif
207
+
208
+ .PHONY: check-master
209
+ check-master: ## Check if we are in master branch
210
+ ifneq ($(CURRENT_BRANCH),master)
211
+ $(error Please make the release from master branch\n)
212
+ endif
213
+
214
+ .PHONY: check-history
215
+ check-history: ## Check if HISTORY.md has been modified
216
+ ifeq ($(CHANGELOG_LINES),0)
217
+ $(error Please insert the release notes in HISTORY.md before releasing)
218
+ endif
219
+
220
+ .PHONY: check-release
221
+ check-release: check-clean check-master check-history ## Check if the release can be made
222
+ @echo "A new release can be made"
223
+
224
+ .PHONY: release
225
+ release: check-release bumpversion-release publish bumpversion-patch
226
+
227
+ .PHONY: release-test
228
+ release-test: check-release bumpversion-release-test publish-test bumpversion-revert
229
+
230
+ .PHONY: release-candidate
231
+ release-candidate: check-master publish bumpversion-candidate
232
+
233
+ .PHONY: release-candidate-test
234
+ release-candidate-test: check-clean check-master publish-test
235
+
236
+ .PHONY: release-minor
237
+ release-minor: check-release bumpversion-minor release
238
+
239
+ .PHONY: release-major
240
+ release-major: check-release bumpversion-major release
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/README.md ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+ <br/>
3
+ <p align="center">
4
+ <i>This repository is part of <a href="https://sdv.dev">The Synthetic Data Vault Project</a>, a project from <a href="https://datacebo.com">DataCebo</a>.</i>
5
+ </p>
6
+
7
+ [![Development Status](https://img.shields.io/badge/Development%20Status-2%20--%20Pre--Alpha-yellow)](https://pypi.org/search/?c=Development+Status+%3A%3A+2+-+Pre-Alpha)
8
+ [![PyPI Shield](https://img.shields.io/pypi/v/ctgan.svg)](https://pypi.python.org/pypi/ctgan)
9
+ [![Unit Tests](https://github.com/sdv-dev/CTGAN/actions/workflows/unit.yml/badge.svg)](https://github.com/sdv-dev/CTGAN/actions/workflows/unit.yml)
10
+ [![Downloads](https://pepy.tech/badge/ctgan)](https://pepy.tech/project/ctgan)
11
+ [![Coverage Status](https://codecov.io/gh/sdv-dev/CTGAN/branch/master/graph/badge.svg)](https://codecov.io/gh/sdv-dev/CTGAN)
12
+
13
+ <div align="left">
14
+ <br/>
15
+ <p align="center">
16
+ <a href="https://github.com/sdv-dev/CTGAN">
17
+ <img align="center" width=40% src="https://github.com/sdv-dev/SDV/blob/master/docs/images/CTGAN-DataCebo.png"></img>
18
+ </a>
19
+ </p>
20
+ </div>
21
+
22
+ </div>
23
+
24
+ # Overview
25
+
26
+ CTGAN is a collection of Deep Learning based Synthetic Data Generators for single table data, which are able to learn from real data and generate synthetic clones with high fidelity.
27
+
28
+ | Important Links | |
29
+ | --------------------------------------------- | -------------------------------------------------------------------- |
30
+ | :computer: **[Website]** | Check out the SDV Website for more information about the project. |
31
+ | :orange_book: **[SDV Blog]** | Regular publshing of useful content about Synthetic Data Generation. |
32
+ | :book: **[Documentation]** | Quickstarts, User and Development Guides, and API Reference. |
33
+ | :octocat: **[Repository]** | The link to the Github Repository of this library. |
34
+ | :scroll: **[License]** | The entire ecosystem is published under the MIT License. |
35
+ | :keyboard: **[Development Status]** | This software is in its Pre-Alpha stage. |
36
+ | [![][Slack Logo] **Community**][Community] | Join our Slack Workspace for announcements and discussions. |
37
+ | [![][MyBinder Logo] **Tutorials**][Tutorials] | Run the SDV Tutorials in a Binder environment. |
38
+
39
+ [Website]: https://sdv.dev
40
+ [SDV Blog]: https://sdv.dev/blog
41
+ [Documentation]: https://sdv.dev/SDV
42
+ [Repository]: https://github.com/sdv-dev/CTGAN
43
+ [License]: https://github.com/sdv-dev/CTGAN/blob/master/LICENSE
44
+ [Development Status]: https://pypi.org/search/?c=Development+Status+%3A%3A+2+-+Pre-Alpha
45
+ [Slack Logo]: https://github.com/sdv-dev/SDV/blob/master/docs/images/slack.png
46
+ [Community]: https://join.slack.com/t/sdv-space/shared_invite/zt-gdsfcb5w-0QQpFMVoyB2Yd6SRiMplcw
47
+ [MyBinder Logo]: https://github.com/sdv-dev/SDV/blob/master/docs/images/mybinder.png
48
+ [Tutorials]: https://mybinder.org/v2/gh/sdv-dev/SDV/master?filepath=tutorials
49
+
50
+ ## Implemented Models
51
+
52
+ Currently, this library implements the **CTGAN** and **TVAE** models proposed in the [Modeling Tabular data using Conditional GAN](https://arxiv.org/abs/1907.00503) paper. For more information about these models, please check out the respective user guides:
53
+ * [CTGAN User Guide](https://sdv.dev/SDV/user_guides/single_table/ctgan.html).
54
+ * [TVAE User Guide](https://sdv.dev/SDV/user_guides/single_table/tvae.html).
55
+
56
+ # Install
57
+
58
+ **CTGAN** is part of the **SDV** project and is automatically installed alongside it. For
59
+ details about this process please visit the [SDV Installation Guide](
60
+ https://sdv.dev/SDV/getting_started/install.html)
61
+
62
+ Optionally, **CTGAN** can also be installed as a standalone library using the following commands:
63
+
64
+ **Using `pip`:**
65
+
66
+ ```bash
67
+ pip install ctgan
68
+ ```
69
+
70
+ **Using `conda`:**
71
+
72
+ ```bash
73
+ conda install -c pytorch -c conda-forge ctgan
74
+ ```
75
+
76
+ For more installation options please visit the [CTGAN installation Guide](INSTALL.md)
77
+
78
+ # Usage Example
79
+
80
+ > :warning: **WARNING**: If you're just getting started with synthetic data, we recommend using the SDV library which provides user-friendly APIs for interacting with CTGAN. To learn more about using CTGAN through SDV, check out the user guide [here](https://sdv.dev/SDV/user_guides/single_table/ctgan.html).
81
+
82
+ To get started with CTGAN, you should prepare your data as either a `numpy.ndarray` or a `pandas.DataFrame` object with two types of columns:
83
+
84
+ * **Continuous Columns**: can contain any numerical value.
85
+ * **Discrete Columns**: contain a finite number values, whether these are string values or not.
86
+
87
+ In this example we load the [Adult Census Dataset](https://archive.ics.uci.edu/ml/datasets/adult) which is a built-in demo dataset. We then model it using the **CTGANSynthesizer** and generate a synthetic copy of it.
88
+
89
+
90
+ ```python3
91
+ from ctgan import CTGANSynthesizer
92
+ from ctgan import load_demo
93
+
94
+ data = load_demo()
95
+
96
+ # Names of the columns that are discrete
97
+ discrete_columns = [
98
+ 'workclass',
99
+ 'education',
100
+ 'marital-status',
101
+ 'occupation',
102
+ 'relationship',
103
+ 'race',
104
+ 'sex',
105
+ 'native-country',
106
+ 'income'
107
+ ]
108
+
109
+ ctgan = CTGANSynthesizer(epochs=10)
110
+ ctgan.fit(data, discrete_columns)
111
+
112
+ # Synthetic copy
113
+ samples = ctgan.sample(1000)
114
+ ```
115
+
116
+
117
+
118
+ # Join our community
119
+
120
+
121
+ 1. Please have a look at the [Contributing Guide](https://sdv.dev/SDV/developer_guides/contributing.html) to see how you can contribute to the project.
122
+ 2. If you have any doubts, feature requests or detect an error, please [open an issue on github](https://github.com/sdv-dev/CTGAN/issues) or [join our Slack Workspace](https://sdv-space.slack.com/join/shared_invite/zt-gdsfcb5w-0QQpFMVoyB2Yd6SRiMplcw#/).
123
+ 3. Also, do not forget to check the [project documentation site](https://sdv.dev/SDV/)!
124
+
125
+
126
+ # Citing TGAN
127
+
128
+ If you use CTGAN, please cite the following work:
129
+
130
+ - *Lei Xu, Maria Skoularidou, Alfredo Cuesta-Infante, Kalyan Veeramachaneni.* **Modeling Tabular data using Conditional GAN**. NeurIPS, 2019.
131
+
132
+ ```LaTeX
133
+ @inproceedings{xu2019modeling,
134
+ title={Modeling Tabular data using Conditional GAN},
135
+ author={Xu, Lei and Skoularidou, Maria and Cuesta-Infante, Alfredo and Veeramachaneni, Kalyan},
136
+ booktitle={Advances in Neural Information Processing Systems},
137
+ year={2019}
138
+ }
139
+ ```
140
+
141
+ # Related Projects
142
+ Please note that these libraries are external contributions and are not maintained nor supervised by
143
+ the MIT DAI-Lab team.
144
+
145
+ ## R interface for CTGAN
146
+
147
+ A wrapper around **CTGAN** has been implemented by Kevin Kuo @kevinykuo, bringing the functionalities
148
+ of **CTGAN** to **R** users.
149
+
150
+ More details can be found in the corresponding repository: https://github.com/kasaai/ctgan
151
+
152
+ ## CTGAN Server CLI
153
+
154
+ A package to easily deploy **CTGAN** onto a remote server. This package is developed by Timothy Pillow @oregonpillow.
155
+
156
+ More details can be found in the corresponding repository: https://github.com/oregonpillow/ctgan-server-cli
157
+
158
+ ---
159
+
160
+
161
+ <div align="center">
162
+ <a href="https://datacebo.com"><img align="center" width=40% src="https://github.com/sdv-dev/SDV/blob/master/docs/images/DataCebo.png"></img></a>
163
+ </div>
164
+ <br/>
165
+ <br/>
166
+
167
+ [The Synthetic Data Vault Project](https://sdv.dev) was first created at MIT's [Data to AI Lab](
168
+ https://dai.lids.mit.edu/) in 2016. After 4 years of research and traction with enterprise, we
169
+ created [DataCebo](https://datacebo.com) in 2020 with the goal of growing the project.
170
+ Today, DataCebo is the proud developer of SDV, the largest ecosystem for
171
+ synthetic data generation & evaluation. It is home to multiple libraries that support synthetic
172
+ data, including:
173
+
174
+ * 🔄 Data discovery & transformation. Reverse the transforms to reproduce realistic data.
175
+ * 🧠 Multiple machine learning models -- ranging from Copulas to Deep Learning -- to create tabular,
176
+ multi table and time series data.
177
+ * 📊 Measuring quality and privacy of synthetic data, and comparing different synthetic data
178
+ generation models.
179
+
180
+ [Get started using the SDV package](https://sdv.dev/SDV/getting_started/install.html) -- a fully
181
+ integrated solution and your one-stop shop for synthetic data. Or, use the standalone libraries
182
+ for specific needs.
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/README.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Instructions
2
+
3
+ These are instructions to deploy the latest version of **CTGAN** to [conda](https://docs.conda.io/en/latest/).
4
+ It should be done after every new release.
5
+
6
+ ## Update the recipe
7
+ Prior to making the release on PyPI, you should update the meta.yaml to reflect any changes in the dependencies.
8
+ Note that you do not need to edit the version number as that is managed by bumpversion.
9
+
10
+ ## Make the PyPI release
11
+ Follow the standard release instructions to make a PyPI release. Then, return here to make the conda release.
12
+
13
+ ## Build a package
14
+ As part of the PyPI release, you will have updated the stable branch. You should now check out the stable
15
+ branch and build the conda package.
16
+
17
+ ```bash
18
+ git checkout stable
19
+ cd conda
20
+ conda build -c sdv-dev -c pytorch -c conda-forge .
21
+ ```
22
+
23
+ ## Upload to Anaconda
24
+ Finally, you can upload the resulting package to Anaconda.
25
+
26
+ ```bash
27
+ anaconda login
28
+ anaconda upload -u sdv-dev <PATH_TO_PACKAGE>
29
+ ```
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/meta.yaml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% set name = 'ctgan' %}
2
+ {% set version = '0.5.2.dev0' %}
3
+
4
+ package:
5
+ name: "{{ name|lower }}"
6
+ version: "{{ version }}"
7
+
8
+ source:
9
+ url: "https://pypi.io/packages/source/{{ name[0] }}/{{ name }}/{{ name }}-{{ version }}.tar.gz"
10
+
11
+ build:
12
+ number: 0
13
+ noarch: python
14
+ entry_points:
15
+ - ctgan=ctgan.__main__:main
16
+ script: "{{ PYTHON }} -m pip install . -vv"
17
+
18
+ requirements:
19
+ host:
20
+ - pip
21
+ - pytest-runner
22
+ - packaging >=20,<22
23
+ - python >=3.6,<3.10
24
+ - numpy >=1.18.0,<2
25
+ - pandas >=1.1.3,<2
26
+ - scikit-learn >=0.24,<1
27
+ - pytorch >=1.8.0,<2
28
+ - torchvision >=0.9.0,<1
29
+ - rdt >=0.6.2,<0.7
30
+ run:
31
+ - packaging >=20,<22
32
+ - python >=3.6,<3.10
33
+ - numpy >=1.18.0,<2
34
+ - pandas >=1.1.3,<2
35
+ - scikit-learn >=0.24,<1
36
+ - pytorch >=1.8.0,<2
37
+ - torchvision >=0.9.0,<1
38
+ - rdt >=0.6.2,<0.7
39
+
40
+ about:
41
+ home: "https://github.com/sdv-dev/CTGAN"
42
+ license: MIT
43
+ license_family: MIT
44
+ license_file:
45
+ summary: "Conditional GAN for Tabular Data"
46
+ doc_url:
47
+ dev_url:
48
+
49
+ extra:
50
+ recipe-maintainers:
51
+ - sdv-dev
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__init__.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ """Top-level package for ctgan."""
4
+
5
+ __author__ = 'MIT Data To AI Lab'
6
+ __email__ = 'dailabmit@gmail.com'
7
+ __version__ = '0.5.2.dev0'
8
+
9
+ from .demo import load_demo
10
+ from .synthesizers.ctgan import CTGANSynthesizer
11
+ from .synthesizers.tvae import TVAESynthesizer
12
+
13
+ __all__ = (
14
+ 'CTGANSynthesizer',
15
+ 'TVAESynthesizer',
16
+ 'load_demo'
17
+ )
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__main__.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CLI."""
2
+
3
+ import argparse
4
+
5
+ from ctgan.data import read_csv, read_tsv, write_tsv
6
+ from ctgan.synthesizers.ctgan import CTGANSynthesizer
7
+
8
+
9
+ def _parse_args():
10
+ parser = argparse.ArgumentParser(description='CTGAN Command Line Interface')
11
+ parser.add_argument('-e', '--epochs', default=300, type=int,
12
+ help='Number of training epochs')
13
+ parser.add_argument('-t', '--tsv', action='store_true',
14
+ help='Load data in TSV format instead of CSV')
15
+ parser.add_argument('--no-header', dest='header', action='store_false',
16
+ help='The CSV file has no header. Discrete columns will be indices.')
17
+
18
+ parser.add_argument('-m', '--metadata', help='Path to the metadata')
19
+ parser.add_argument('-d', '--discrete',
20
+ help='Comma separated list of discrete columns without whitespaces.')
21
+ parser.add_argument('-n', '--num-samples', type=int,
22
+ help='Number of rows to sample. Defaults to the training data size')
23
+
24
+ parser.add_argument('--generator_lr', type=float, default=2e-4,
25
+ help='Learning rate for the generator.')
26
+ parser.add_argument('--discriminator_lr', type=float, default=2e-4,
27
+ help='Learning rate for the discriminator.')
28
+
29
+ parser.add_argument('--generator_decay', type=float, default=1e-6,
30
+ help='Weight decay for the generator.')
31
+ parser.add_argument('--discriminator_decay', type=float, default=0,
32
+ help='Weight decay for the discriminator.')
33
+
34
+ parser.add_argument('--embedding_dim', type=int, default=128,
35
+ help='Dimension of input z to the generator.')
36
+ parser.add_argument('--generator_dim', type=str, default='256,256',
37
+ help='Dimension of each generator layer. '
38
+ 'Comma separated integers with no whitespaces.')
39
+ parser.add_argument('--discriminator_dim', type=str, default='256,256',
40
+ help='Dimension of each discriminator layer. '
41
+ 'Comma separated integers with no whitespaces.')
42
+
43
+ parser.add_argument('--batch_size', type=int, default=500,
44
+ help='Batch size. Must be an even number.')
45
+ parser.add_argument('--save', default=None, type=str,
46
+ help='A filename to save the trained synthesizer.')
47
+ parser.add_argument('--load', default=None, type=str,
48
+ help='A filename to load a trained synthesizer.')
49
+
50
+ parser.add_argument('--sample_condition_column', default=None, type=str,
51
+ help='Select a discrete column name.')
52
+ parser.add_argument('--sample_condition_column_value', default=None, type=str,
53
+ help='Specify the value of the selected discrete column.')
54
+
55
+ parser.add_argument('data', help='Path to training data')
56
+ parser.add_argument('output', help='Path of the output file')
57
+
58
+ return parser.parse_args()
59
+
60
+
61
+ def main():
62
+ """CLI."""
63
+ args = _parse_args()
64
+ if args.tsv:
65
+ data, discrete_columns = read_tsv(args.data, args.metadata)
66
+ else:
67
+ data, discrete_columns = read_csv(args.data, args.metadata, args.header, args.discrete)
68
+
69
+ if args.load:
70
+ model = CTGANSynthesizer.load(args.load)
71
+ else:
72
+ generator_dim = [int(x) for x in args.generator_dim.split(',')]
73
+ discriminator_dim = [int(x) for x in args.discriminator_dim.split(',')]
74
+ model = CTGANSynthesizer(
75
+ embedding_dim=args.embedding_dim, generator_dim=generator_dim,
76
+ discriminator_dim=discriminator_dim, generator_lr=args.generator_lr,
77
+ generator_decay=args.generator_decay, discriminator_lr=args.discriminator_lr,
78
+ discriminator_decay=args.discriminator_decay, batch_size=args.batch_size,
79
+ epochs=args.epochs)
80
+ model.fit(data, discrete_columns)
81
+
82
+ if args.save is not None:
83
+ model.save(args.save)
84
+
85
+ num_samples = args.num_samples or len(data)
86
+
87
+ if args.sample_condition_column is not None:
88
+ assert args.sample_condition_column_value is not None
89
+
90
+ sampled = model.sample(
91
+ num_samples,
92
+ args.sample_condition_column,
93
+ args.sample_condition_column_value)
94
+
95
+ if args.tsv:
96
+ write_tsv(sampled, args.metadata, args.output)
97
+ else:
98
+ sampled.to_csv(args.output, index=False)
99
+
100
+
101
+ if __name__ == '__main__':
102
+ main()
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Data loading."""
2
+
3
+ import json
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+
8
+
9
+ def read_csv(csv_filename, meta_filename=None, header=True, discrete=None):
10
+ """Read a csv file."""
11
+ data = pd.read_csv(csv_filename, header='infer' if header else None)
12
+
13
+ if meta_filename:
14
+ with open(meta_filename) as meta_file:
15
+ metadata = json.load(meta_file)
16
+
17
+ discrete_columns = [
18
+ column['name']
19
+ for column in metadata['columns']
20
+ if column['type'] != 'continuous'
21
+ ]
22
+
23
+ elif discrete:
24
+ discrete_columns = discrete.split(',')
25
+ if not header:
26
+ discrete_columns = [int(i) for i in discrete_columns]
27
+
28
+ else:
29
+ discrete_columns = []
30
+
31
+ return data, discrete_columns
32
+
33
+
34
+ def read_tsv(data_filename, meta_filename):
35
+ """Read a tsv file."""
36
+ with open(meta_filename) as f:
37
+ column_info = f.readlines()
38
+
39
+ column_info_raw = [
40
+ x.replace('{', ' ').replace('}', ' ').split()
41
+ for x in column_info
42
+ ]
43
+
44
+ discrete = []
45
+ continuous = []
46
+ column_info = []
47
+
48
+ for idx, item in enumerate(column_info_raw):
49
+ if item[0] == 'C':
50
+ continuous.append(idx)
51
+ column_info.append((float(item[1]), float(item[2])))
52
+ else:
53
+ assert item[0] == 'D'
54
+ discrete.append(idx)
55
+ column_info.append(item[1:])
56
+
57
+ meta = {
58
+ 'continuous_columns': continuous,
59
+ 'discrete_columns': discrete,
60
+ 'column_info': column_info
61
+ }
62
+
63
+ with open(data_filename) as f:
64
+ lines = f.readlines()
65
+
66
+ data = []
67
+ for row in lines:
68
+ row_raw = row.split()
69
+ row = []
70
+ for idx, col in enumerate(row_raw):
71
+ if idx in continuous:
72
+ row.append(col)
73
+ else:
74
+ assert idx in discrete
75
+ row.append(column_info[idx].index(col))
76
+
77
+ data.append(row)
78
+
79
+ return np.asarray(data, dtype='float32'), meta['discrete_columns']
80
+
81
+
82
+ def write_tsv(data, meta, output_filename):
83
+ """Write to a tsv file."""
84
+ with open(output_filename, 'w') as f:
85
+
86
+ for row in data:
87
+ for idx, col in enumerate(row):
88
+ if idx in meta['continuous_columns']:
89
+ print(col, end=' ', file=f)
90
+ else:
91
+ assert idx in meta['discrete_columns']
92
+ print(meta['column_info'][idx][int(col)], end=' ', file=f)
93
+
94
+ print(file=f)