TabQueryBench commited on
Commit
76eb9b9
·
verified ·
1 Parent(s): 2327eb8

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/ctabgan.py +70 -0
  2. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/eval/evaluation.py +193 -0
  3. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/pipeline/data_preparation.py +130 -0
  4. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/privacy_utils/rdp_accountant.py +280 -0
  5. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/ctabgan_synthesizer.py +601 -0
  6. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/transformer.py +429 -0
  7. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py +72 -0
  8. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/eval/evaluation.py +193 -0
  9. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/pipeline/data_preparation.py +131 -0
  10. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/privacy_utils/rdp_accountant.py +280 -0
  11. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/ctabgan_synthesizer.py +605 -0
  12. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/transformer.py +429 -0
  13. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/__init__.py +0 -0
  14. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py +58 -0
  15. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py +191 -0
  16. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/pipeline/data_preparation.py +114 -0
  17. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/ctabgan_synthesizer.py +526 -0
  18. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/transformer.py +363 -0
  19. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.editorconfig +24 -0
  20. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/CODEOWNERS +2 -0
  21. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/bug_report.md +33 -0
  22. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/feature_request.md +24 -0
  23. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/question.md +33 -0
  24. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/integration.yml +31 -0
  25. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/lint.yml +21 -0
  26. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/minimum.yml +31 -0
  27. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/readme.yml +25 -0
  28. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/unit.yml +34 -0
  29. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.gitignore +107 -0
  30. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.travis.yml +15 -0
  31. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/AUTHORS.rst +13 -0
  32. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/CONTRIBUTING.rst +237 -0
  33. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/HISTORY.md +147 -0
  34. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/LICENSE +22 -0
  35. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/MANIFEST.in +11 -0
  36. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/Makefile +240 -0
  37. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/README.md +182 -0
  38. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/README.md +29 -0
  39. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/meta.yaml +51 -0
  40. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__init__.py +17 -0
  41. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__main__.py +102 -0
  42. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data.py +94 -0
  43. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_sampler.py +156 -0
  44. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_transformer.py +217 -0
  45. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/demo.py +10 -0
  46. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/__init__.py +16 -0
  47. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/base.py +105 -0
  48. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/ctgan.py +482 -0
  49. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/tvae.py +218 -0
  50. syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.cfg +59 -0
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/ctabgan.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Generative model training algorithm based on the CTABGANSynthesiser
3
+
4
+ """
5
+ import pandas as pd
6
+ import time
7
+ from model.pipeline.data_preparation import DataPrep
8
+ from model.synthesizer.ctabgan_synthesizer import CTABGANSynthesizer
9
+
10
+ import warnings
11
+
12
+ warnings.filterwarnings("ignore")
13
+
14
+ class CTABGAN():
15
+
16
+ def __init__(self,
17
+ df,
18
+ test_ratio = 0.20,
19
+ categorical_columns = [ 'workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'gender', 'native-country', 'income'],
20
+ log_columns = [],
21
+ mixed_columns= {'capital-loss':[0.0],'capital-gain':[0.0]},
22
+ general_columns = ["age"],
23
+ non_categorical_columns = [],
24
+ integer_columns = ['age', 'fnlwgt','capital-gain', 'capital-loss','hours-per-week'],
25
+ problem_type= {"Classification": "income"},
26
+ class_dim=(256, 256, 256, 256),
27
+ random_dim=100,
28
+ num_channels=64,
29
+ l2scale=1e-5,
30
+ batch_size=500,
31
+ epochs=150,
32
+ device="cpu"):
33
+
34
+ self.__name__ = 'CTABGAN'
35
+
36
+ self.synthesizer = CTABGANSynthesizer(
37
+ class_dim=class_dim,
38
+ random_dim=random_dim,
39
+ num_channels=num_channels,
40
+ l2scale=l2scale,
41
+ batch_size=batch_size,
42
+ epochs=epochs,
43
+ device=device
44
+ )
45
+ self.raw_df = df
46
+ self.test_ratio = test_ratio
47
+ self.categorical_columns = categorical_columns
48
+ self.log_columns = log_columns
49
+ self.mixed_columns = mixed_columns
50
+ self.general_columns = general_columns
51
+ self.non_categorical_columns = non_categorical_columns
52
+ self.integer_columns = integer_columns
53
+ self.problem_type = problem_type
54
+
55
+ def fit(self):
56
+
57
+ start_time = time.time()
58
+ self.data_prep = DataPrep(self.raw_df,self.categorical_columns,self.log_columns,self.mixed_columns,self.general_columns,self.non_categorical_columns,self.integer_columns,self.problem_type,self.test_ratio)
59
+ self.synthesizer.fit(train_data=self.data_prep.df, categorical = self.data_prep.column_types["categorical"], mixed = self.data_prep.column_types["mixed"],
60
+ general = self.data_prep.column_types["general"], non_categorical = self.data_prep.column_types["non_categorical"], type=self.problem_type)
61
+ end_time = time.time()
62
+ print('Finished training in',end_time-start_time," seconds.")
63
+
64
+
65
+ def generate_samples(self, seed=0):
66
+
67
+ sample = self.synthesizer.sample(len(self.raw_df), seed)
68
+ sample_df = self.data_prep.inverse_prep(sample)
69
+
70
+ return sample_df
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/eval/evaluation.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn import metrics
4
+ from sklearn import model_selection
5
+ from sklearn.preprocessing import MinMaxScaler,StandardScaler
6
+ from sklearn.neural_network import MLPClassifier
7
+ from sklearn.linear_model import LogisticRegression
8
+ from sklearn import svm,tree
9
+ from sklearn.ensemble import RandomForestClassifier
10
+ from dython.nominal import compute_associations
11
+ from scipy.stats import wasserstein_distance
12
+ from scipy.spatial import distance
13
+ import warnings
14
+
15
+ warnings.filterwarnings("ignore")
16
+
17
+ def supervised_model_training(x_train, y_train, x_test,
18
+ y_test, model_name):
19
+
20
+
21
+ if model_name == 'lr':
22
+ model = LogisticRegression(random_state=42,max_iter=500)
23
+ elif model_name == 'svm':
24
+ model = svm.SVC(random_state=42,probability=True)
25
+ elif model_name == 'dt':
26
+ model = tree.DecisionTreeClassifier(random_state=42)
27
+ elif model_name == 'rf':
28
+ model = RandomForestClassifier(random_state=42)
29
+ elif model_name == "mlp":
30
+ model = MLPClassifier(random_state=42,max_iter=100)
31
+
32
+ model.fit(x_train, y_train)
33
+ pred = model.predict(x_test)
34
+
35
+ if len(np.unique(y_train))>2:
36
+ predict = model.predict_proba(x_test)
37
+ acc = metrics.accuracy_score(y_test,pred)*100
38
+ auc = metrics.roc_auc_score(y_test, predict,average="weighted",multi_class="ovr")
39
+ f1_score = metrics.precision_recall_fscore_support(y_test, pred,average="weighted")[2]
40
+ return [acc, auc,f1_score]
41
+
42
+ else:
43
+ predict = model.predict_proba(x_test)[:,1]
44
+ acc = metrics.accuracy_score(y_test,pred)*100
45
+ auc = metrics.roc_auc_score(y_test, predict)
46
+ f1_score = metrics.precision_recall_fscore_support(y_test,pred)[2].mean()
47
+ return [acc, auc,f1_score]
48
+
49
+
50
+ def get_utility_metrics(real_path,fake_paths,scaler="MinMax",classifiers=["lr","dt","rf","mlp"],test_ratio=.20):
51
+
52
+ data_real = pd.read_csv(real_path).to_numpy()
53
+ data_dim = data_real.shape[1]
54
+
55
+ data_real_y = data_real[:,-1]
56
+ data_real_X = data_real[:,:data_dim-1]
57
+ X_train_real, X_test_real, y_train_real, y_test_real = model_selection.train_test_split(data_real_X ,data_real_y, test_size=test_ratio, stratify=data_real_y,random_state=42)
58
+
59
+ if scaler=="MinMax":
60
+ scaler_real = MinMaxScaler()
61
+ else:
62
+ scaler_real = StandardScaler()
63
+
64
+ scaler_real.fit(data_real_X)
65
+ X_train_real_scaled = scaler_real.transform(X_train_real)
66
+ X_test_real_scaled = scaler_real.transform(X_test_real)
67
+
68
+ all_real_results = []
69
+ for classifier in classifiers:
70
+ real_results = supervised_model_training(X_train_real_scaled,y_train_real,X_test_real_scaled,y_test_real,classifier)
71
+ all_real_results.append(real_results)
72
+
73
+ all_fake_results_avg = []
74
+
75
+ for fake_path in fake_paths:
76
+ data_fake = pd.read_csv(fake_path).to_numpy()
77
+ data_fake_y = data_fake[:,-1]
78
+ data_fake_X = data_fake[:,:data_dim-1]
79
+ X_train_fake, _ , y_train_fake, _ = model_selection.train_test_split(data_fake_X ,data_fake_y, test_size=test_ratio, stratify=data_fake_y,random_state=42)
80
+
81
+ if scaler=="MinMax":
82
+ scaler_fake = MinMaxScaler()
83
+ else:
84
+ scaler_fake = StandardScaler()
85
+
86
+ scaler_fake.fit(data_fake_X)
87
+
88
+ X_train_fake_scaled = scaler_fake.transform(X_train_fake)
89
+
90
+ all_fake_results = []
91
+ for classifier in classifiers:
92
+ fake_results = supervised_model_training(X_train_fake_scaled,y_train_fake,X_test_real_scaled,y_test_real,classifier)
93
+ all_fake_results.append(fake_results)
94
+
95
+ all_fake_results_avg.append(all_fake_results)
96
+
97
+ diff_results = np.array(all_real_results)- np.array(all_fake_results_avg).mean(axis=0)
98
+
99
+ return diff_results
100
+
101
+ def stat_sim(real_path,fake_path,cat_cols=None):
102
+
103
+ Stat_dict={}
104
+
105
+ real = pd.read_csv(real_path)
106
+ fake = pd.read_csv(fake_path)
107
+
108
+ really = real.copy()
109
+ fakey = fake.copy()
110
+
111
+ real_corr = compute_associations(real, nominal_columns=cat_cols)
112
+
113
+ fake_corr = compute_associations(fake, nominal_columns=cat_cols)
114
+
115
+ corr_dist = np.linalg.norm(real_corr - fake_corr)
116
+
117
+ cat_stat = []
118
+ num_stat = []
119
+
120
+ for column in real.columns:
121
+
122
+ if column in cat_cols:
123
+
124
+ real_pdf=(really[column].value_counts()/really[column].value_counts().sum())
125
+ fake_pdf=(fakey[column].value_counts()/fakey[column].value_counts().sum())
126
+ categories = (fakey[column].value_counts()/fakey[column].value_counts().sum()).keys().tolist()
127
+ sorted_categories = sorted(categories)
128
+
129
+ real_pdf_values = []
130
+ fake_pdf_values = []
131
+
132
+ for i in sorted_categories:
133
+ real_pdf_values.append(real_pdf[i])
134
+ fake_pdf_values.append(fake_pdf[i])
135
+
136
+ if len(real_pdf)!=len(fake_pdf):
137
+ zero_cats = set(really[column].value_counts().keys())-set(fakey[column].value_counts().keys())
138
+ for z in zero_cats:
139
+ real_pdf_values.append(real_pdf[z])
140
+ fake_pdf_values.append(0)
141
+ Stat_dict[column]=(distance.jensenshannon(real_pdf_values,fake_pdf_values, 2.0))
142
+ cat_stat.append(Stat_dict[column])
143
+ else:
144
+ scaler = MinMaxScaler()
145
+ scaler.fit(real[column].values.reshape(-1,1))
146
+ l1 = scaler.transform(real[column].values.reshape(-1,1)).flatten()
147
+ l2 = scaler.transform(fake[column].values.reshape(-1,1)).flatten()
148
+ Stat_dict[column]= (wasserstein_distance(l1,l2))
149
+ num_stat.append(Stat_dict[column])
150
+
151
+ return [np.mean(num_stat),np.mean(cat_stat),corr_dist]
152
+
153
+ def privacy_metrics(real_path,fake_path,data_percent=15):
154
+
155
+ real = pd.read_csv(real_path).drop_duplicates(keep=False)
156
+ fake = pd.read_csv(fake_path).drop_duplicates(keep=False)
157
+
158
+ real_refined = real.sample(n=int(len(real)*(.01*data_percent)), random_state=42).to_numpy()
159
+ fake_refined = fake.sample(n=int(len(fake)*(.01*data_percent)), random_state=42).to_numpy()
160
+
161
+ scalerR = StandardScaler()
162
+ scalerR.fit(real_refined)
163
+ scalerF = StandardScaler()
164
+ scalerF.fit(fake_refined)
165
+ df_real_scaled = scalerR.transform(real_refined)
166
+ df_fake_scaled = scalerF.transform(fake_refined)
167
+
168
+ dist_rf = metrics.pairwise_distances(df_real_scaled, Y=df_fake_scaled, metric='minkowski', n_jobs=-1)
169
+ dist_rr = metrics.pairwise_distances(df_real_scaled, Y=None, metric='minkowski', n_jobs=-1)
170
+ rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1)
171
+ dist_ff = metrics.pairwise_distances(df_fake_scaled, Y=None, metric='minkowski', n_jobs=-1)
172
+ rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1)
173
+ smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))]
174
+ smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))]
175
+ smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))]
176
+ smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))]
177
+ smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))]
178
+ smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))]
179
+ nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr])
180
+ nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff])
181
+ nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf])
182
+ nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5)
183
+ nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5)
184
+ nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5)
185
+
186
+ min_dist_rf = np.array([i[0] for i in smallest_two_rf])
187
+ fifth_perc_rf = np.percentile(min_dist_rf,5)
188
+ min_dist_rr = np.array([i[0] for i in smallest_two_rr])
189
+ fifth_perc_rr = np.percentile(min_dist_rr,5)
190
+ min_dist_ff = np.array([i[0] for i in smallest_two_ff])
191
+ fifth_perc_ff = np.percentile(min_dist_ff,5)
192
+
193
+ return np.array([fifth_perc_rf,fifth_perc_rr,fifth_perc_ff,nn_fifth_perc_rf,nn_fifth_perc_rr,nn_fifth_perc_ff]).reshape(1,6)
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/pipeline/data_preparation.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ from sklearn import preprocessing
4
+ from sklearn import model_selection
5
+
6
+ class DataPrep(object):
7
+
8
+ def __init__(self, raw_df: pd.DataFrame, categorical: list, log:list, mixed:dict, general:list, non_categorical:list, integer:list, type:dict, test_ratio:float):
9
+
10
+
11
+ self.categorical_columns = categorical
12
+ self.log_columns = log
13
+ self.mixed_columns = mixed
14
+ self.general_columns = general
15
+ self.non_categorical_columns = non_categorical
16
+ self.integer_columns = integer
17
+ self.column_types = dict()
18
+ self.column_types["categorical"] = []
19
+ self.column_types["mixed"] = {}
20
+ self.column_types["general"] = []
21
+ self.column_types["non_categorical"] = []
22
+ self.lower_bounds = {}
23
+ self.label_encoder_list = []
24
+
25
+ target_col = list(type.values())[0]
26
+ if target_col is not None:
27
+ y_real = raw_df[target_col]
28
+ X_real = raw_df.drop(columns=[target_col])
29
+ X_train_real, _, y_train_real, _ = model_selection.train_test_split(X_real ,y_real, test_size=test_ratio, stratify=y_real,random_state=42)
30
+
31
+ X_train_real[target_col]= y_train_real
32
+
33
+ self.df = X_train_real
34
+ else:
35
+ self.df = raw_df
36
+
37
+ self.df = self.df.replace(r' ', np.nan)
38
+ self.df = self.df.fillna('empty')
39
+
40
+ all_columns= set(self.df.columns)
41
+ irrelevant_missing_columns = set(self.categorical_columns)
42
+ relevant_missing_columns = list(all_columns - irrelevant_missing_columns)
43
+
44
+ for i in relevant_missing_columns:
45
+ if i in self.log_columns:
46
+ if "empty" in list(self.df[i].values):
47
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x)
48
+ self.mixed_columns[i] = [-9999999]
49
+ elif i in list(self.mixed_columns.keys()):
50
+ if "empty" in list(self.df[i].values):
51
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x )
52
+ self.mixed_columns[i].append(-9999999)
53
+ else:
54
+ if "empty" in list(self.df[i].values):
55
+ self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x)
56
+ self.mixed_columns[i] = [-9999999]
57
+
58
+ if self.log_columns:
59
+ for log_column in self.log_columns:
60
+ valid_indices = []
61
+ for idx,val in enumerate(self.df[log_column].values):
62
+ if val!=-9999999:
63
+ valid_indices.append(idx)
64
+ eps = 1
65
+ lower = np.min(self.df[log_column].iloc[valid_indices].values)
66
+ self.lower_bounds[log_column] = lower
67
+ if lower>0:
68
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x) if x!=-9999999 else -9999999)
69
+ elif lower == 0:
70
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x+eps) if x!=-9999999 else -9999999)
71
+ else:
72
+ self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x-lower+eps) if x!=-9999999 else -9999999)
73
+
74
+ for column_index, column in enumerate(self.df.columns):
75
+ if column in self.categorical_columns:
76
+ label_encoder = preprocessing.LabelEncoder()
77
+ self.df[column] = self.df[column].astype(str)
78
+ label_encoder.fit(self.df[column])
79
+ current_label_encoder = dict()
80
+ current_label_encoder['column'] = column
81
+ current_label_encoder['label_encoder'] = label_encoder
82
+ transformed_column = label_encoder.transform(self.df[column])
83
+ self.df[column] = transformed_column
84
+ self.label_encoder_list.append(current_label_encoder)
85
+ self.column_types["categorical"].append(column_index)
86
+
87
+ if column in self.general_columns:
88
+ self.column_types["general"].append(column_index)
89
+
90
+ if column in self.non_categorical_columns:
91
+ self.column_types["non_categorical"].append(column_index)
92
+
93
+ elif column in self.mixed_columns:
94
+ self.column_types["mixed"][column_index] = self.mixed_columns[column]
95
+
96
+ elif column in self.general_columns:
97
+ self.column_types["general"].append(column_index)
98
+
99
+
100
+ super().__init__()
101
+
102
+ def inverse_prep(self, data, eps=1):
103
+
104
+ df_sample = pd.DataFrame(data,columns=self.df.columns)
105
+
106
+ for i in range(len(self.label_encoder_list)):
107
+ le = self.label_encoder_list[i]["label_encoder"]
108
+ df_sample[self.label_encoder_list[i]["column"]] = df_sample[self.label_encoder_list[i]["column"]].astype(int)
109
+ df_sample[self.label_encoder_list[i]["column"]] = le.inverse_transform(df_sample[self.label_encoder_list[i]["column"]])
110
+
111
+ if self.log_columns:
112
+ for i in df_sample:
113
+ if i in self.log_columns:
114
+ lower_bound = self.lower_bounds[i]
115
+ if lower_bound>0:
116
+ df_sample[i].apply(lambda x: np.exp(x))
117
+ elif lower_bound==0:
118
+ df_sample[i] = df_sample[i].apply(lambda x: np.ceil(np.exp(x)-eps) if (np.exp(x)-eps) < 0 else (np.exp(x)-eps))
119
+ else:
120
+ df_sample[i] = df_sample[i].apply(lambda x: np.exp(x)-eps+lower_bound)
121
+
122
+ if self.integer_columns:
123
+ for column in self.integer_columns:
124
+ df_sample[column]= (np.round(df_sample[column].values))
125
+ df_sample[column] = df_sample[column].astype(int)
126
+
127
+ df_sample.replace(-9999999, np.nan,inplace=True)
128
+ df_sample.replace('empty', np.nan,inplace=True)
129
+
130
+ return df_sample
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/privacy_utils/rdp_accountant.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+ from __future__ import division
3
+ from __future__ import print_function
4
+
5
+ import math
6
+ import sys
7
+
8
+ import numpy as np
9
+ from scipy import special
10
+ import six
11
+
12
+ ########################
13
+ # LOG-SPACE ARITHMETIC #
14
+ ########################
15
+
16
+
17
+ def _log_add(logx, logy):
18
+ """Add two numbers in the log space."""
19
+ a, b = min(logx, logy), max(logx, logy)
20
+ if a == -np.inf: # adding 0
21
+ return b
22
+ # Use exp(a) + exp(b) = (exp(a - b) + 1) * exp(b)
23
+ return math.log1p(math.exp(a - b)) + b # log1p(x) = log(x + 1)
24
+
25
+
26
+ def _log_sub(logx, logy):
27
+ """Subtract two numbers in the log space. Answer must be non-negative."""
28
+ if logx < logy:
29
+ raise ValueError("The result of subtraction must be non-negative.")
30
+ if logy == -np.inf: # subtracting 0
31
+ return logx
32
+ if logx == logy:
33
+ return -np.inf # 0 is represented as -np.inf in the log space.
34
+
35
+ try:
36
+ # Use exp(x) - exp(y) = (exp(x - y) - 1) * exp(y).
37
+ return math.log(math.expm1(logx - logy)) + logy # expm1(x) = exp(x) - 1
38
+ except OverflowError:
39
+ return logx
40
+
41
+
42
+ def _log_print(logx):
43
+ """Pretty print."""
44
+ if logx < math.log(sys.float_info.max):
45
+ return "{}".format(math.exp(logx))
46
+ else:
47
+ return "exp({})".format(logx)
48
+
49
+
50
+ def _compute_log_a_int(q, sigma, alpha):
51
+ """Compute log(A_alpha) for integer alpha. 0 < q < 1."""
52
+ assert isinstance(alpha, six.integer_types)
53
+
54
+ # Initialize with 0 in the log space.
55
+ log_a = -np.inf
56
+
57
+ for i in range(alpha + 1):
58
+ log_coef_i = (
59
+ math.log(special.binom(alpha, i)) + i * math.log(q) +
60
+ (alpha - i) * math.log(1 - q))
61
+
62
+ s = log_coef_i + (i * i - i) / (2 * (sigma**2))
63
+ log_a = _log_add(log_a, s)
64
+
65
+ return float(log_a)
66
+
67
+
68
+ def _compute_log_a_frac(q, sigma, alpha):
69
+ """Compute log(A_alpha) for fractional alpha. 0 < q < 1."""
70
+ # The two parts of A_alpha, integrals over (-inf,z0] and [z0, +inf), are
71
+ # initialized to 0 in the log space:
72
+ log_a0, log_a1 = -np.inf, -np.inf
73
+ i = 0
74
+
75
+ z0 = sigma**2 * math.log(1 / q - 1) + .5
76
+
77
+ while True: # do ... until loop
78
+ coef = special.binom(alpha, i)
79
+ log_coef = math.log(abs(coef))
80
+ j = alpha - i
81
+
82
+ log_t0 = log_coef + i * math.log(q) + j * math.log(1 - q)
83
+ log_t1 = log_coef + j * math.log(q) + i * math.log(1 - q)
84
+
85
+ log_e0 = math.log(.5) + _log_erfc((i - z0) / (math.sqrt(2) * sigma))
86
+ log_e1 = math.log(.5) + _log_erfc((z0 - j) / (math.sqrt(2) * sigma))
87
+
88
+ log_s0 = log_t0 + (i * i - i) / (2 * (sigma**2)) + log_e0
89
+ log_s1 = log_t1 + (j * j - j) / (2 * (sigma**2)) + log_e1
90
+
91
+ if coef > 0:
92
+ log_a0 = _log_add(log_a0, log_s0)
93
+ log_a1 = _log_add(log_a1, log_s1)
94
+ else:
95
+ log_a0 = _log_sub(log_a0, log_s0)
96
+ log_a1 = _log_sub(log_a1, log_s1)
97
+
98
+ i += 1
99
+ if max(log_s0, log_s1) < -30:
100
+ break
101
+
102
+ return _log_add(log_a0, log_a1)
103
+
104
+
105
+ def _compute_log_a(q, sigma, alpha):
106
+ """Compute log(A_alpha) for any positive finite alpha."""
107
+ if float(alpha).is_integer():
108
+ return _compute_log_a_int(q, sigma, int(alpha))
109
+ else:
110
+ return _compute_log_a_frac(q, sigma, alpha)
111
+
112
+
113
+ def _log_erfc(x):
114
+ """Compute log(erfc(x)) with high accuracy for large x."""
115
+ try:
116
+ return math.log(2) + special.log_ndtr(-x * 2**.5)
117
+ except NameError:
118
+ # If log_ndtr is not available, approximate as follows:
119
+ r = special.erfc(x)
120
+ if r == 0.0:
121
+ # Using the Laurent series at infinity for the tail of the erfc function:
122
+ # erfc(x) ~ exp(-x^2-.5/x^2+.625/x^4)/(x*pi^.5)
123
+ # To verify in Mathematica:
124
+ # Series[Log[Erfc[x]] + Log[x] + Log[Pi]/2 + x^2, {x, Infinity, 6}]
125
+ return (-math.log(math.pi) / 2 - math.log(x) - x**2 - .5 * x**-2 +
126
+ .625 * x**-4 - 37. / 24. * x**-6 + 353. / 64. * x**-8)
127
+ else:
128
+ return math.log(r)
129
+
130
+
131
+ def _compute_delta(orders, rdp, eps):
132
+ """Compute delta given a list of RDP values and target epsilon.
133
+
134
+ Args:
135
+ orders: An array (or a scalar) of orders.
136
+ rdp: A list (or a scalar) of RDP guarantees.
137
+ eps: The target epsilon.
138
+
139
+ Returns:
140
+ Pair of (delta, optimal_order).
141
+
142
+ Raises:
143
+ ValueError: If input is malformed.
144
+
145
+ """
146
+ orders_vec = np.atleast_1d(orders)
147
+ rdp_vec = np.atleast_1d(rdp)
148
+
149
+ if len(orders_vec) != len(rdp_vec):
150
+ raise ValueError("Input lists must have the same length.")
151
+
152
+ deltas = np.exp((rdp_vec - eps) * (orders_vec - 1))
153
+ idx_opt = np.argmin(deltas)
154
+ return min(deltas[idx_opt], 1.), orders_vec[idx_opt]
155
+
156
+
157
+ def _compute_eps(orders, rdp, delta):
158
+ """Compute epsilon given a list of RDP values and target delta.
159
+
160
+ Args:
161
+ orders: An array (or a scalar) of orders.
162
+ rdp: A list (or a scalar) of RDP guarantees.
163
+ delta: The target delta.
164
+
165
+ Returns:
166
+ Pair of (eps, optimal_order).
167
+
168
+ Raises:
169
+ ValueError: If input is malformed.
170
+
171
+ """
172
+ orders_vec = np.atleast_1d(orders)
173
+ rdp_vec = np.atleast_1d(rdp)
174
+
175
+ if len(orders_vec) != len(rdp_vec):
176
+ raise ValueError("Input lists must have the same length.")
177
+
178
+ eps = rdp_vec - math.log(delta) / (orders_vec - 1)
179
+
180
+ idx_opt = np.nanargmin(eps) # Ignore NaNs
181
+ return eps[idx_opt], orders_vec[idx_opt]
182
+
183
+
184
+ def _compute_rdp(q, sigma, alpha):
185
+ """Compute RDP of the Sampled Gaussian mechanism at order alpha.
186
+
187
+ Args:
188
+ q: The sampling rate.
189
+ sigma: The std of the additive Gaussian noise.
190
+ alpha: The order at which RDP is computed.
191
+
192
+ Returns:
193
+ RDP at alpha, can be np.inf.
194
+ """
195
+ if q == 0:
196
+ return 0
197
+
198
+ if q == 1.:
199
+ return alpha / (2 * sigma**2)
200
+
201
+ if np.isinf(alpha):
202
+ return np.inf
203
+
204
+ return _compute_log_a(q, sigma, alpha) / (alpha - 1)
205
+
206
+
207
+ def compute_rdp(q, noise_multiplier, steps, orders):
208
+ """Compute RDP of the Sampled Gaussian Mechanism.
209
+
210
+ Args:
211
+ q: The sampling rate.
212
+ noise_multiplier: The ratio of the standard deviation of the Gaussian noise
213
+ to the l2-sensitivity of the function to which it is added.
214
+ steps: The number of steps.
215
+ orders: An array (or a scalar) of RDP orders.
216
+
217
+ Returns:
218
+ The RDPs at all orders, can be np.inf.
219
+ """
220
+ if np.isscalar(orders):
221
+ rdp = _compute_rdp(q, noise_multiplier, orders)
222
+ else:
223
+ rdp = np.array([_compute_rdp(q, noise_multiplier, order)
224
+ for order in orders])
225
+
226
+ return rdp * steps
227
+
228
+
229
+ def get_privacy_spent(orders, rdp, target_eps=None, target_delta=None):
230
+ """Compute delta (or eps) for given eps (or delta) from RDP values.
231
+
232
+ Args:
233
+ orders: An array (or a scalar) of RDP orders.
234
+ rdp: An array of RDP values. Must be of the same length as the orders list.
235
+ target_eps: If not None, the epsilon for which we compute the corresponding
236
+ delta.
237
+ target_delta: If not None, the delta for which we compute the corresponding
238
+ epsilon. Exactly one of target_eps and target_delta must be None.
239
+
240
+ Returns:
241
+ eps, delta, opt_order.
242
+
243
+ Raises:
244
+ ValueError: If target_eps and target_delta are messed up.
245
+ """
246
+ if target_eps is None and target_delta is None:
247
+ raise ValueError(
248
+ "Exactly one out of eps and delta must be None. (Both are).")
249
+
250
+ if target_eps is not None and target_delta is not None:
251
+ raise ValueError(
252
+ "Exactly one out of eps and delta must be None. (None is).")
253
+
254
+ if target_eps is not None:
255
+ delta, opt_order = _compute_delta(orders, rdp, target_eps)
256
+ return target_eps, delta, opt_order
257
+ else:
258
+ eps, opt_order = _compute_eps(orders, rdp, target_delta)
259
+ return eps, target_delta, opt_order
260
+
261
+
262
+ def compute_rdp_from_ledger(ledger, orders):
263
+ """Compute RDP of Sampled Gaussian Mechanism from ledger.
264
+
265
+ Args:
266
+ ledger: A formatted privacy ledger.
267
+ orders: An array (or a scalar) of RDP orders.
268
+
269
+ Returns:
270
+ RDP at all orders, can be np.inf.
271
+ """
272
+ total_rdp = np.zeros_like(orders, dtype=float)
273
+ for sample in ledger:
274
+ # Compute equivalent z from l2_clip_bounds and noise stddevs in sample.
275
+ # See https://arxiv.org/pdf/1812.06210.pdf for derivation of this formula.
276
+ effective_z = sum([
277
+ (q.noise_stddev / q.l2_norm_bound)**-2 for q in sample.queries])**-0.5
278
+ total_rdp += compute_rdp(
279
+ sample.selection_probability, effective_z, 1, orders)
280
+ return total_rdp
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/ctabgan_synthesizer.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import pandas as pd
3
+ import torch
4
+ import torch.utils.data
5
+ import torch.optim as optim
6
+ from torch.optim import Adam
7
+ from torch.nn import functional as F
8
+ from torch.nn import (Dropout, LeakyReLU, Linear, Module, ReLU, Sequential,
9
+ Conv2d, ConvTranspose2d, Sigmoid, init, BCELoss, CrossEntropyLoss,SmoothL1Loss,LayerNorm)
10
+ from model.synthesizer.transformer import ImageTransformer,DataTransformer
11
+ from model.privacy_utils.rdp_accountant import compute_rdp, get_privacy_spent
12
+ from tqdm import tqdm
13
+
14
+
15
+ class Classifier(Module):
16
+ def __init__(self,input_dim, dis_dims,st_ed):
17
+ super(Classifier,self).__init__()
18
+ dim = input_dim-(st_ed[1]-st_ed[0])
19
+ seq = []
20
+ self.str_end = st_ed
21
+ for item in list(dis_dims):
22
+ seq += [
23
+ Linear(dim, item),
24
+ LeakyReLU(0.2),
25
+ Dropout(0.5)
26
+ ]
27
+ dim = item
28
+
29
+ if (st_ed[1]-st_ed[0])==1:
30
+ seq += [Linear(dim, 1)]
31
+
32
+ elif (st_ed[1]-st_ed[0])==2:
33
+ seq += [Linear(dim, 1),Sigmoid()]
34
+ else:
35
+ seq += [Linear(dim,(st_ed[1]-st_ed[0]))]
36
+
37
+ self.seq = Sequential(*seq)
38
+
39
+ def forward(self, input):
40
+
41
+ label=None
42
+
43
+ if (self.str_end[1]-self.str_end[0])==1:
44
+ label = input[:, self.str_end[0]:self.str_end[1]]
45
+ else:
46
+ label = torch.argmax(input[:, self.str_end[0]:self.str_end[1]], axis=-1)
47
+
48
+ new_imp = torch.cat((input[:,:self.str_end[0]],input[:,self.str_end[1]:]),1)
49
+
50
+ if ((self.str_end[1]-self.str_end[0])==2) | ((self.str_end[1]-self.str_end[0])==1):
51
+ return self.seq(new_imp).view(-1), label
52
+ else:
53
+ return self.seq(new_imp), label
54
+
55
+ def apply_activate(data, output_info):
56
+ data_t = []
57
+ st = 0
58
+ for item in output_info:
59
+ if item[1] == 'tanh':
60
+ ed = st + item[0]
61
+ data_t.append(torch.tanh(data[:, st:ed]))
62
+ st = ed
63
+ elif item[1] == 'softmax':
64
+ ed = st + item[0]
65
+ data_t.append(F.gumbel_softmax(data[:, st:ed], tau=0.2))
66
+ st = ed
67
+ return torch.cat(data_t, dim=1)
68
+
69
+ def get_st_ed(target_col_index,output_info):
70
+ st = 0
71
+ c= 0
72
+ tc= 0
73
+
74
+ for item in output_info:
75
+ if c==target_col_index:
76
+ break
77
+ if item[1]=='tanh':
78
+ st += item[0]
79
+ if item[2] == 'yes_g':
80
+ c+=1
81
+ elif item[1] == 'softmax':
82
+ st += item[0]
83
+ c+=1
84
+ tc+=1
85
+
86
+ ed= st+output_info[tc][0]
87
+
88
+ return (st,ed)
89
+
90
+ def random_choice_prob_index_sampling(probs,col_idx):
91
+ option_list = []
92
+ for i in col_idx:
93
+ pp = probs[i]
94
+ option_list.append(np.random.choice(np.arange(len(probs[i])), p=pp))
95
+
96
+ return np.array(option_list).reshape(col_idx.shape)
97
+
98
+ def random_choice_prob_index(a, axis=1):
99
+ r = np.expand_dims(np.random.rand(a.shape[1 - axis]), axis=axis)
100
+ return (a.cumsum(axis=axis) > r).argmax(axis=axis)
101
+
102
+ def maximum_interval(output_info):
103
+ max_interval = 0
104
+ for item in output_info:
105
+ max_interval = max(max_interval, item[0])
106
+ return max_interval
107
+
108
+ class Cond(object):
109
+ def __init__(self, data, output_info):
110
+
111
+ self.model = []
112
+ st = 0
113
+ counter = 0
114
+ for item in output_info:
115
+
116
+ if item[1] == 'tanh':
117
+ st += item[0]
118
+ continue
119
+ elif item[1] == 'softmax':
120
+ ed = st + item[0]
121
+ counter += 1
122
+ self.model.append(np.argmax(data[:, st:ed], axis=-1))
123
+ st = ed
124
+
125
+ self.interval = []
126
+ self.n_col = 0
127
+ self.n_opt = 0
128
+ st = 0
129
+ self.p = np.zeros((counter, maximum_interval(output_info)))
130
+ self.p_sampling = []
131
+ for item in output_info:
132
+ if item[1] == 'tanh':
133
+ st += item[0]
134
+ continue
135
+ elif item[1] == 'softmax':
136
+ ed = st + item[0]
137
+ tmp = np.sum(data[:, st:ed], axis=0)
138
+ tmp_sampling = np.sum(data[:, st:ed], axis=0)
139
+ tmp = np.log(tmp + 1)
140
+ tmp = tmp / np.sum(tmp)
141
+ tmp_sampling = tmp_sampling / np.sum(tmp_sampling)
142
+ self.p_sampling.append(tmp_sampling)
143
+ self.p[self.n_col, :item[0]] = tmp
144
+ self.interval.append((self.n_opt, item[0]))
145
+ self.n_opt += item[0]
146
+ self.n_col += 1
147
+ st = ed
148
+
149
+ self.interval = np.asarray(self.interval)
150
+
151
+ def sample_train(self, batch):
152
+ if self.n_col == 0:
153
+ return None
154
+ batch = batch
155
+
156
+ idx = np.random.choice(np.arange(self.n_col), batch)
157
+
158
+ vec = np.zeros((batch, self.n_opt), dtype='float32')
159
+ mask = np.zeros((batch, self.n_col), dtype='float32')
160
+ mask[np.arange(batch), idx] = 1
161
+ opt1prime = random_choice_prob_index(self.p[idx])
162
+ for i in np.arange(batch):
163
+ vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1
164
+
165
+ return vec, mask, idx, opt1prime
166
+
167
+ def sample(self, batch):
168
+ if self.n_col == 0:
169
+ return None
170
+ batch = batch
171
+
172
+ idx = np.random.choice(np.arange(self.n_col), batch)
173
+
174
+ vec = np.zeros((batch, self.n_opt), dtype='float32')
175
+ opt1prime = random_choice_prob_index_sampling(self.p_sampling,idx)
176
+
177
+ for i in np.arange(batch):
178
+ vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1
179
+
180
+ return vec
181
+
182
+ def cond_loss(data, output_info, c, m):
183
+ loss = []
184
+ st = 0
185
+ st_c = 0
186
+ for item in output_info:
187
+ if item[1] == 'tanh':
188
+ st += item[0]
189
+ continue
190
+
191
+ elif item[1] == 'softmax':
192
+ ed = st + item[0]
193
+ ed_c = st_c + item[0]
194
+ tmp = F.cross_entropy(
195
+ data[:, st:ed],
196
+ torch.argmax(c[:, st_c:ed_c], dim=1),
197
+ reduction='none')
198
+ loss.append(tmp)
199
+ st = ed
200
+ st_c = ed_c
201
+
202
+ loss = torch.stack(loss, dim=1)
203
+ return (loss * m).sum() / data.size()[0]
204
+
205
+ class Sampler(object):
206
+ def __init__(self, data, output_info):
207
+ super(Sampler, self).__init__()
208
+ self.data = data
209
+ self.model = []
210
+ self.n = len(data)
211
+ st = 0
212
+ for item in output_info:
213
+ if item[1] == 'tanh':
214
+ st += item[0]
215
+ continue
216
+ elif item[1] == 'softmax':
217
+ ed = st + item[0]
218
+ tmp = []
219
+ for j in range(item[0]):
220
+ tmp.append(np.nonzero(data[:, st + j])[0])
221
+ self.model.append(tmp)
222
+ st = ed
223
+
224
+ def sample(self, n, col, opt):
225
+ if col is None:
226
+ idx = np.random.choice(np.arange(self.n), n)
227
+ return self.data[idx]
228
+ idx = []
229
+ for c, o in zip(col, opt):
230
+ idx.append(np.random.choice(self.model[c][o]))
231
+ return self.data[idx]
232
+
233
+ class Discriminator(Module):
234
+ def __init__(self, side, layers):
235
+ super(Discriminator, self).__init__()
236
+ self.side = side
237
+ info = len(layers)-2
238
+ self.seq = Sequential(*layers)
239
+ self.seq_info = Sequential(*layers[:info])
240
+
241
+ def forward(self, input):
242
+ return (self.seq(input)), self.seq_info(input)
243
+
244
+ class Generator(Module):
245
+ def __init__(self, side, layers):
246
+ super(Generator, self).__init__()
247
+ self.side = side
248
+ self.seq = Sequential(*layers)
249
+
250
+ def forward(self, input_):
251
+ return self.seq(input_)
252
+
253
+ def determine_layers_disc(side, num_channels):
254
+ assert side >= 4 and side <= 64
255
+
256
+ layer_dims = [(1, side), (num_channels, side // 2)]
257
+
258
+ while layer_dims[-1][1] > 3 and len(layer_dims) < 4:
259
+ layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2))
260
+
261
+ layerNorms = []
262
+ num_c = num_channels
263
+ num_s = side / 2
264
+ for l in range(len(layer_dims) - 1):
265
+ layerNorms.append([int(num_c), int(num_s), int(num_s)])
266
+ num_c = num_c * 2
267
+ num_s = num_s / 2
268
+
269
+ layers_D = []
270
+
271
+ for prev, curr, ln in zip(layer_dims, layer_dims[1:], layerNorms):
272
+ layers_D += [
273
+ Conv2d(prev[0], curr[0], 4, 2, 1, bias=False),
274
+ LayerNorm(ln),
275
+ LeakyReLU(0.2, inplace=True),
276
+ ]
277
+
278
+ layers_D += [Conv2d(layer_dims[-1][0], 1, layer_dims[-1][1], 1, 0), ReLU(True)]
279
+
280
+ return layers_D
281
+
282
+ def determine_layers_gen(side, random_dim, num_channels):
283
+ assert side >= 4 and side <= 64
284
+
285
+ layer_dims = [(1, side), (num_channels, side // 2)]
286
+
287
+ while layer_dims[-1][1] > 3 and len(layer_dims) < 4:
288
+ layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2))
289
+
290
+ layerNorms = []
291
+
292
+ num_c = num_channels * (2 ** (len(layer_dims) - 2))
293
+ num_s = int(side / (2 ** (len(layer_dims) - 1)))
294
+ for l in range(len(layer_dims) - 1):
295
+ layerNorms.append([int(num_c), int(num_s), int(num_s)])
296
+ num_c = num_c / 2
297
+ num_s = num_s * 2
298
+
299
+ layers_G = [ConvTranspose2d(random_dim, layer_dims[-1][0], layer_dims[-1][1], 1, 0, output_padding=0, bias=False)]
300
+
301
+ for prev, curr, ln in zip(reversed(layer_dims), reversed(layer_dims[:-1]), layerNorms):
302
+ layers_G += [LayerNorm(ln), ReLU(True), ConvTranspose2d(prev[0], curr[0], 4, 2, 1, output_padding=0, bias=True)]
303
+ return layers_G
304
+
305
+ def slerp(val, low, high):
306
+ low_norm = low/torch.norm(low, dim=1, keepdim=True)
307
+ high_norm = high/torch.norm(high, dim=1, keepdim=True)
308
+ omega = torch.acos((low_norm*high_norm).sum(1)).view(val.size(0), 1)
309
+ so = torch.sin(omega)
310
+ res = (torch.sin((1.0-val)*omega)/so)*low + (torch.sin(val*omega)/so) * high
311
+
312
+ return res
313
+
314
+ def calc_gradient_penalty_slerp(netD, real_data, fake_data, transformer, device='cpu', lambda_=10):
315
+ batchsize = real_data.shape[0]
316
+ alpha = torch.rand(batchsize, 1, device=device)
317
+ interpolates = slerp(alpha, real_data, fake_data)
318
+ interpolates = interpolates.to(device)
319
+ interpolates = transformer.transform(interpolates)
320
+ interpolates = torch.autograd.Variable(interpolates, requires_grad=True)
321
+ disc_interpolates,_ = netD(interpolates)
322
+
323
+ gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates,
324
+ grad_outputs=torch.ones(disc_interpolates.size()).to(device),
325
+ create_graph=True, retain_graph=True, only_inputs=True)[0]
326
+
327
+ gradients_norm = gradients.norm(2, dim=1)
328
+ gradient_penalty = ((gradients_norm - 1) ** 2).mean() * lambda_
329
+
330
+ return gradient_penalty
331
+
332
+ def weights_init(m):
333
+ classname = m.__class__.__name__
334
+
335
+ if classname.find('Conv') != -1:
336
+ init.normal_(m.weight.data, 0.0, 0.02)
337
+
338
+ elif classname.find('BatchNorm') != -1:
339
+ init.normal_(m.weight.data, 1.0, 0.02)
340
+ init.constant_(m.bias.data, 0)
341
+
342
+ class CTABGANSynthesizer:
343
+ def __init__(self,
344
+ class_dim=(256, 256, 256, 256),
345
+ random_dim=100,
346
+ num_channels=64,
347
+ l2scale=1e-5,
348
+ batch_size=500,
349
+ epochs=150,
350
+ device="cpu"):
351
+
352
+
353
+ self.random_dim = random_dim
354
+ self.class_dim = class_dim
355
+ self.num_channels = num_channels
356
+ self.dside = None
357
+ self.gside = None
358
+ self.l2scale = l2scale
359
+ self.batch_size = batch_size
360
+ self.epochs = epochs
361
+ self.device = torch.device(device)
362
+
363
+ def fit(self, train_data=pd.DataFrame, categorical=[], mixed={}, general=[], non_categorical=[], type={}):
364
+
365
+ problem_type = None
366
+ target_index=None
367
+ if type:
368
+ problem_type = list(type.keys())[0]
369
+ if problem_type:
370
+ target_index = train_data.columns.get_loc(type[problem_type])
371
+
372
+ self.transformer = DataTransformer(train_data=train_data, categorical_list=categorical, mixed_dict=mixed, general_list=general, non_categorical_list=non_categorical)
373
+ self.transformer.fit()
374
+ train_data = self.transformer.transform(train_data.values)
375
+ data_sampler = Sampler(train_data, self.transformer.output_info)
376
+ data_dim = self.transformer.output_dim
377
+ self.cond_generator = Cond(train_data, self.transformer.output_info)
378
+
379
+ sides = [4, 8, 16, 24, 64]
380
+ col_size_d = data_dim + self.cond_generator.n_opt
381
+ for i in sides:
382
+ if i * i >= col_size_d:
383
+ self.dside = i
384
+ break
385
+
386
+ sides = [4, 8, 16, 24, 64]
387
+ col_size_g = data_dim
388
+ for i in sides:
389
+ if i * i >= col_size_g:
390
+ self.gside = i
391
+ break
392
+
393
+
394
+ layers_G = determine_layers_gen(self.gside, self.random_dim+self.cond_generator.n_opt, self.num_channels)
395
+ layers_D = determine_layers_disc(self.dside, self.num_channels)
396
+
397
+ self.generator = Generator(self.gside, layers_G).to(self.device)
398
+ discriminator = Discriminator(self.dside, layers_D).to(self.device)
399
+ optimizer_params = dict(lr=2e-4, betas=(0.5, 0.9), eps=1e-3, weight_decay=self.l2scale)
400
+ optimizerG = Adam(self.generator.parameters(), **optimizer_params)
401
+ optimizerD = Adam(discriminator.parameters(), **optimizer_params)
402
+
403
+ st_ed = None
404
+ classifier=None
405
+ optimizerC= None
406
+ if target_index != None:
407
+ st_ed= get_st_ed(target_index,self.transformer.output_info)
408
+ classifier = Classifier(data_dim,self.class_dim,st_ed).to(self.device)
409
+ optimizerC = optim.Adam(classifier.parameters(),**optimizer_params)
410
+
411
+
412
+ self.generator.apply(weights_init)
413
+ discriminator.apply(weights_init)
414
+
415
+ self.Gtransformer = ImageTransformer(self.gside)
416
+ self.Dtransformer = ImageTransformer(self.dside)
417
+
418
+ epsilon = 0
419
+ epoch = 0
420
+ steps = 0
421
+ ci = 1
422
+
423
+ for i in tqdm(range(self.epochs)):
424
+
425
+
426
+ for _ in range(ci):
427
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
428
+ condvec = self.cond_generator.sample_train(self.batch_size)
429
+
430
+ c, m, col, opt = condvec
431
+ c = torch.from_numpy(c).to(self.device)
432
+ m = torch.from_numpy(m).to(self.device)
433
+ noisez = torch.cat([noisez, c], dim=1)
434
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
435
+
436
+ perm = np.arange(self.batch_size)
437
+ np.random.shuffle(perm)
438
+ real = data_sampler.sample(self.batch_size, col[perm], opt[perm])
439
+ c_perm = c[perm]
440
+
441
+ real = torch.from_numpy(real.astype('float32')).to(self.device)
442
+
443
+ fake = self.generator(noisez)
444
+ faket = self.Gtransformer.inverse_transform(fake)
445
+ fakeact = apply_activate(faket, self.transformer.output_info)
446
+
447
+ fake_cat = torch.cat([fakeact, c], dim=1)
448
+ real_cat = torch.cat([real, c_perm], dim=1)
449
+
450
+ real_cat_d = self.Dtransformer.transform(real_cat)
451
+ fake_cat_d = self.Dtransformer.transform(fake_cat)
452
+
453
+ optimizerD.zero_grad()
454
+
455
+ d_real,_ = discriminator(real_cat_d)
456
+
457
+
458
+ d_real = -torch.mean(d_real)
459
+ d_real.backward()
460
+
461
+
462
+ d_fake,_ = discriminator(fake_cat_d)
463
+
464
+ d_fake = torch.mean(d_fake)
465
+
466
+ d_fake.backward()
467
+
468
+ pen = calc_gradient_penalty_slerp(discriminator, real_cat, fake_cat, self.Dtransformer , self.device)
469
+
470
+ pen.backward()
471
+
472
+ optimizerD.step()
473
+
474
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
475
+
476
+ condvec = self.cond_generator.sample_train(self.batch_size)
477
+
478
+ c, m, col, opt = condvec
479
+ c = torch.from_numpy(c).to(self.device)
480
+ m = torch.from_numpy(m).to(self.device)
481
+ noisez = torch.cat([noisez, c], dim=1)
482
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
483
+
484
+ optimizerG.zero_grad()
485
+
486
+ fake = self.generator(noisez)
487
+ faket = self.Gtransformer.inverse_transform(fake)
488
+ fakeact = apply_activate(faket, self.transformer.output_info)
489
+
490
+ fake_cat = torch.cat([fakeact, c], dim=1)
491
+ fake_cat = self.Dtransformer.transform(fake_cat)
492
+
493
+ y_fake,info_fake = discriminator(fake_cat)
494
+
495
+ cross_entropy = cond_loss(faket, self.transformer.output_info, c, m)
496
+
497
+ _,info_real = discriminator(real_cat_d)
498
+
499
+
500
+ g = -torch.mean(y_fake) + cross_entropy
501
+ g.backward(retain_graph=True)
502
+ loss_mean = torch.norm(torch.mean(info_fake.view(self.batch_size,-1), dim=0) - torch.mean(info_real.view(self.batch_size,-1), dim=0), 1)
503
+ loss_std = torch.norm(torch.std(info_fake.view(self.batch_size,-1), dim=0) - torch.std(info_real.view(self.batch_size,-1), dim=0), 1)
504
+ loss_info = loss_mean + loss_std
505
+ loss_info.backward()
506
+ optimizerG.step()
507
+
508
+
509
+ if problem_type:
510
+
511
+ fake = self.generator(noisez)
512
+
513
+ faket = self.Gtransformer.inverse_transform(fake)
514
+
515
+ fakeact = apply_activate(faket, self.transformer.output_info)
516
+
517
+ real_pre, real_label = classifier(real)
518
+ fake_pre, fake_label = classifier(fakeact)
519
+
520
+ c_loss = CrossEntropyLoss()
521
+
522
+ if (st_ed[1] - st_ed[0])==1:
523
+ c_loss= SmoothL1Loss()
524
+ real_label = real_label.type_as(real_pre)
525
+ fake_label = fake_label.type_as(fake_pre)
526
+ real_label = torch.reshape(real_label,real_pre.size())
527
+ fake_label = torch.reshape(fake_label,fake_pre.size())
528
+
529
+
530
+ elif (st_ed[1] - st_ed[0])==2:
531
+ c_loss = BCELoss()
532
+ real_label = real_label.type_as(real_pre)
533
+ fake_label = fake_label.type_as(fake_pre)
534
+
535
+ loss_cc = c_loss(real_pre, real_label)
536
+ loss_cg = c_loss(fake_pre, fake_label)
537
+
538
+ optimizerG.zero_grad()
539
+ loss_cg.backward()
540
+ optimizerG.step()
541
+
542
+ optimizerC.zero_grad()
543
+ loss_cc.backward()
544
+ optimizerC.step()
545
+
546
+
547
+
548
+
549
+ @torch.no_grad()
550
+ def sample(self, n, seed=0):
551
+
552
+ torch.manual_seed(seed)
553
+ torch.cuda.manual_seed(seed)
554
+ sample_batch_size = 8092
555
+ self.generator.eval()
556
+
557
+ output_info = self.transformer.output_info
558
+ steps = n // sample_batch_size + 1
559
+
560
+ data = []
561
+
562
+ for i in range(steps):
563
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
564
+ condvec = self.cond_generator.sample(self.batch_size)
565
+ c = condvec
566
+ c = torch.from_numpy(c).to(self.device)
567
+ noisez = torch.cat([noisez, c], dim=1)
568
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
569
+
570
+ fake = self.generator(noisez)
571
+ faket = self.Gtransformer.inverse_transform(fake)
572
+ fakeact = apply_activate(faket,output_info)
573
+ data.append(fakeact.detach().cpu().numpy())
574
+
575
+ data = np.concatenate(data, axis=0)
576
+ result,resample = self.transformer.inverse_transform(data)
577
+
578
+ while len(result) < n:
579
+ data_resample = []
580
+ steps_left = resample// self.batch_size + 1
581
+
582
+ for i in range(steps_left):
583
+ noisez = torch.randn(self.batch_size, self.random_dim, device=self.device)
584
+ condvec = self.cond_generator.sample(self.batch_size)
585
+ c = condvec
586
+ c = torch.from_numpy(c).to(self.device)
587
+ noisez = torch.cat([noisez, c], dim=1)
588
+ noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1)
589
+
590
+ fake = self.generator(noisez)
591
+ faket = self.Gtransformer.inverse_transform(fake)
592
+ fakeact = apply_activate(faket, output_info)
593
+ data_resample.append(fakeact.detach().cpu().numpy())
594
+
595
+ data_resample = np.concatenate(data_resample, axis=0)
596
+
597
+ res,resample = self.transformer.inverse_transform(data_resample)
598
+ result = np.concatenate([result,res],axis=0)
599
+
600
+ return result[0:n]
601
+
syntheticSuccess/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
+
syntheticSuccess/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
syntheticSuccess/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)
syntheticSuccess/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
syntheticSuccess/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
syntheticSuccess/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
+
syntheticSuccess/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
+
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/__init__.py ADDED
File without changes
syntheticSuccess/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
syntheticSuccess/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)
syntheticSuccess/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
syntheticSuccess/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
+
syntheticSuccess/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
+
syntheticSuccess/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
syntheticSuccess/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
syntheticSuccess/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
+ ```
syntheticSuccess/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.-->
syntheticSuccess/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
+ ```
syntheticSuccess/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
syntheticSuccess/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
syntheticSuccess/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
syntheticSuccess/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
syntheticSuccess/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
syntheticSuccess/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
syntheticSuccess/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
syntheticSuccess/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>
syntheticSuccess/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
syntheticSuccess/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.
syntheticSuccess/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
+
syntheticSuccess/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
syntheticSuccess/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
syntheticSuccess/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.
syntheticSuccess/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
+ ```
syntheticSuccess/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
syntheticSuccess/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
+ )
syntheticSuccess/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()
syntheticSuccess/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)
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_sampler.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DataSampler module."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ class DataSampler(object):
7
+ """DataSampler samples the conditional vector and corresponding data for CTGAN."""
8
+
9
+ def __init__(self, data, output_info, log_frequency):
10
+ self._data = data
11
+
12
+ def is_discrete_column(column_info):
13
+ return (len(column_info) == 1
14
+ and column_info[0].activation_fn == 'softmax')
15
+
16
+ n_discrete_columns = sum(
17
+ [1 for column_info in output_info if is_discrete_column(column_info)])
18
+
19
+ self._discrete_column_matrix_st = np.zeros(
20
+ n_discrete_columns, dtype='int32')
21
+
22
+ # Store the row id for each category in each discrete column.
23
+ # For example _rid_by_cat_cols[a][b] is a list of all rows with the
24
+ # a-th discrete column equal value b.
25
+ self._rid_by_cat_cols = []
26
+
27
+ # Compute _rid_by_cat_cols
28
+ st = 0
29
+ for column_info in output_info:
30
+ if is_discrete_column(column_info):
31
+ span_info = column_info[0]
32
+ ed = st + span_info.dim
33
+
34
+ rid_by_cat = []
35
+ for j in range(span_info.dim):
36
+ rid_by_cat.append(np.nonzero(data[:, st + j])[0])
37
+ self._rid_by_cat_cols.append(rid_by_cat)
38
+ st = ed
39
+ else:
40
+ st += sum([span_info.dim for span_info in column_info])
41
+ assert st == data.shape[1]
42
+
43
+ # Prepare an interval matrix for efficiently sample conditional vector
44
+ max_category = max([
45
+ column_info[0].dim
46
+ for column_info in output_info
47
+ if is_discrete_column(column_info)
48
+ ], default=0)
49
+
50
+ self._discrete_column_cond_st = np.zeros(n_discrete_columns, dtype='int32')
51
+ self._discrete_column_n_category = np.zeros(n_discrete_columns, dtype='int32')
52
+ self._discrete_column_category_prob = np.zeros((n_discrete_columns, max_category))
53
+ self._n_discrete_columns = n_discrete_columns
54
+ self._n_categories = sum([
55
+ column_info[0].dim
56
+ for column_info in output_info
57
+ if is_discrete_column(column_info)
58
+ ])
59
+
60
+ st = 0
61
+ current_id = 0
62
+ current_cond_st = 0
63
+ for column_info in output_info:
64
+ if is_discrete_column(column_info):
65
+ span_info = column_info[0]
66
+ ed = st + span_info.dim
67
+ category_freq = np.sum(data[:, st:ed], axis=0)
68
+ if log_frequency:
69
+ category_freq = np.log(category_freq + 1)
70
+ category_prob = category_freq / np.sum(category_freq)
71
+ self._discrete_column_category_prob[current_id, :span_info.dim] = category_prob
72
+ self._discrete_column_cond_st[current_id] = current_cond_st
73
+ self._discrete_column_n_category[current_id] = span_info.dim
74
+ current_cond_st += span_info.dim
75
+ current_id += 1
76
+ st = ed
77
+ else:
78
+ st += sum([span_info.dim for span_info in column_info])
79
+
80
+ def _random_choice_prob_index(self, discrete_column_id):
81
+ probs = self._discrete_column_category_prob[discrete_column_id]
82
+ r = np.expand_dims(np.random.rand(probs.shape[0]), axis=1)
83
+ return (probs.cumsum(axis=1) > r).argmax(axis=1)
84
+
85
+ def sample_condvec(self, batch):
86
+ """Generate the conditional vector for training.
87
+
88
+ Returns:
89
+ cond (batch x #categories):
90
+ The conditional vector.
91
+ mask (batch x #discrete columns):
92
+ A one-hot vector indicating the selected discrete column.
93
+ discrete column id (batch):
94
+ Integer representation of mask.
95
+ category_id_in_col (batch):
96
+ Selected category in the selected discrete column.
97
+ """
98
+ if self._n_discrete_columns == 0:
99
+ return None
100
+
101
+ discrete_column_id = np.random.choice(
102
+ np.arange(self._n_discrete_columns), batch)
103
+
104
+ cond = np.zeros((batch, self._n_categories), dtype='float32')
105
+ mask = np.zeros((batch, self._n_discrete_columns), dtype='float32')
106
+ mask[np.arange(batch), discrete_column_id] = 1
107
+ category_id_in_col = self._random_choice_prob_index(discrete_column_id)
108
+ category_id = (self._discrete_column_cond_st[discrete_column_id] + category_id_in_col)
109
+ cond[np.arange(batch), category_id] = 1
110
+
111
+ return cond, mask, discrete_column_id, category_id_in_col
112
+
113
+ def sample_original_condvec(self, batch):
114
+ """Generate the conditional vector for generation use original frequency."""
115
+ if self._n_discrete_columns == 0:
116
+ return None
117
+
118
+ cond = np.zeros((batch, self._n_categories), dtype='float32')
119
+
120
+ for i in range(batch):
121
+ row_idx = np.random.randint(0, len(self._data))
122
+ col_idx = np.random.randint(0, self._n_discrete_columns)
123
+ matrix_st = self._discrete_column_matrix_st[col_idx]
124
+ matrix_ed = matrix_st + self._discrete_column_n_category[col_idx]
125
+ pick = np.argmax(self._data[row_idx, matrix_st:matrix_ed])
126
+ cond[i, pick + self._discrete_column_cond_st[col_idx]] = 1
127
+
128
+ return cond
129
+
130
+ def sample_data(self, n, col, opt):
131
+ """Sample data from original training data satisfying the sampled conditional vector.
132
+
133
+ Returns:
134
+ n rows of matrix data.
135
+ """
136
+ if col is None:
137
+ idx = np.random.randint(len(self._data), size=n)
138
+ return self._data[idx]
139
+
140
+ idx = []
141
+ for c, o in zip(col, opt):
142
+ idx.append(np.random.choice(self._rid_by_cat_cols[c][o]))
143
+
144
+ return self._data[idx]
145
+
146
+ def dim_cond_vec(self):
147
+ """Return the total number of categories."""
148
+ return self._n_categories
149
+
150
+ def generate_cond_from_condition_column_info(self, condition_info, batch):
151
+ """Generate the condition vector."""
152
+ vec = np.zeros((batch, self._n_categories), dtype='float32')
153
+ id_ = self._discrete_column_matrix_st[condition_info['discrete_column_id']]
154
+ id_ += condition_info['value_id']
155
+ vec[:, id_] = 1
156
+ return vec
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_transformer.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """DataTransformer module."""
2
+
3
+ from collections import namedtuple
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ from rdt.transformers import BayesGMMTransformer, OneHotEncodingTransformer
8
+
9
+ SpanInfo = namedtuple('SpanInfo', ['dim', 'activation_fn'])
10
+ ColumnTransformInfo = namedtuple(
11
+ 'ColumnTransformInfo', [
12
+ 'column_name', 'column_type', 'transform', 'output_info', 'output_dimensions'
13
+ ]
14
+ )
15
+
16
+
17
+ class DataTransformer(object):
18
+ """Data Transformer.
19
+
20
+ Model continuous columns with a BayesianGMM and normalized to a scalar [0, 1] and a vector.
21
+ Discrete columns are encoded using a scikit-learn OneHotEncoder.
22
+ """
23
+
24
+ def __init__(self, max_clusters=10, weight_threshold=0.005):
25
+ """Create a data transformer.
26
+
27
+ Args:
28
+ max_clusters (int):
29
+ Maximum number of Gaussian distributions in Bayesian GMM.
30
+ weight_threshold (float):
31
+ Weight threshold for a Gaussian distribution to be kept.
32
+ """
33
+ self._max_clusters = max_clusters
34
+ self._weight_threshold = weight_threshold
35
+
36
+ def _fit_continuous(self, data):
37
+ """Train Bayesian GMM for continuous columns.
38
+
39
+ Args:
40
+ data (pd.DataFrame):
41
+ A dataframe containing a column.
42
+
43
+ Returns:
44
+ namedtuple:
45
+ A ``ColumnTransformInfo`` object.
46
+ """
47
+ column_name = data.columns[0]
48
+ gm = BayesGMMTransformer(max_clusters=min(len(data), 10))
49
+ gm.fit(data, [column_name])
50
+ num_components = sum(gm.valid_component_indicator)
51
+
52
+ return ColumnTransformInfo(
53
+ column_name=column_name, column_type='continuous', transform=gm,
54
+ output_info=[SpanInfo(1, 'tanh'), SpanInfo(num_components, 'softmax')],
55
+ output_dimensions=1 + num_components)
56
+
57
+ def _fit_discrete(self, data):
58
+ """Fit one hot encoder for discrete column.
59
+
60
+ Args:
61
+ data (pd.DataFrame):
62
+ A dataframe containing a column.
63
+
64
+ Returns:
65
+ namedtuple:
66
+ A ``ColumnTransformInfo`` object.
67
+ """
68
+ column_name = data.columns[0]
69
+ ohe = OneHotEncodingTransformer()
70
+ ohe.fit(data, [column_name])
71
+ num_categories = len(ohe.dummies)
72
+
73
+ return ColumnTransformInfo(
74
+ column_name=column_name, column_type='discrete', transform=ohe,
75
+ output_info=[SpanInfo(num_categories, 'softmax')],
76
+ output_dimensions=num_categories)
77
+
78
+ def fit(self, raw_data, discrete_columns=()):
79
+ """Fit the ``DataTransformer``.
80
+
81
+ Fits a ``BayesGMMTransformer`` for continuous columns and a
82
+ ``OneHotEncodingTransformer`` for discrete columns.
83
+
84
+ This step also counts the #columns in matrix data and span information.
85
+ """
86
+ self.output_info_list = []
87
+ self.output_dimensions = 0
88
+ self.dataframe = True
89
+
90
+ if not isinstance(raw_data, pd.DataFrame):
91
+ self.dataframe = False
92
+ # work around for RDT issue #328 Fitting with numerical column names fails
93
+ discrete_columns = [str(column) for column in discrete_columns]
94
+ column_names = [str(num) for num in range(raw_data.shape[1])]
95
+ raw_data = pd.DataFrame(raw_data, columns=column_names)
96
+
97
+ self._column_raw_dtypes = raw_data.infer_objects().dtypes
98
+ self._column_transform_info_list = []
99
+ for column_name in raw_data.columns:
100
+ if column_name in discrete_columns:
101
+ column_transform_info = self._fit_discrete(raw_data[[column_name]])
102
+ else:
103
+ column_transform_info = self._fit_continuous(raw_data[[column_name]])
104
+
105
+ self.output_info_list.append(column_transform_info.output_info)
106
+ self.output_dimensions += column_transform_info.output_dimensions
107
+ self._column_transform_info_list.append(column_transform_info)
108
+
109
+ def _transform_continuous(self, column_transform_info, data):
110
+ column_name = data.columns[0]
111
+ data.loc[:, column_name] = data[column_name].to_numpy().flatten()
112
+ gm = column_transform_info.transform
113
+ transformed = gm.transform(data, [column_name])
114
+
115
+ # Converts the transformed data to the appropriate output format.
116
+ # The first column (ending in '.normalized') stays the same,
117
+ # but the lable encoded column (ending in '.component') is one hot encoded.
118
+ output = np.zeros((len(transformed), column_transform_info.output_dimensions))
119
+ output[:, 0] = transformed[f'{column_name}.normalized'].to_numpy()
120
+ index = transformed[f'{column_name}.component'].to_numpy().astype(int)
121
+ output[np.arange(index.size), index + 1] = 1.0
122
+
123
+ return output
124
+
125
+ def _transform_discrete(self, column_transform_info, data):
126
+ ohe = column_transform_info.transform
127
+ return ohe.transform(data).to_numpy()
128
+
129
+ def transform(self, raw_data):
130
+ """Take raw data and output a matrix data."""
131
+ if not isinstance(raw_data, pd.DataFrame):
132
+ column_names = [str(num) for num in range(raw_data.shape[1])]
133
+ raw_data = pd.DataFrame(raw_data, columns=column_names)
134
+
135
+ column_data_list = []
136
+ for column_transform_info in self._column_transform_info_list:
137
+ column_name = column_transform_info.column_name
138
+ data = raw_data[[column_name]]
139
+ if column_transform_info.column_type == 'continuous':
140
+ column_data_list.append(self._transform_continuous(column_transform_info, data))
141
+ else:
142
+ column_data_list.append(self._transform_discrete(column_transform_info, data))
143
+
144
+ return np.concatenate(column_data_list, axis=1).astype(float)
145
+
146
+ def _inverse_transform_continuous(self, column_transform_info, column_data, sigmas, st):
147
+ gm = column_transform_info.transform
148
+ data = pd.DataFrame(column_data[:, :2], columns=list(gm.get_output_types()))
149
+ data.iloc[:, 1] = np.argmax(column_data[:, 1:], axis=1)
150
+ if sigmas is not None:
151
+ selected_normalized_value = np.random.normal(data.iloc[:, 0], sigmas[st])
152
+ data.iloc[:, 0] = selected_normalized_value
153
+
154
+ return gm.reverse_transform(data, [column_transform_info.column_name])
155
+
156
+ def _inverse_transform_discrete(self, column_transform_info, column_data):
157
+ ohe = column_transform_info.transform
158
+ data = pd.DataFrame(column_data, columns=list(ohe.get_output_types()))
159
+ return ohe.reverse_transform(data)[column_transform_info.column_name]
160
+
161
+ def inverse_transform(self, data, sigmas=None):
162
+ """Take matrix data and output raw data.
163
+
164
+ Output uses the same type as input to the transform function.
165
+ Either np array or pd dataframe.
166
+ """
167
+ st = 0
168
+ recovered_column_data_list = []
169
+ column_names = []
170
+ for column_transform_info in self._column_transform_info_list:
171
+ dim = column_transform_info.output_dimensions
172
+ column_data = data[:, st:st + dim]
173
+ if column_transform_info.column_type == 'continuous':
174
+ recovered_column_data = self._inverse_transform_continuous(
175
+ column_transform_info, column_data, sigmas, st)
176
+ else:
177
+ recovered_column_data = self._inverse_transform_discrete(
178
+ column_transform_info, column_data)
179
+
180
+ recovered_column_data_list.append(recovered_column_data)
181
+ column_names.append(column_transform_info.column_name)
182
+ st += dim
183
+
184
+ recovered_data = np.column_stack(recovered_column_data_list)
185
+ recovered_data = (pd.DataFrame(recovered_data, columns=column_names)
186
+ .astype(self._column_raw_dtypes))
187
+ if not self.dataframe:
188
+ recovered_data = recovered_data.to_numpy()
189
+
190
+ return recovered_data
191
+
192
+ def convert_column_name_value_to_id(self, column_name, value):
193
+ """Get the ids of the given `column_name`."""
194
+ discrete_counter = 0
195
+ column_id = 0
196
+ for column_transform_info in self._column_transform_info_list:
197
+ if column_transform_info.column_name == column_name:
198
+ break
199
+ if column_transform_info.column_type == 'discrete':
200
+ discrete_counter += 1
201
+
202
+ column_id += 1
203
+
204
+ else:
205
+ raise ValueError(f"The column_name `{column_name}` doesn't exist in the data.")
206
+
207
+ ohe = column_transform_info.transform
208
+ data = pd.DataFrame([value], columns=[column_transform_info.column_name])
209
+ one_hot = ohe.transform(data).to_numpy()[0]
210
+ if sum(one_hot) == 0:
211
+ raise ValueError(f"The value `{value}` doesn't exist in the column `{column_name}`.")
212
+
213
+ return {
214
+ 'discrete_column_id': discrete_counter,
215
+ 'column_id': column_id,
216
+ 'value_id': np.argmax(one_hot)
217
+ }
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/demo.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Demo module."""
2
+
3
+ import pandas as pd
4
+
5
+ DEMO_URL = 'http://ctgan-data.s3.amazonaws.com/census.csv.gz'
6
+
7
+
8
+ def load_demo():
9
+ """Load the demo."""
10
+ return pd.read_csv(DEMO_URL, compression='gzip')
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Synthesizers module."""
2
+
3
+ from .ctgan import CTGANSynthesizer
4
+ from .tvae import TVAESynthesizer
5
+
6
+ __all__ = (
7
+ 'CTGANSynthesizer',
8
+ 'TVAESynthesizer'
9
+ )
10
+
11
+
12
+ def get_all_synthesizers():
13
+ return {
14
+ name: globals()[name]
15
+ for name in __all__
16
+ }
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/base.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """BaseSynthesizer module."""
2
+
3
+ import contextlib
4
+
5
+ import numpy as np
6
+ import torch
7
+
8
+
9
+ @contextlib.contextmanager
10
+ def set_random_states(random_state, set_model_random_state):
11
+ """Context manager for managing the random state.
12
+
13
+ Args:
14
+ random_state (int or tuple):
15
+ The random seed or a tuple of (numpy.random.RandomState, torch.Generator).
16
+ set_model_random_state (function):
17
+ Function to set the random state on the model.
18
+ """
19
+ original_np_state = np.random.get_state()
20
+ original_torch_state = torch.get_rng_state()
21
+
22
+ random_np_state, random_torch_state = random_state
23
+
24
+ np.random.set_state(random_np_state.get_state())
25
+ torch.set_rng_state(random_torch_state.get_state())
26
+
27
+ try:
28
+ yield
29
+ finally:
30
+ current_np_state = np.random.RandomState()
31
+ current_np_state.set_state(np.random.get_state())
32
+ current_torch_state = torch.Generator()
33
+ current_torch_state.set_state(torch.get_rng_state())
34
+ set_model_random_state((current_np_state, current_torch_state))
35
+
36
+ np.random.set_state(original_np_state)
37
+ torch.set_rng_state(original_torch_state)
38
+
39
+
40
+ def random_state(function):
41
+ """Set the random state before calling the function.
42
+
43
+ Args:
44
+ function (Callable):
45
+ The function to wrap around.
46
+ """
47
+ def wrapper(self, *args, **kwargs):
48
+ if self.random_states is None:
49
+ return function(self, *args, **kwargs)
50
+
51
+ else:
52
+ with set_random_states(self.random_states, self.set_random_state):
53
+ return function(self, *args, **kwargs)
54
+
55
+ return wrapper
56
+
57
+
58
+ class BaseSynthesizer:
59
+ """Base class for all default synthesizers of ``CTGAN``.
60
+
61
+ This should contain the save/load methods.
62
+ """
63
+
64
+ random_states = None
65
+
66
+ def save(self, path):
67
+ """Save the model in the passed `path`."""
68
+ device_backup = self._device
69
+ self.set_device(torch.device('cpu'))
70
+ torch.save(self, path)
71
+ self.set_device(device_backup)
72
+
73
+ @classmethod
74
+ def load(cls, path):
75
+ """Load the model stored in the passed `path`."""
76
+ device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
77
+ model = torch.load(path)
78
+ model.set_device(device)
79
+ return model
80
+
81
+ def set_random_state(self, random_state):
82
+ """Set the random state.
83
+
84
+ Args:
85
+ random_state (int, tuple, or None):
86
+ Either a tuple containing the (numpy.random.RandomState, torch.Generator)
87
+ or an int representing the random seed to use for both random states.
88
+ """
89
+ if random_state is None:
90
+ self.random_states = random_state
91
+ elif isinstance(random_state, int):
92
+ self.random_states = (
93
+ np.random.RandomState(seed=random_state),
94
+ torch.Generator().manual_seed(random_state),
95
+ )
96
+ elif (
97
+ isinstance(random_state, tuple) and
98
+ isinstance(random_state[0], np.random.RandomState) and
99
+ isinstance(random_state[1], torch.Generator)
100
+ ):
101
+ self.random_states = random_state
102
+ else:
103
+ raise TypeError(
104
+ f'`random_state` {random_state} expected to be an int or a tuple of '
105
+ '(`np.random.RandomState`, `torch.Generator`)')
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/ctgan.py ADDED
@@ -0,0 +1,482 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CTGANSynthesizer module."""
2
+
3
+ import warnings
4
+
5
+ import numpy as np
6
+ import pandas as pd
7
+ import torch
8
+ from packaging import version
9
+ from torch import optim
10
+ from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, functional
11
+
12
+ from ..data_sampler import DataSampler
13
+ from ..data_transformer import DataTransformer
14
+ from .base import BaseSynthesizer, random_state
15
+
16
+
17
+ class Discriminator(Module):
18
+ """Discriminator for the CTGANSynthesizer."""
19
+
20
+ def __init__(self, input_dim, discriminator_dim, pac=10):
21
+ super(Discriminator, self).__init__()
22
+ dim = input_dim * pac
23
+ self.pac = pac
24
+ self.pacdim = dim
25
+ seq = []
26
+ for item in list(discriminator_dim):
27
+ seq += [Linear(dim, item), LeakyReLU(0.2), Dropout(0.5)]
28
+ dim = item
29
+
30
+ seq += [Linear(dim, 1)]
31
+ self.seq = Sequential(*seq)
32
+
33
+ def calc_gradient_penalty(self, real_data, fake_data, device='cpu', pac=10, lambda_=10):
34
+ """Compute the gradient penalty."""
35
+ alpha = torch.rand(real_data.size(0) // pac, 1, 1, device=device)
36
+ alpha = alpha.repeat(1, pac, real_data.size(1))
37
+ alpha = alpha.view(-1, real_data.size(1))
38
+
39
+ interpolates = alpha * real_data + ((1 - alpha) * fake_data)
40
+
41
+ disc_interpolates = self(interpolates)
42
+
43
+ gradients = torch.autograd.grad(
44
+ outputs=disc_interpolates, inputs=interpolates,
45
+ grad_outputs=torch.ones(disc_interpolates.size(), device=device),
46
+ create_graph=True, retain_graph=True, only_inputs=True
47
+ )[0]
48
+
49
+ gradients_view = gradients.view(-1, pac * real_data.size(1)).norm(2, dim=1) - 1
50
+ gradient_penalty = ((gradients_view) ** 2).mean() * lambda_
51
+
52
+ return gradient_penalty
53
+
54
+ def forward(self, input_):
55
+ """Apply the Discriminator to the `input_`."""
56
+ assert input_.size()[0] % self.pac == 0
57
+ return self.seq(input_.view(-1, self.pacdim))
58
+
59
+
60
+ class Residual(Module):
61
+ """Residual layer for the CTGANSynthesizer."""
62
+
63
+ def __init__(self, i, o):
64
+ super(Residual, self).__init__()
65
+ self.fc = Linear(i, o)
66
+ self.bn = BatchNorm1d(o)
67
+ self.relu = ReLU()
68
+
69
+ def forward(self, input_):
70
+ """Apply the Residual layer to the `input_`."""
71
+ out = self.fc(input_)
72
+ out = self.bn(out)
73
+ out = self.relu(out)
74
+ return torch.cat([out, input_], dim=1)
75
+
76
+
77
+ class Generator(Module):
78
+ """Generator for the CTGANSynthesizer."""
79
+
80
+ def __init__(self, embedding_dim, generator_dim, data_dim):
81
+ super(Generator, self).__init__()
82
+ dim = embedding_dim
83
+ seq = []
84
+ for item in list(generator_dim):
85
+ seq += [Residual(dim, item)]
86
+ dim += item
87
+ seq.append(Linear(dim, data_dim))
88
+ self.seq = Sequential(*seq)
89
+
90
+ def forward(self, input_):
91
+ """Apply the Generator to the `input_`."""
92
+ data = self.seq(input_)
93
+ return data
94
+
95
+
96
+ class CTGANSynthesizer(BaseSynthesizer):
97
+ """Conditional Table GAN Synthesizer.
98
+
99
+ This is the core class of the CTGAN project, where the different components
100
+ are orchestrated together.
101
+ For more details about the process, please check the [Modeling Tabular data using
102
+ Conditional GAN](https://arxiv.org/abs/1907.00503) paper.
103
+
104
+ Args:
105
+ embedding_dim (int):
106
+ Size of the random sample passed to the Generator. Defaults to 128.
107
+ generator_dim (tuple or list of ints):
108
+ Size of the output samples for each one of the Residuals. A Residual Layer
109
+ will be created for each one of the values provided. Defaults to (256, 256).
110
+ discriminator_dim (tuple or list of ints):
111
+ Size of the output samples for each one of the Discriminator Layers. A Linear Layer
112
+ will be created for each one of the values provided. Defaults to (256, 256).
113
+ generator_lr (float):
114
+ Learning rate for the generator. Defaults to 2e-4.
115
+ generator_decay (float):
116
+ Generator weight decay for the Adam Optimizer. Defaults to 1e-6.
117
+ discriminator_lr (float):
118
+ Learning rate for the discriminator. Defaults to 2e-4.
119
+ discriminator_decay (float):
120
+ Discriminator weight decay for the Adam Optimizer. Defaults to 1e-6.
121
+ batch_size (int):
122
+ Number of data samples to process in each step.
123
+ discriminator_steps (int):
124
+ Number of discriminator updates to do for each generator update.
125
+ From the WGAN paper: https://arxiv.org/abs/1701.07875. WGAN paper
126
+ default is 5. Default used is 1 to match original CTGAN implementation.
127
+ log_frequency (boolean):
128
+ Whether to use log frequency of categorical levels in conditional
129
+ sampling. Defaults to ``True``.
130
+ verbose (boolean):
131
+ Whether to have print statements for progress results. Defaults to ``False``.
132
+ epochs (int):
133
+ Number of training epochs. Defaults to 300.
134
+ pac (int):
135
+ Number of samples to group together when applying the discriminator.
136
+ Defaults to 10.
137
+ cuda (bool):
138
+ Whether to attempt to use cuda for GPU computation.
139
+ If this is False or CUDA is not available, CPU will be used.
140
+ Defaults to ``True``.
141
+ """
142
+
143
+ def __init__(self, embedding_dim=128, generator_dim=(256, 256), discriminator_dim=(256, 256),
144
+ generator_lr=2e-4, generator_decay=1e-6, discriminator_lr=2e-4,
145
+ discriminator_decay=1e-6, batch_size=500, discriminator_steps=1,
146
+ log_frequency=True, verbose=False, epochs=300, pac=10, cuda=True):
147
+
148
+ assert batch_size % 2 == 0
149
+
150
+ self._embedding_dim = embedding_dim
151
+ self._generator_dim = generator_dim
152
+ self._discriminator_dim = discriminator_dim
153
+
154
+ self._generator_lr = generator_lr
155
+ self._generator_decay = generator_decay
156
+ self._discriminator_lr = discriminator_lr
157
+ self._discriminator_decay = discriminator_decay
158
+
159
+ self._batch_size = batch_size
160
+ self._discriminator_steps = discriminator_steps
161
+ self._log_frequency = log_frequency
162
+ self._verbose = verbose
163
+ self._epochs = epochs
164
+ self.pac = pac
165
+
166
+ if not cuda or not torch.cuda.is_available():
167
+ device = 'cpu'
168
+ elif isinstance(cuda, str):
169
+ device = cuda
170
+ else:
171
+ device = 'cuda'
172
+
173
+ self._device = torch.device(device)
174
+
175
+ self._transformer = None
176
+ self._data_sampler = None
177
+ self._generator = None
178
+
179
+ @staticmethod
180
+ def _gumbel_softmax(logits, tau=1, hard=False, eps=1e-10, dim=-1):
181
+ """Deals with the instability of the gumbel_softmax for older versions of torch.
182
+
183
+ For more details about the issue:
184
+ https://drive.google.com/file/d/1AA5wPfZ1kquaRtVruCd6BiYZGcDeNxyP/view?usp=sharing
185
+
186
+ Args:
187
+ logits […, num_features]:
188
+ Unnormalized log probabilities
189
+ tau:
190
+ Non-negative scalar temperature
191
+ hard (bool):
192
+ If True, the returned samples will be discretized as one-hot vectors,
193
+ but will be differentiated as if it is the soft sample in autograd
194
+ dim (int):
195
+ A dimension along which softmax will be computed. Default: -1.
196
+
197
+ Returns:
198
+ Sampled tensor of same shape as logits from the Gumbel-Softmax distribution.
199
+ """
200
+ if version.parse(torch.__version__) < version.parse('1.2.0'):
201
+ for i in range(10):
202
+ transformed = functional.gumbel_softmax(logits, tau=tau, hard=hard,
203
+ eps=eps, dim=dim)
204
+ if not torch.isnan(transformed).any():
205
+ return transformed
206
+ raise ValueError('gumbel_softmax returning NaN.')
207
+
208
+ return functional.gumbel_softmax(logits, tau=tau, hard=hard, eps=eps, dim=dim)
209
+
210
+ def _apply_activate(self, data):
211
+ """Apply proper activation function to the output of the generator."""
212
+ data_t = []
213
+ st = 0
214
+ for column_info in self._transformer.output_info_list:
215
+ for span_info in column_info:
216
+ if span_info.activation_fn == 'tanh':
217
+ ed = st + span_info.dim
218
+ data_t.append(torch.tanh(data[:, st:ed]))
219
+ st = ed
220
+ elif span_info.activation_fn == 'softmax':
221
+ ed = st + span_info.dim
222
+ transformed = self._gumbel_softmax(data[:, st:ed], tau=0.2)
223
+ data_t.append(transformed)
224
+ st = ed
225
+ else:
226
+ raise ValueError(f'Unexpected activation function {span_info.activation_fn}.')
227
+
228
+ return torch.cat(data_t, dim=1)
229
+
230
+ def _cond_loss(self, data, c, m):
231
+ """Compute the cross entropy loss on the fixed discrete column."""
232
+ loss = []
233
+ st = 0
234
+ st_c = 0
235
+ for column_info in self._transformer.output_info_list:
236
+ for span_info in column_info:
237
+ if len(column_info) != 1 or span_info.activation_fn != 'softmax':
238
+ # not discrete column
239
+ st += span_info.dim
240
+ else:
241
+ ed = st + span_info.dim
242
+ ed_c = st_c + span_info.dim
243
+ tmp = functional.cross_entropy(
244
+ data[:, st:ed],
245
+ torch.argmax(c[:, st_c:ed_c], dim=1),
246
+ reduction='none'
247
+ )
248
+ loss.append(tmp)
249
+ st = ed
250
+ st_c = ed_c
251
+
252
+ loss = torch.stack(loss, dim=1) # noqa: PD013
253
+
254
+ return (loss * m).sum() / data.size()[0]
255
+
256
+ def _validate_discrete_columns(self, train_data, discrete_columns):
257
+ """Check whether ``discrete_columns`` exists in ``train_data``.
258
+
259
+ Args:
260
+ train_data (numpy.ndarray or pandas.DataFrame):
261
+ Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame.
262
+ discrete_columns (list-like):
263
+ List of discrete columns to be used to generate the Conditional
264
+ Vector. If ``train_data`` is a Numpy array, this list should
265
+ contain the integer indices of the columns. Otherwise, if it is
266
+ a ``pandas.DataFrame``, this list should contain the column names.
267
+ """
268
+ if isinstance(train_data, pd.DataFrame):
269
+ invalid_columns = set(discrete_columns) - set(train_data.columns)
270
+ elif isinstance(train_data, np.ndarray):
271
+ invalid_columns = []
272
+ for column in discrete_columns:
273
+ if column < 0 or column >= train_data.shape[1]:
274
+ invalid_columns.append(column)
275
+ else:
276
+ raise TypeError('``train_data`` should be either pd.DataFrame or np.array.')
277
+
278
+ if invalid_columns:
279
+ raise ValueError(f'Invalid columns found: {invalid_columns}')
280
+
281
+ @random_state
282
+ def fit(self, train_data, discrete_columns=(), epochs=None):
283
+ """Fit the CTGAN Synthesizer models to the training data.
284
+
285
+ Args:
286
+ train_data (numpy.ndarray or pandas.DataFrame):
287
+ Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame.
288
+ discrete_columns (list-like):
289
+ List of discrete columns to be used to generate the Conditional
290
+ Vector. If ``train_data`` is a Numpy array, this list should
291
+ contain the integer indices of the columns. Otherwise, if it is
292
+ a ``pandas.DataFrame``, this list should contain the column names.
293
+ """
294
+ self._validate_discrete_columns(train_data, discrete_columns)
295
+
296
+ if epochs is None:
297
+ epochs = self._epochs
298
+ else:
299
+ warnings.warn(
300
+ ('`epochs` argument in `fit` method has been deprecated and will be removed '
301
+ 'in a future version. Please pass `epochs` to the constructor instead'),
302
+ DeprecationWarning
303
+ )
304
+
305
+ self._transformer = DataTransformer()
306
+ self._transformer.fit(train_data, discrete_columns)
307
+
308
+ train_data = self._transformer.transform(train_data)
309
+
310
+ self._data_sampler = DataSampler(
311
+ train_data,
312
+ self._transformer.output_info_list,
313
+ self._log_frequency)
314
+
315
+ data_dim = self._transformer.output_dimensions
316
+
317
+ self._generator = Generator(
318
+ self._embedding_dim + self._data_sampler.dim_cond_vec(),
319
+ self._generator_dim,
320
+ data_dim
321
+ ).to(self._device)
322
+
323
+ discriminator = Discriminator(
324
+ data_dim + self._data_sampler.dim_cond_vec(),
325
+ self._discriminator_dim,
326
+ pac=self.pac
327
+ ).to(self._device)
328
+
329
+ optimizerG = optim.Adam(
330
+ self._generator.parameters(), lr=self._generator_lr, betas=(0.5, 0.9),
331
+ weight_decay=self._generator_decay
332
+ )
333
+
334
+ optimizerD = optim.Adam(
335
+ discriminator.parameters(), lr=self._discriminator_lr,
336
+ betas=(0.5, 0.9), weight_decay=self._discriminator_decay
337
+ )
338
+
339
+ mean = torch.zeros(self._batch_size, self._embedding_dim, device=self._device)
340
+ std = mean + 1
341
+
342
+ print('CTGAN training')
343
+ steps_per_epoch = max(len(train_data) // self._batch_size, 1)
344
+ for i in range(epochs):
345
+ for n in range(self._discriminator_steps):
346
+ fakez = torch.normal(mean=mean, std=std)
347
+
348
+ condvec = self._data_sampler.sample_condvec(self._batch_size)
349
+ if condvec is None:
350
+ c1, m1, col, opt = None, None, None, None
351
+ real = self._data_sampler.sample_data(self._batch_size, col, opt)
352
+ else:
353
+ c1, m1, col, opt = condvec
354
+ c1 = torch.from_numpy(c1).to(self._device)
355
+ m1 = torch.from_numpy(m1).to(self._device)
356
+ fakez = torch.cat([fakez, c1], dim=1)
357
+
358
+ perm = np.arange(self._batch_size)
359
+ np.random.shuffle(perm)
360
+ real = self._data_sampler.sample_data(
361
+ self._batch_size, col[perm], opt[perm])
362
+ c2 = c1[perm]
363
+
364
+ fake = self._generator(fakez)
365
+ fakeact = self._apply_activate(fake)
366
+
367
+ real = torch.from_numpy(real.astype('float32')).to(self._device)
368
+
369
+ if c1 is not None:
370
+ fake_cat = torch.cat([fakeact, c1], dim=1)
371
+ real_cat = torch.cat([real, c2], dim=1)
372
+ else:
373
+ real_cat = real
374
+ fake_cat = fakeact
375
+
376
+ y_fake = discriminator(fake_cat)
377
+ y_real = discriminator(real_cat)
378
+
379
+ pen = discriminator.calc_gradient_penalty(
380
+ real_cat, fake_cat, self._device, self.pac)
381
+ loss_d = -(torch.mean(y_real) - torch.mean(y_fake))
382
+
383
+ optimizerD.zero_grad()
384
+ pen.backward(retain_graph=True)
385
+ loss_d.backward()
386
+ optimizerD.step()
387
+
388
+ fakez = torch.normal(mean=mean, std=std)
389
+ condvec = self._data_sampler.sample_condvec(self._batch_size)
390
+
391
+ if condvec is None:
392
+ c1, m1, col, opt = None, None, None, None
393
+ else:
394
+ c1, m1, col, opt = condvec
395
+ c1 = torch.from_numpy(c1).to(self._device)
396
+ m1 = torch.from_numpy(m1).to(self._device)
397
+ fakez = torch.cat([fakez, c1], dim=1)
398
+
399
+ fake = self._generator(fakez)
400
+ fakeact = self._apply_activate(fake)
401
+
402
+ if c1 is not None:
403
+ y_fake = discriminator(torch.cat([fakeact, c1], dim=1))
404
+ else:
405
+ y_fake = discriminator(fakeact)
406
+
407
+ if condvec is None:
408
+ cross_entropy = 0
409
+ else:
410
+ cross_entropy = self._cond_loss(fake, c1, m1)
411
+
412
+ loss_g = -torch.mean(y_fake) + cross_entropy
413
+
414
+ optimizerG.zero_grad()
415
+ loss_g.backward()
416
+ optimizerG.step()
417
+
418
+ if self._verbose and (i + 1) % 1000 == 0:
419
+ print(f'Epoch {i+1}, Loss G: {loss_g.detach().cpu(): .4f},' # noqa: T001
420
+ f'Loss D: {loss_d.detach().cpu(): .4f}',
421
+ flush=True)
422
+
423
+ @random_state
424
+ def sample(self, n, condition_column=None, condition_value=None):
425
+ """Sample data similar to the training data.
426
+
427
+ Choosing a condition_column and condition_value will increase the probability of the
428
+ discrete condition_value happening in the condition_column.
429
+
430
+ Args:
431
+ n (int):
432
+ Number of rows to sample.
433
+ condition_column (string):
434
+ Name of a discrete column.
435
+ condition_value (string):
436
+ Name of the category in the condition_column which we wish to increase the
437
+ probability of happening.
438
+
439
+ Returns:
440
+ numpy.ndarray or pandas.DataFrame
441
+ """
442
+ if condition_column is not None and condition_value is not None:
443
+ condition_info = self._transformer.convert_column_name_value_to_id(
444
+ condition_column, condition_value)
445
+ global_condition_vec = self._data_sampler.generate_cond_from_condition_column_info(
446
+ condition_info, self._batch_size)
447
+ else:
448
+ global_condition_vec = None
449
+
450
+ steps = n // self._batch_size + 1
451
+ data = []
452
+ for i in range(steps):
453
+ mean = torch.zeros(self._batch_size, self._embedding_dim)
454
+ std = mean + 1
455
+ fakez = torch.normal(mean=mean, std=std).to(self._device)
456
+
457
+ if global_condition_vec is not None:
458
+ condvec = global_condition_vec.copy()
459
+ else:
460
+ condvec = self._data_sampler.sample_original_condvec(self._batch_size)
461
+
462
+ if condvec is None:
463
+ pass
464
+ else:
465
+ c1 = condvec
466
+ c1 = torch.from_numpy(c1).to(self._device)
467
+ fakez = torch.cat([fakez, c1], dim=1)
468
+
469
+ fake = self._generator(fakez)
470
+ fakeact = self._apply_activate(fake)
471
+ data.append(fakeact.detach().cpu().numpy())
472
+
473
+ data = np.concatenate(data, axis=0)
474
+ data = data[:n]
475
+
476
+ return self._transformer.inverse_transform(data)
477
+
478
+ def set_device(self, device):
479
+ """Set the `device` to be used ('GPU' or 'CPU)."""
480
+ self._device = device
481
+ if self._generator is not None:
482
+ self._generator.to(self._device)
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/tvae.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """TVAESynthesizer module."""
2
+
3
+ import numpy as np
4
+ import torch
5
+ from torch.nn import Linear, Module, Parameter, ReLU, Sequential
6
+ from torch.nn.functional import cross_entropy
7
+ from torch.optim import Adam
8
+ from torch.utils.data import DataLoader, TensorDataset
9
+
10
+ from ..data_transformer import DataTransformer
11
+ from .base import BaseSynthesizer, random_state
12
+
13
+
14
+ class Encoder(Module):
15
+ """Encoder for the TVAESynthesizer.
16
+
17
+ Args:
18
+ data_dim (int):
19
+ Dimensions of the data.
20
+ compress_dims (tuple or list of ints):
21
+ Size of each hidden layer.
22
+ embedding_dim (int):
23
+ Size of the output vector.
24
+ """
25
+
26
+ def __init__(self, data_dim, compress_dims, embedding_dim):
27
+ super(Encoder, self).__init__()
28
+ dim = data_dim
29
+ seq = []
30
+ for item in list(compress_dims):
31
+ seq += [
32
+ Linear(dim, item),
33
+ ReLU()
34
+ ]
35
+ dim = item
36
+
37
+ self.seq = Sequential(*seq)
38
+ self.fc1 = Linear(dim, embedding_dim)
39
+ self.fc2 = Linear(dim, embedding_dim)
40
+
41
+ def forward(self, input_):
42
+ """Encode the passed `input_`."""
43
+ feature = self.seq(input_)
44
+ mu = self.fc1(feature)
45
+ logvar = self.fc2(feature)
46
+ std = torch.exp(0.5 * logvar)
47
+ return mu, std, logvar
48
+
49
+
50
+ class Decoder(Module):
51
+ """Decoder for the TVAESynthesizer.
52
+
53
+ Args:
54
+ embedding_dim (int):
55
+ Size of the input vector.
56
+ decompress_dims (tuple or list of ints):
57
+ Size of each hidden layer.
58
+ data_dim (int):
59
+ Dimensions of the data.
60
+ """
61
+
62
+ def __init__(self, embedding_dim, decompress_dims, data_dim):
63
+ super(Decoder, self).__init__()
64
+ dim = embedding_dim
65
+ seq = []
66
+ for item in list(decompress_dims):
67
+ seq += [Linear(dim, item), ReLU()]
68
+ dim = item
69
+
70
+ seq.append(Linear(dim, data_dim))
71
+ self.seq = Sequential(*seq)
72
+ self.sigma = Parameter(torch.ones(data_dim) * 0.1)
73
+
74
+ def forward(self, input_):
75
+ """Decode the passed `input_`."""
76
+ return self.seq(input_), self.sigma
77
+
78
+
79
+ def _loss_function(recon_x, x, sigmas, mu, logvar, output_info, factor):
80
+ st = 0
81
+ loss = []
82
+ for column_info in output_info:
83
+ for span_info in column_info:
84
+ if span_info.activation_fn != 'softmax':
85
+ ed = st + span_info.dim
86
+ std = sigmas[st]
87
+ eq = x[:, st] - torch.tanh(recon_x[:, st])
88
+ loss.append((eq ** 2 / 2 / (std ** 2)).sum())
89
+ loss.append(torch.log(std) * x.size()[0])
90
+ st = ed
91
+
92
+ else:
93
+ ed = st + span_info.dim
94
+ loss.append(cross_entropy(
95
+ recon_x[:, st:ed], torch.argmax(x[:, st:ed], dim=-1), reduction='sum'))
96
+ st = ed
97
+
98
+ assert st == recon_x.size()[1]
99
+ KLD = -0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp())
100
+ return sum(loss) * factor / x.size()[0], KLD / x.size()[0]
101
+
102
+
103
+ class TVAESynthesizer(BaseSynthesizer):
104
+ """TVAESynthesizer."""
105
+
106
+ def __init__(
107
+ self,
108
+ embedding_dim=128,
109
+ compress_dims=(128, 128),
110
+ decompress_dims=(128, 128),
111
+ l2scale=1e-5,
112
+ batch_size=500,
113
+ epochs=300,
114
+ lr=1e-3,
115
+ loss_factor=2,
116
+ device="cuda:0"
117
+ ):
118
+ self.embedding_dim = embedding_dim
119
+ self.compress_dims = compress_dims
120
+ self.decompress_dims = decompress_dims
121
+
122
+ self.lr = lr
123
+ self.l2scale = l2scale
124
+ self.batch_size = batch_size
125
+ self.loss_factor = loss_factor
126
+ self.epochs = epochs
127
+
128
+
129
+ self._device = torch.device(device)
130
+
131
+ @random_state
132
+ def fit(self, train_data, discrete_columns=()):
133
+ """Fit the TVAE Synthesizer models to the training data.
134
+
135
+ Args:
136
+ train_data (numpy.ndarray or pandas.DataFrame):
137
+ Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame.
138
+ discrete_columns (list-like):
139
+ List of discrete columns to be used to generate the Conditional
140
+ Vector. If ``train_data`` is a Numpy array, this list should
141
+ contain the integer indices of the columns. Otherwise, if it is
142
+ a ``pandas.DataFrame``, this list should contain the column names.
143
+ """
144
+ self.transformer = DataTransformer()
145
+ self.transformer.fit(train_data, discrete_columns)
146
+ train_data = self.transformer.transform(train_data)
147
+ dataset = TensorDataset(torch.from_numpy(train_data.astype('float32')))
148
+ loader = DataLoader(dataset, batch_size=self.batch_size, shuffle=True, drop_last=False)
149
+
150
+ data_dim = self.transformer.output_dimensions
151
+ encoder = Encoder(data_dim, self.compress_dims, self.embedding_dim).to(self._device)
152
+ self.decoder = Decoder(self.embedding_dim, self.decompress_dims, data_dim).to(self._device)
153
+ optimizerAE = Adam(
154
+ list(encoder.parameters()) + list(self.decoder.parameters()),
155
+ lr=self.lr,
156
+ weight_decay=self.l2scale)
157
+ data_iter = iter(loader)
158
+ print('Training:')
159
+ for i in range(self.epochs):
160
+ try:
161
+ data = next(data_iter)
162
+ except:
163
+ data_iter = iter(loader)
164
+ data = next(data_iter)
165
+
166
+ optimizerAE.zero_grad()
167
+ real = data[0].to(self._device)
168
+ mu, std, logvar = encoder(real)
169
+ eps = torch.randn_like(std)
170
+ emb = eps * std + mu
171
+ rec, sigmas = self.decoder(emb)
172
+ loss_1, loss_2 = _loss_function(
173
+ rec, real, sigmas, mu, logvar,
174
+ self.transformer.output_info_list, self.loss_factor
175
+ )
176
+ loss = loss_1 + loss_2
177
+ loss.backward()
178
+ optimizerAE.step()
179
+ self.decoder.sigma.data.clamp_(0.01, 1.0)
180
+ if (i + 1) % 1000 == 0:
181
+ print(f"{i + 1}/{self.epochs} {loss}", flush=True)
182
+
183
+ @random_state
184
+ def sample(self, samples, seed=0):
185
+ """Sample data similar to the training data.
186
+
187
+ Args:
188
+ samples (int):
189
+ Number of rows to sample.
190
+
191
+ Returns:
192
+ numpy.ndarray or pandas.DataFrame
193
+ """
194
+
195
+ torch.cuda.manual_seed(seed)
196
+ torch.manual_seed(seed)
197
+
198
+ self.decoder.eval()
199
+
200
+ sample_batch_size = 8092
201
+ steps = samples // sample_batch_size + 1
202
+ data = []
203
+ for _ in range(steps):
204
+ mean = torch.zeros(sample_batch_size, self.embedding_dim)
205
+ std = mean + 1
206
+ noise = torch.normal(mean=mean, std=std).to(self._device)
207
+ fake, sigmas = self.decoder(noise)
208
+ fake = torch.tanh(fake)
209
+ data.append(fake.detach().cpu().numpy())
210
+
211
+ data = np.concatenate(data, axis=0)
212
+ data = data[:samples]
213
+ return self.transformer.inverse_transform(data, sigmas.detach().cpu().numpy())
214
+
215
+ def set_device(self, device):
216
+ """Set the `device` to be used ('GPU' or 'CPU)."""
217
+ self._device = device
218
+ self.decoder.to(self._device)
syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.cfg ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [bumpversion]
2
+ current_version = 0.5.2.dev0
3
+ commit = True
4
+ tag = True
5
+ parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\.(?P<release>[a-z]+)(?P<candidate>\d+))?
6
+ serialize =
7
+ {major}.{minor}.{patch}.{release}{candidate}
8
+ {major}.{minor}.{patch}
9
+
10
+ [bumpversion:part:release]
11
+ optional_value = release
12
+ first_value = dev
13
+ values =
14
+ dev
15
+ release
16
+
17
+ [bumpversion:part:candidate]
18
+
19
+ [bumpversion:file:setup.py]
20
+ search = version='{current_version}'
21
+ replace = version='{new_version}'
22
+
23
+ [bumpversion:file:ctgan/__init__.py]
24
+ search = __version__ = '{current_version}'
25
+ replace = __version__ = '{new_version}'
26
+
27
+ [bumpversion:file:conda/meta.yaml]
28
+ search = version = '{current_version}'
29
+ replace = version = '{new_version}'
30
+
31
+ [bdist_wheel]
32
+ universal = 1
33
+
34
+ [flake8]
35
+ convention = google
36
+ max-line-length = 99
37
+ exclude = docs, .tox, .git, __pycache__, .ipynb_checkpoints
38
+ extend-ignore = D107, # Missing docstring in __init__
39
+ D407, # Missing dashed underline after section
40
+ D417, # Missing argument descriptions in the docstring
41
+ SFS3, # String literal formatting using f-string.
42
+ VNE001 # Single letter variable names are not allowed
43
+ per-file-ignores =
44
+ ctgan/data.py:T001
45
+
46
+ [isort]
47
+ include_trailing_comment = True
48
+ line_length = 99
49
+ lines_between_types = 0
50
+ multi_line_output = 4
51
+ not_skip = __init__.py
52
+ use_parentheses = True
53
+
54
+ [aliases]
55
+ test = pytest
56
+
57
+ [tool:pytest]
58
+ collect_ignore = ['setup.py']
59
+