diff --git a/.gitattributes b/.gitattributes index 1f85e486686406325517e581cc20e17d1d88c9fd..284678aa261e24dfdfb961905d67aa782a701899 100644 --- a/.gitattributes +++ b/.gitattributes @@ -4774,3 +4774,4 @@ SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/tabular_bundle/pipe SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/tabular_bundle/pipeline_ds/y_val.npy filter=lfs diff=lfs merge=lfs -text SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/train_20260420_063042.log filter=lfs diff=lfs merge=lfs -text SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/columns.json filter=lfs diff=lfs merge=lfs -text +SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json filter=lfs diff=lfs merge=lfs -text diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/transformer.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..ddad92266dc6d8b47e9ea1f4b4528795b9126e7d --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/transformer.py @@ -0,0 +1,429 @@ +import numpy as np +import pandas as pd +import torch +from sklearn.mixture import BayesianGaussianMixture + +class DataTransformer(): + + def __init__(self, train_data=pd.DataFrame, categorical_list=[], mixed_dict={}, general_list=[], non_categorical_list=[], n_clusters=10, eps=0.005): + self.meta = None + self.n_clusters = n_clusters + self.eps = eps + self.train_data = train_data + self.categorical_columns= categorical_list + self.mixed_columns= mixed_dict + self.general_columns = general_list + self.non_categorical_columns= non_categorical_list + + def get_metadata(self): + + meta = [] + + for index in range(self.train_data.shape[1]): + column = self.train_data.iloc[:,index] + if index in self.categorical_columns: + if index in self.non_categorical_columns: + meta.append({ + "name": index, + "type": "continuous", + "min": column.min(), + "max": column.max(), + }) + else: + mapper = column.value_counts().index.tolist() + meta.append({ + "name": index, + "type": "categorical", + "size": len(mapper), + "i2s": mapper + }) + + elif index in self.mixed_columns.keys(): + meta.append({ + "name": index, + "type": "mixed", + "min": column.min(), + "max": column.max(), + "modal": self.mixed_columns[index] + }) + else: + meta.append({ + "name": index, + "type": "continuous", + "min": column.min(), + "max": column.max(), + }) + + return meta + + def fit(self): + data = self.train_data.values + self.meta = self.get_metadata() + model = [] + self.ordering = [] + self.output_info = [] + self.output_dim = 0 + self.components = [] + self.filter_arr = [] + for id_, info in enumerate(self.meta): + if info['type'] == "continuous": + if id_ not in self.general_columns: + gm = BayesianGaussianMixture( + n_components = self.n_clusters, + weight_concentration_prior_type='dirichlet_process', + weight_concentration_prior=0.001, + max_iter=100,n_init=1, random_state=42) + gm.fit(data[:, id_].reshape([-1, 1])) + mode_freq = (pd.Series(gm.predict(data[:, id_].reshape([-1, 1]))).value_counts().keys()) + model.append(gm) + old_comp = gm.weights_ > self.eps + comp = [] + for i in range(self.n_clusters): + if (i in (mode_freq)) & old_comp[i]: + comp.append(True) + else: + comp.append(False) + self.components.append(comp) + self.output_info += [(1, 'tanh','no_g'), (np.sum(comp), 'softmax')] + self.output_dim += 1 + np.sum(comp) + else: + model.append(None) + self.components.append(None) + self.output_info += [(1, 'tanh','yes_g')] + self.output_dim += 1 + + elif info['type'] == "mixed": + + gm1 = BayesianGaussianMixture( + n_components = self.n_clusters, + weight_concentration_prior_type='dirichlet_process', + weight_concentration_prior=0.001, max_iter=100, + n_init=1,random_state=42) + gm2 = BayesianGaussianMixture( + n_components = self.n_clusters, + weight_concentration_prior_type='dirichlet_process', + weight_concentration_prior=0.001, max_iter=100, + n_init=1,random_state=42) + + gm1.fit(data[:, id_].reshape([-1, 1])) + + filter_arr = [] + for element in data[:, id_]: + if element not in info['modal']: + filter_arr.append(True) + else: + filter_arr.append(False) + + gm2.fit(data[:, id_][filter_arr].reshape([-1, 1])) + mode_freq = (pd.Series(gm2.predict(data[:, id_][filter_arr].reshape([-1, 1]))).value_counts().keys()) + self.filter_arr.append(filter_arr) + model.append((gm1,gm2)) + + old_comp = gm2.weights_ > self.eps + + comp = [] + + for i in range(self.n_clusters): + if (i in (mode_freq)) & old_comp[i]: + comp.append(True) + else: + comp.append(False) + + self.components.append(comp) + + self.output_info += [(1, 'tanh',"no_g"), (np.sum(comp) + len(info['modal']), 'softmax')] + self.output_dim += 1 + np.sum(comp) + len(info['modal']) + else: + model.append(None) + self.components.append(None) + self.output_info += [(info['size'], 'softmax')] + self.output_dim += info['size'] + self.model = model + + def transform(self, data, ispositive = False, positive_list = None): + values = [] + mixed_counter = 0 + for id_, info in enumerate(self.meta): + current = data[:, id_] + if info['type'] == "continuous": + if id_ not in self.general_columns: + current = current.reshape([-1, 1]) + means = self.model[id_].means_.reshape((1, self.n_clusters)) + stds = np.sqrt(self.model[id_].covariances_).reshape((1, self.n_clusters)) + features = np.empty(shape=(len(current),self.n_clusters)) + if ispositive == True: + if id_ in positive_list: + features = np.abs(current - means) / (4 * stds) + else: + features = (current - means) / (4 * stds) + + probs = self.model[id_].predict_proba(current.reshape([-1, 1])) + n_opts = sum(self.components[id_]) + features = features[:, self.components[id_]] + probs = probs[:, self.components[id_]] + + opt_sel = np.zeros(len(data), dtype='int') + for i in range(len(data)): + pp = probs[i] + 1e-6 + pp = pp / sum(pp) + opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp) + + idx = np.arange((len(features))) + features = features[idx, opt_sel].reshape([-1, 1]) + features = np.clip(features, -.99, .99) + probs_onehot = np.zeros_like(probs) + probs_onehot[np.arange(len(probs)), opt_sel] = 1 + + re_ordered_phot = np.zeros_like(probs_onehot) + + col_sums = probs_onehot.sum(axis=0) + + + n = probs_onehot.shape[1] + largest_indices = np.argsort(-1*col_sums)[:n] + self.ordering.append(largest_indices) + for id,val in enumerate(largest_indices): + re_ordered_phot[:,id] = probs_onehot[:,val] + + + values += [features, re_ordered_phot] + + else: + + self.ordering.append(None) + + if id_ in self.non_categorical_columns: + info['min'] = -1e-3 + info['max'] = info['max'] + 1e-3 + + current = (current - (info['min'])) / (info['max'] - info['min']) + current = current * 2 - 1 + current = current.reshape([-1, 1]) + values.append(current) + + elif info['type'] == "mixed": + + means_0 = self.model[id_][0].means_.reshape([-1]) + stds_0 = np.sqrt(self.model[id_][0].covariances_).reshape([-1]) + + zero_std_list = [] + means_needed = [] + stds_needed = [] + + for mode in info['modal']: + if mode!=-9999999: + dist = [] + for idx,val in enumerate(list(means_0.flatten())): + dist.append(abs(mode-val)) + index_min = np.argmin(np.array(dist)) + zero_std_list.append(index_min) + else: continue + + for idx in zero_std_list: + means_needed.append(means_0[idx]) + stds_needed.append(stds_0[idx]) + + + mode_vals = [] + + for i,j,k in zip(info['modal'],means_needed,stds_needed): + this_val = np.abs(i - j) / (4*k) + mode_vals.append(this_val) + + if -9999999 in info["modal"]: + mode_vals.append(0) + + current = current.reshape([-1, 1]) + filter_arr = self.filter_arr[mixed_counter] + current = current[filter_arr] + + means = self.model[id_][1].means_.reshape((1, self.n_clusters)) + stds = np.sqrt(self.model[id_][1].covariances_).reshape((1, self.n_clusters)) + features = np.empty(shape=(len(current),self.n_clusters)) + if ispositive == True: + if id_ in positive_list: + features = np.abs(current - means) / (4 * stds) + else: + features = (current - means) / (4 * stds) + + probs = self.model[id_][1].predict_proba(current.reshape([-1, 1])) + + n_opts = sum(self.components[id_]) # 8 + features = features[:, self.components[id_]] + probs = probs[:, self.components[id_]] + + opt_sel = np.zeros(len(current), dtype='int') + for i in range(len(current)): + pp = probs[i] + 1e-6 + pp = pp / sum(pp) + opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp) + idx = np.arange((len(features))) + features = features[idx, opt_sel].reshape([-1, 1]) + features = np.clip(features, -.99, .99) + probs_onehot = np.zeros_like(probs) + probs_onehot[np.arange(len(probs)), opt_sel] = 1 + extra_bits = np.zeros([len(current), len(info['modal'])]) + temp_probs_onehot = np.concatenate([extra_bits,probs_onehot], axis = 1) + final = np.zeros([len(data), 1 + probs_onehot.shape[1] + len(info['modal'])]) + features_curser = 0 + for idx, val in enumerate(data[:, id_]): + if val in info['modal']: + category_ = list(map(info['modal'].index, [val]))[0] + final[idx, 0] = mode_vals[category_] + final[idx, (category_+1)] = 1 + + else: + final[idx, 0] = features[features_curser] + final[idx, (1+len(info['modal'])):] = temp_probs_onehot[features_curser][len(info['modal']):] + features_curser = features_curser + 1 + + just_onehot = final[:,1:] + re_ordered_jhot= np.zeros_like(just_onehot) + n = just_onehot.shape[1] + col_sums = just_onehot.sum(axis=0) + largest_indices = np.argsort(-1*col_sums)[:n] + self.ordering.append(largest_indices) + for id,val in enumerate(largest_indices): + re_ordered_jhot[:,id] = just_onehot[:,val] + final_features = final[:,0].reshape([-1, 1]) + values += [final_features, re_ordered_jhot] + mixed_counter = mixed_counter + 1 + + else: + self.ordering.append(None) + col_t = np.zeros([len(data), info['size']]) + idx = list(map(info['i2s'].index, current)) + col_t[np.arange(len(data)), idx] = 1 + values.append(col_t) + + return np.concatenate(values, axis=1) + + def inverse_transform(self, data): + data_t = np.zeros([len(data), len(self.meta)]) + invalid_ids = [] + st = 0 + for id_, info in enumerate(self.meta): + if info['type'] == "continuous": + if id_ not in self.general_columns: + u = data[:, st] + v = data[:, st + 1:st + 1 + np.sum(self.components[id_])] + order = self.ordering[id_] + v_re_ordered = np.zeros_like(v) + + for id,val in enumerate(order): + v_re_ordered[:,val] = v[:,id] + + v = v_re_ordered + + u = np.clip(u, -1, 1) + v_t = np.ones((data.shape[0], self.n_clusters)) * -100 + v_t[:, self.components[id_]] = v + v = v_t + st += 1 + np.sum(self.components[id_]) + means = self.model[id_].means_.reshape([-1]) + stds = np.sqrt(self.model[id_].covariances_).reshape([-1]) + p_argmax = np.argmax(v, axis=1) + std_t = stds[p_argmax] + mean_t = means[p_argmax] + tmp = u * 4 * std_t + mean_t + + for idx,val in enumerate(tmp): + if (val < info["min"]) | (val > info['max']): + invalid_ids.append(idx) + + if id_ in self.non_categorical_columns: + + tmp = np.round(tmp) + + data_t[:, id_] = tmp + + else: + u = data[:, st] + u = (u + 1) / 2 + u = np.clip(u, 0, 1) + u = u * (info['max'] - info['min']) + info['min'] + if id_ in self.non_categorical_columns: + data_t[:, id_] = np.round(u) + else: data_t[:, id_] = u + + st += 1 + + elif info['type'] == "mixed": + + u = data[:, st] + full_v = data[:,(st+1):(st+1)+len(info['modal'])+np.sum(self.components[id_])] + order = self.ordering[id_] + full_v_re_ordered = np.zeros_like(full_v) + + for id,val in enumerate(order): + full_v_re_ordered[:,val] = full_v[:,id] + + full_v = full_v_re_ordered + + + mixed_v = full_v[:,:len(info['modal'])] + v = full_v[:,-np.sum(self.components[id_]):] + + u = np.clip(u, -1, 1) + v_t = np.ones((data.shape[0], self.n_clusters)) * -100 + v_t[:, self.components[id_]] = v + v = np.concatenate([mixed_v,v_t], axis=1) + + st += 1 + np.sum(self.components[id_]) + len(info['modal']) + means = self.model[id_][1].means_.reshape([-1]) + stds = np.sqrt(self.model[id_][1].covariances_).reshape([-1]) + p_argmax = np.argmax(v, axis=1) + + result = np.zeros_like(u) + + for idx in range(len(data)): + if p_argmax[idx] < len(info['modal']): + argmax_value = p_argmax[idx] + result[idx] = float(list(map(info['modal'].__getitem__, [argmax_value]))[0]) + else: + std_t = stds[(p_argmax[idx]-len(info['modal']))] + mean_t = means[(p_argmax[idx]-len(info['modal']))] + result[idx] = u[idx] * 4 * std_t + mean_t + + for idx,val in enumerate(result): + if (val < info["min"]) | (val > info['max']): + invalid_ids.append(idx) + + data_t[:, id_] = result + + else: + current = data[:, st:st + info['size']] + st += info['size'] + idx = np.argmax(current, axis=1) + data_t[:, id_] = list(map(info['i2s'].__getitem__, idx)) + + + invalid_ids = np.unique(np.array(invalid_ids)) + all_ids = np.arange(0,len(data)) + valid_ids = list(set(all_ids) - set(invalid_ids)) + + return data_t[valid_ids],len(invalid_ids) + + +class ImageTransformer(): + + def __init__(self, side): + + self.height = side + + def transform(self, data): + + if self.height * self.height > len(data[0]): + + padding = torch.zeros((len(data), self.height * self.height - len(data[0]))).to(data.device) + data = torch.cat([data, padding], axis=1) + + return data.view(-1, 1, self.height, self.height) + + def inverse_transform(self, data): + + data = data.view(-1, self.height * self.height) + + return data + + diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py new file mode 100644 index 0000000000000000000000000000000000000000..a99b5d587da5f3e49b3923e43975e02e9c11e6e1 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py @@ -0,0 +1,72 @@ +""" +Generative model training algorithm based on the CTABGANSynthesiser + +""" +import pandas as pd +import time +from model.pipeline.data_preparation import DataPrep +from model.synthesizer.ctabgan_synthesizer import CTABGANSynthesizer + +import warnings + +warnings.filterwarnings("ignore") + +class CTABGAN(): + + def __init__(self, + df, + test_ratio = 0.20, + categorical_columns = [], + log_columns = [], + mixed_columns= {}, + general_columns = [], + non_categorical_columns = [], + integer_columns = [], + problem_type= {}, + class_dim=(256, 256, 256, 256), + random_dim=100, + num_channels=64, + l2scale=1e-5, + batch_size=500, + epochs=150, + lr=2e-4, + device="cpu"): + + self.__name__ = 'CTABGAN' + + self.synthesizer = CTABGANSynthesizer( + class_dim=class_dim, + random_dim=random_dim, + num_channels=num_channels, + l2scale=l2scale, + lr=lr, + batch_size=batch_size, + epochs=epochs, + device=device + ) + self.raw_df = df + self.test_ratio = test_ratio + self.categorical_columns = categorical_columns + self.log_columns = log_columns + self.mixed_columns = mixed_columns + self.general_columns = general_columns + self.non_categorical_columns = non_categorical_columns + self.integer_columns = integer_columns + self.problem_type = problem_type + + def fit(self): + + start_time = time.time() + 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) + self.synthesizer.fit(train_data=self.data_prep.df, categorical = self.data_prep.column_types["categorical"], mixed = self.data_prep.column_types["mixed"], + general = self.data_prep.column_types["general"], non_categorical = self.data_prep.column_types["non_categorical"], type=self.problem_type) + end_time = time.time() + print('Finished training in',end_time-start_time," seconds.") + + + def generate_samples(self, num_samples, seed=0): + + sample = self.synthesizer.sample(num_samples, seed) + sample_df = self.data_prep.inverse_prep(sample) + + return sample_df \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/eval/evaluation.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/eval/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..1492fcf80cfb907f95b3844e4c0f38f15effbdb0 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/eval/evaluation.py @@ -0,0 +1,193 @@ +import numpy as np +import pandas as pd +from sklearn import metrics +from sklearn import model_selection +from sklearn.preprocessing import MinMaxScaler,StandardScaler +from sklearn.neural_network import MLPClassifier +from sklearn.linear_model import LogisticRegression +from sklearn import svm,tree +from sklearn.ensemble import RandomForestClassifier +from dython.nominal import compute_associations +from scipy.stats import wasserstein_distance +from scipy.spatial import distance +import warnings + +warnings.filterwarnings("ignore") + +def supervised_model_training(x_train, y_train, x_test, + y_test, model_name): + + + if model_name == 'lr': + model = LogisticRegression(random_state=42,max_iter=500) + elif model_name == 'svm': + model = svm.SVC(random_state=42,probability=True) + elif model_name == 'dt': + model = tree.DecisionTreeClassifier(random_state=42) + elif model_name == 'rf': + model = RandomForestClassifier(random_state=42) + elif model_name == "mlp": + model = MLPClassifier(random_state=42,max_iter=100) + + model.fit(x_train, y_train) + pred = model.predict(x_test) + + if len(np.unique(y_train))>2: + predict = model.predict_proba(x_test) + acc = metrics.accuracy_score(y_test,pred)*100 + auc = metrics.roc_auc_score(y_test, predict,average="weighted",multi_class="ovr") + f1_score = metrics.precision_recall_fscore_support(y_test, pred,average="weighted")[2] + return [acc, auc,f1_score] + + else: + predict = model.predict_proba(x_test)[:,1] + acc = metrics.accuracy_score(y_test,pred)*100 + auc = metrics.roc_auc_score(y_test, predict) + f1_score = metrics.precision_recall_fscore_support(y_test,pred)[2].mean() + return [acc, auc,f1_score] + + +def get_utility_metrics(real_path,fake_paths,scaler="MinMax",classifiers=["lr","dt","rf","mlp"],test_ratio=.20): + + data_real = pd.read_csv(real_path).to_numpy() + data_dim = data_real.shape[1] + + data_real_y = data_real[:,-1] + data_real_X = data_real[:,:data_dim-1] + 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) + + if scaler=="MinMax": + scaler_real = MinMaxScaler() + else: + scaler_real = StandardScaler() + + scaler_real.fit(data_real_X) + X_train_real_scaled = scaler_real.transform(X_train_real) + X_test_real_scaled = scaler_real.transform(X_test_real) + + all_real_results = [] + for classifier in classifiers: + real_results = supervised_model_training(X_train_real_scaled,y_train_real,X_test_real_scaled,y_test_real,classifier) + all_real_results.append(real_results) + + all_fake_results_avg = [] + + for fake_path in fake_paths: + data_fake = pd.read_csv(fake_path).to_numpy() + data_fake_y = data_fake[:,-1] + data_fake_X = data_fake[:,:data_dim-1] + 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) + + if scaler=="MinMax": + scaler_fake = MinMaxScaler() + else: + scaler_fake = StandardScaler() + + scaler_fake.fit(data_fake_X) + + X_train_fake_scaled = scaler_fake.transform(X_train_fake) + + all_fake_results = [] + for classifier in classifiers: + fake_results = supervised_model_training(X_train_fake_scaled,y_train_fake,X_test_real_scaled,y_test_real,classifier) + all_fake_results.append(fake_results) + + all_fake_results_avg.append(all_fake_results) + + diff_results = np.array(all_real_results)- np.array(all_fake_results_avg).mean(axis=0) + + return diff_results + +def stat_sim(real_path,fake_path,cat_cols=None): + + Stat_dict={} + + real = pd.read_csv(real_path) + fake = pd.read_csv(fake_path) + + really = real.copy() + fakey = fake.copy() + + real_corr = compute_associations(real, nominal_columns=cat_cols) + + fake_corr = compute_associations(fake, nominal_columns=cat_cols) + + corr_dist = np.linalg.norm(real_corr - fake_corr) + + cat_stat = [] + num_stat = [] + + for column in real.columns: + + if column in cat_cols: + + real_pdf=(really[column].value_counts()/really[column].value_counts().sum()) + fake_pdf=(fakey[column].value_counts()/fakey[column].value_counts().sum()) + categories = (fakey[column].value_counts()/fakey[column].value_counts().sum()).keys().tolist() + sorted_categories = sorted(categories) + + real_pdf_values = [] + fake_pdf_values = [] + + for i in sorted_categories: + real_pdf_values.append(real_pdf[i]) + fake_pdf_values.append(fake_pdf[i]) + + if len(real_pdf)!=len(fake_pdf): + zero_cats = set(really[column].value_counts().keys())-set(fakey[column].value_counts().keys()) + for z in zero_cats: + real_pdf_values.append(real_pdf[z]) + fake_pdf_values.append(0) + Stat_dict[column]=(distance.jensenshannon(real_pdf_values,fake_pdf_values, 2.0)) + cat_stat.append(Stat_dict[column]) + else: + scaler = MinMaxScaler() + scaler.fit(real[column].values.reshape(-1,1)) + l1 = scaler.transform(real[column].values.reshape(-1,1)).flatten() + l2 = scaler.transform(fake[column].values.reshape(-1,1)).flatten() + Stat_dict[column]= (wasserstein_distance(l1,l2)) + num_stat.append(Stat_dict[column]) + + return [np.mean(num_stat),np.mean(cat_stat),corr_dist] + +def privacy_metrics(real_path,fake_path,data_percent=15): + + real = pd.read_csv(real_path).drop_duplicates(keep=False) + fake = pd.read_csv(fake_path).drop_duplicates(keep=False) + + real_refined = real.sample(n=int(len(real)*(.01*data_percent)), random_state=42).to_numpy() + fake_refined = fake.sample(n=int(len(fake)*(.01*data_percent)), random_state=42).to_numpy() + + scalerR = StandardScaler() + scalerR.fit(real_refined) + scalerF = StandardScaler() + scalerF.fit(fake_refined) + df_real_scaled = scalerR.transform(real_refined) + df_fake_scaled = scalerF.transform(fake_refined) + + dist_rf = metrics.pairwise_distances(df_real_scaled, Y=df_fake_scaled, metric='minkowski', n_jobs=-1) + dist_rr = metrics.pairwise_distances(df_real_scaled, Y=None, metric='minkowski', n_jobs=-1) + rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1) + dist_ff = metrics.pairwise_distances(df_fake_scaled, Y=None, metric='minkowski', n_jobs=-1) + rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1) + smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))] + smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))] + smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))] + smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))] + smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))] + smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))] + nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr]) + nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff]) + nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf]) + nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5) + nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5) + nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5) + + min_dist_rf = np.array([i[0] for i in smallest_two_rf]) + fifth_perc_rf = np.percentile(min_dist_rf,5) + min_dist_rr = np.array([i[0] for i in smallest_two_rr]) + fifth_perc_rr = np.percentile(min_dist_rr,5) + min_dist_ff = np.array([i[0] for i in smallest_two_ff]) + fifth_perc_ff = np.percentile(min_dist_ff,5) + + 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) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/pipeline/data_preparation.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/pipeline/data_preparation.py new file mode 100644 index 0000000000000000000000000000000000000000..3f4b7293d63db51bc7c9da6c38b84c6c033d779b --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/pipeline/data_preparation.py @@ -0,0 +1,131 @@ +import numpy as np +import pandas as pd +from sklearn import preprocessing +from sklearn import model_selection + +class DataPrep(object): + + 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): + + + self.categorical_columns = categorical + self.log_columns = log + self.mixed_columns = mixed + self.general_columns = general + self.non_categorical_columns = non_categorical + self.integer_columns = integer + self.column_types = dict() + self.column_types["categorical"] = [] + self.column_types["mixed"] = {} + self.column_types["general"] = [] + self.column_types["non_categorical"] = [] + self.lower_bounds = {} + self.label_encoder_list = [] + + target_col = list(type.values())[0] + if target_col is not None: + y_real = raw_df[target_col] + X_real = raw_df.drop(columns=[target_col]) + # 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) + X_train_real, y_train_real = X_real, y_real + + X_train_real[target_col]= y_train_real + + self.df = X_train_real + else: + self.df = raw_df + + self.df = self.df.replace(r' ', np.nan) + self.df = self.df.fillna('empty') + + all_columns= set(self.df.columns) + irrelevant_missing_columns = set(self.categorical_columns) + relevant_missing_columns = list(all_columns - irrelevant_missing_columns) + + for i in relevant_missing_columns: + if i in self.log_columns: + if "empty" in list(self.df[i].values): + self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x) + self.mixed_columns[i] = [-9999999] + elif i in list(self.mixed_columns.keys()): + if "empty" in list(self.df[i].values): + self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x ) + self.mixed_columns[i].append(-9999999) + else: + if "empty" in list(self.df[i].values): + self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x) + self.mixed_columns[i] = [-9999999] + + if self.log_columns: + for log_column in self.log_columns: + valid_indices = [] + for idx,val in enumerate(self.df[log_column].values): + if val!=-9999999: + valid_indices.append(idx) + eps = 1 + lower = np.min(self.df[log_column].iloc[valid_indices].values) + self.lower_bounds[log_column] = lower + if lower>0: + self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x) if x!=-9999999 else -9999999) + elif lower == 0: + self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x+eps) if x!=-9999999 else -9999999) + else: + self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x-lower+eps) if x!=-9999999 else -9999999) + + for column_index, column in enumerate(self.df.columns): + if column in self.categorical_columns: + label_encoder = preprocessing.LabelEncoder() + self.df[column] = self.df[column].astype(str) + label_encoder.fit(self.df[column]) + current_label_encoder = dict() + current_label_encoder['column'] = column + current_label_encoder['label_encoder'] = label_encoder + transformed_column = label_encoder.transform(self.df[column]) + self.df[column] = transformed_column + self.label_encoder_list.append(current_label_encoder) + self.column_types["categorical"].append(column_index) + + if column in self.general_columns: + self.column_types["general"].append(column_index) + + if column in self.non_categorical_columns: + self.column_types["non_categorical"].append(column_index) + + elif column in self.mixed_columns: + self.column_types["mixed"][column_index] = self.mixed_columns[column] + + elif column in self.general_columns: + self.column_types["general"].append(column_index) + + + super().__init__() + + def inverse_prep(self, data, eps=1): + + df_sample = pd.DataFrame(data,columns=self.df.columns) + + for i in range(len(self.label_encoder_list)): + le = self.label_encoder_list[i]["label_encoder"] + df_sample[self.label_encoder_list[i]["column"]] = df_sample[self.label_encoder_list[i]["column"]].astype(int) + df_sample[self.label_encoder_list[i]["column"]] = le.inverse_transform(df_sample[self.label_encoder_list[i]["column"]]) + + if self.log_columns: + for i in df_sample: + if i in self.log_columns: + lower_bound = self.lower_bounds[i] + if lower_bound>0: + df_sample[i].apply(lambda x: np.exp(x)) + elif lower_bound==0: + 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)) + else: + df_sample[i] = df_sample[i].apply(lambda x: np.exp(x)-eps+lower_bound) + + if self.integer_columns: + for column in self.integer_columns: + df_sample[column]= (np.round(df_sample[column].values)) + df_sample[column] = df_sample[column].astype(int) + + df_sample.replace(-9999999, np.nan,inplace=True) + df_sample.replace('empty', np.nan,inplace=True) + + return df_sample diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/privacy_utils/rdp_accountant.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/privacy_utils/rdp_accountant.py new file mode 100644 index 0000000000000000000000000000000000000000..5e225cbb0994fa6b9e9726f38d873754bbfe82cf --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/privacy_utils/rdp_accountant.py @@ -0,0 +1,280 @@ +from __future__ import absolute_import +from __future__ import division +from __future__ import print_function + +import math +import sys + +import numpy as np +from scipy import special +import six + +######################## +# LOG-SPACE ARITHMETIC # +######################## + + +def _log_add(logx, logy): + """Add two numbers in the log space.""" + a, b = min(logx, logy), max(logx, logy) + if a == -np.inf: # adding 0 + return b + # Use exp(a) + exp(b) = (exp(a - b) + 1) * exp(b) + return math.log1p(math.exp(a - b)) + b # log1p(x) = log(x + 1) + + +def _log_sub(logx, logy): + """Subtract two numbers in the log space. Answer must be non-negative.""" + if logx < logy: + raise ValueError("The result of subtraction must be non-negative.") + if logy == -np.inf: # subtracting 0 + return logx + if logx == logy: + return -np.inf # 0 is represented as -np.inf in the log space. + + try: + # Use exp(x) - exp(y) = (exp(x - y) - 1) * exp(y). + return math.log(math.expm1(logx - logy)) + logy # expm1(x) = exp(x) - 1 + except OverflowError: + return logx + + +def _log_print(logx): + """Pretty print.""" + if logx < math.log(sys.float_info.max): + return "{}".format(math.exp(logx)) + else: + return "exp({})".format(logx) + + +def _compute_log_a_int(q, sigma, alpha): + """Compute log(A_alpha) for integer alpha. 0 < q < 1.""" + assert isinstance(alpha, six.integer_types) + + # Initialize with 0 in the log space. + log_a = -np.inf + + for i in range(alpha + 1): + log_coef_i = ( + math.log(special.binom(alpha, i)) + i * math.log(q) + + (alpha - i) * math.log(1 - q)) + + s = log_coef_i + (i * i - i) / (2 * (sigma**2)) + log_a = _log_add(log_a, s) + + return float(log_a) + + +def _compute_log_a_frac(q, sigma, alpha): + """Compute log(A_alpha) for fractional alpha. 0 < q < 1.""" + # The two parts of A_alpha, integrals over (-inf,z0] and [z0, +inf), are + # initialized to 0 in the log space: + log_a0, log_a1 = -np.inf, -np.inf + i = 0 + + z0 = sigma**2 * math.log(1 / q - 1) + .5 + + while True: # do ... until loop + coef = special.binom(alpha, i) + log_coef = math.log(abs(coef)) + j = alpha - i + + log_t0 = log_coef + i * math.log(q) + j * math.log(1 - q) + log_t1 = log_coef + j * math.log(q) + i * math.log(1 - q) + + log_e0 = math.log(.5) + _log_erfc((i - z0) / (math.sqrt(2) * sigma)) + log_e1 = math.log(.5) + _log_erfc((z0 - j) / (math.sqrt(2) * sigma)) + + log_s0 = log_t0 + (i * i - i) / (2 * (sigma**2)) + log_e0 + log_s1 = log_t1 + (j * j - j) / (2 * (sigma**2)) + log_e1 + + if coef > 0: + log_a0 = _log_add(log_a0, log_s0) + log_a1 = _log_add(log_a1, log_s1) + else: + log_a0 = _log_sub(log_a0, log_s0) + log_a1 = _log_sub(log_a1, log_s1) + + i += 1 + if max(log_s0, log_s1) < -30: + break + + return _log_add(log_a0, log_a1) + + +def _compute_log_a(q, sigma, alpha): + """Compute log(A_alpha) for any positive finite alpha.""" + if float(alpha).is_integer(): + return _compute_log_a_int(q, sigma, int(alpha)) + else: + return _compute_log_a_frac(q, sigma, alpha) + + +def _log_erfc(x): + """Compute log(erfc(x)) with high accuracy for large x.""" + try: + return math.log(2) + special.log_ndtr(-x * 2**.5) + except NameError: + # If log_ndtr is not available, approximate as follows: + r = special.erfc(x) + if r == 0.0: + # Using the Laurent series at infinity for the tail of the erfc function: + # erfc(x) ~ exp(-x^2-.5/x^2+.625/x^4)/(x*pi^.5) + # To verify in Mathematica: + # Series[Log[Erfc[x]] + Log[x] + Log[Pi]/2 + x^2, {x, Infinity, 6}] + return (-math.log(math.pi) / 2 - math.log(x) - x**2 - .5 * x**-2 + + .625 * x**-4 - 37. / 24. * x**-6 + 353. / 64. * x**-8) + else: + return math.log(r) + + +def _compute_delta(orders, rdp, eps): + """Compute delta given a list of RDP values and target epsilon. + + Args: + orders: An array (or a scalar) of orders. + rdp: A list (or a scalar) of RDP guarantees. + eps: The target epsilon. + + Returns: + Pair of (delta, optimal_order). + + Raises: + ValueError: If input is malformed. + + """ + orders_vec = np.atleast_1d(orders) + rdp_vec = np.atleast_1d(rdp) + + if len(orders_vec) != len(rdp_vec): + raise ValueError("Input lists must have the same length.") + + deltas = np.exp((rdp_vec - eps) * (orders_vec - 1)) + idx_opt = np.argmin(deltas) + return min(deltas[idx_opt], 1.), orders_vec[idx_opt] + + +def _compute_eps(orders, rdp, delta): + """Compute epsilon given a list of RDP values and target delta. + + Args: + orders: An array (or a scalar) of orders. + rdp: A list (or a scalar) of RDP guarantees. + delta: The target delta. + + Returns: + Pair of (eps, optimal_order). + + Raises: + ValueError: If input is malformed. + + """ + orders_vec = np.atleast_1d(orders) + rdp_vec = np.atleast_1d(rdp) + + if len(orders_vec) != len(rdp_vec): + raise ValueError("Input lists must have the same length.") + + eps = rdp_vec - math.log(delta) / (orders_vec - 1) + + idx_opt = np.nanargmin(eps) # Ignore NaNs + return eps[idx_opt], orders_vec[idx_opt] + + +def _compute_rdp(q, sigma, alpha): + """Compute RDP of the Sampled Gaussian mechanism at order alpha. + + Args: + q: The sampling rate. + sigma: The std of the additive Gaussian noise. + alpha: The order at which RDP is computed. + + Returns: + RDP at alpha, can be np.inf. + """ + if q == 0: + return 0 + + if q == 1.: + return alpha / (2 * sigma**2) + + if np.isinf(alpha): + return np.inf + + return _compute_log_a(q, sigma, alpha) / (alpha - 1) + + +def compute_rdp(q, noise_multiplier, steps, orders): + """Compute RDP of the Sampled Gaussian Mechanism. + + Args: + q: The sampling rate. + noise_multiplier: The ratio of the standard deviation of the Gaussian noise + to the l2-sensitivity of the function to which it is added. + steps: The number of steps. + orders: An array (or a scalar) of RDP orders. + + Returns: + The RDPs at all orders, can be np.inf. + """ + if np.isscalar(orders): + rdp = _compute_rdp(q, noise_multiplier, orders) + else: + rdp = np.array([_compute_rdp(q, noise_multiplier, order) + for order in orders]) + + return rdp * steps + + +def get_privacy_spent(orders, rdp, target_eps=None, target_delta=None): + """Compute delta (or eps) for given eps (or delta) from RDP values. + + Args: + orders: An array (or a scalar) of RDP orders. + rdp: An array of RDP values. Must be of the same length as the orders list. + target_eps: If not None, the epsilon for which we compute the corresponding + delta. + target_delta: If not None, the delta for which we compute the corresponding + epsilon. Exactly one of target_eps and target_delta must be None. + + Returns: + eps, delta, opt_order. + + Raises: + ValueError: If target_eps and target_delta are messed up. + """ + if target_eps is None and target_delta is None: + raise ValueError( + "Exactly one out of eps and delta must be None. (Both are).") + + if target_eps is not None and target_delta is not None: + raise ValueError( + "Exactly one out of eps and delta must be None. (None is).") + + if target_eps is not None: + delta, opt_order = _compute_delta(orders, rdp, target_eps) + return target_eps, delta, opt_order + else: + eps, opt_order = _compute_eps(orders, rdp, target_delta) + return eps, target_delta, opt_order + + +def compute_rdp_from_ledger(ledger, orders): + """Compute RDP of Sampled Gaussian Mechanism from ledger. + + Args: + ledger: A formatted privacy ledger. + orders: An array (or a scalar) of RDP orders. + + Returns: + RDP at all orders, can be np.inf. + """ + total_rdp = np.zeros_like(orders, dtype=float) + for sample in ledger: + # Compute equivalent z from l2_clip_bounds and noise stddevs in sample. + # See https://arxiv.org/pdf/1812.06210.pdf for derivation of this formula. + effective_z = sum([ + (q.noise_stddev / q.l2_norm_bound)**-2 for q in sample.queries])**-0.5 + total_rdp += compute_rdp( + sample.selection_probability, effective_z, 1, orders) + return total_rdp \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/ctabgan_synthesizer.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/ctabgan_synthesizer.py new file mode 100644 index 0000000000000000000000000000000000000000..521a29aff4e8db1d45c7c3be98d593892c65c8d1 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/ctabgan_synthesizer.py @@ -0,0 +1,605 @@ +import numpy as np +import pandas as pd +import torch +import torch.utils.data +import torch.optim as optim +from torch.optim import Adam +from torch.nn import functional as F +from torch.nn import (Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, +Conv2d, ConvTranspose2d, Sigmoid, init, BCELoss, CrossEntropyLoss,SmoothL1Loss,LayerNorm) +from model.synthesizer.transformer import ImageTransformer,DataTransformer +from model.privacy_utils.rdp_accountant import compute_rdp, get_privacy_spent +from tqdm import tqdm, trange +import time + + +class Classifier(Module): + def __init__(self,input_dim, dis_dims,st_ed): + super(Classifier,self).__init__() + dim = input_dim-(st_ed[1]-st_ed[0]) + seq = [] + self.str_end = st_ed + for item in list(dis_dims): + seq += [ + Linear(dim, item), + LeakyReLU(0.2), + Dropout(0.5) + ] + dim = item + + if (st_ed[1]-st_ed[0])==1: + seq += [Linear(dim, 1)] + + elif (st_ed[1]-st_ed[0])==2: + seq += [Linear(dim, 1),Sigmoid()] + else: + seq += [Linear(dim,(st_ed[1]-st_ed[0]))] + + self.seq = Sequential(*seq) + + def forward(self, input): + + label=None + + if (self.str_end[1]-self.str_end[0])==1: + label = input[:, self.str_end[0]:self.str_end[1]] + else: + label = torch.argmax(input[:, self.str_end[0]:self.str_end[1]], axis=-1) + + new_imp = torch.cat((input[:,:self.str_end[0]],input[:,self.str_end[1]:]),1) + + if ((self.str_end[1]-self.str_end[0])==2) | ((self.str_end[1]-self.str_end[0])==1): + return self.seq(new_imp).view(-1), label + else: + return self.seq(new_imp), label + +def apply_activate(data, output_info): + data_t = [] + st = 0 + for item in output_info: + if item[1] == 'tanh': + ed = st + item[0] + data_t.append(torch.tanh(data[:, st:ed])) + st = ed + elif item[1] == 'softmax': + ed = st + item[0] + data_t.append(F.gumbel_softmax(data[:, st:ed], tau=0.2)) + st = ed + return torch.cat(data_t, dim=1) + +def get_st_ed(target_col_index,output_info): + st = 0 + c= 0 + tc= 0 + + for item in output_info: + if c==target_col_index: + break + if item[1]=='tanh': + st += item[0] + if item[2] == 'yes_g': + c+=1 + elif item[1] == 'softmax': + st += item[0] + c+=1 + tc+=1 + + ed= st+output_info[tc][0] + + return (st,ed) + +def random_choice_prob_index_sampling(probs,col_idx): + option_list = [] + for i in col_idx: + pp = probs[i] + option_list.append(np.random.choice(np.arange(len(probs[i])), p=pp)) + + return np.array(option_list).reshape(col_idx.shape) + +def random_choice_prob_index(a, axis=1): + r = np.expand_dims(np.random.rand(a.shape[1 - axis]), axis=axis) + return (a.cumsum(axis=axis) > r).argmax(axis=axis) + +def maximum_interval(output_info): + max_interval = 0 + for item in output_info: + max_interval = max(max_interval, item[0]) + return max_interval + +class Cond(object): + def __init__(self, data, output_info): + + self.model = [] + st = 0 + counter = 0 + for item in output_info: + + if item[1] == 'tanh': + st += item[0] + continue + elif item[1] == 'softmax': + ed = st + item[0] + counter += 1 + self.model.append(np.argmax(data[:, st:ed], axis=-1)) + st = ed + + self.interval = [] + self.n_col = 0 + self.n_opt = 0 + st = 0 + self.p = np.zeros((counter, maximum_interval(output_info))) + self.p_sampling = [] + for item in output_info: + if item[1] == 'tanh': + st += item[0] + continue + elif item[1] == 'softmax': + ed = st + item[0] + tmp = np.sum(data[:, st:ed], axis=0) + tmp_sampling = np.sum(data[:, st:ed], axis=0) + tmp = np.log(tmp + 1) + tmp = tmp / np.sum(tmp) + tmp_sampling = tmp_sampling / np.sum(tmp_sampling) + self.p_sampling.append(tmp_sampling) + self.p[self.n_col, :item[0]] = tmp + self.interval.append((self.n_opt, item[0])) + self.n_opt += item[0] + self.n_col += 1 + st = ed + + self.interval = np.asarray(self.interval) + + def sample_train(self, batch): + if self.n_col == 0: + return None + batch = batch + + idx = np.random.choice(np.arange(self.n_col), batch) + + vec = np.zeros((batch, self.n_opt), dtype='float32') + mask = np.zeros((batch, self.n_col), dtype='float32') + mask[np.arange(batch), idx] = 1 + opt1prime = random_choice_prob_index(self.p[idx]) + for i in np.arange(batch): + vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1 + + return vec, mask, idx, opt1prime + + def sample(self, batch): + if self.n_col == 0: + return None + batch = batch + + idx = np.random.choice(np.arange(self.n_col), batch) + + vec = np.zeros((batch, self.n_opt), dtype='float32') + opt1prime = random_choice_prob_index_sampling(self.p_sampling,idx) + + for i in np.arange(batch): + vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1 + + return vec + +def cond_loss(data, output_info, c, m): + loss = [] + st = 0 + st_c = 0 + for item in output_info: + if item[1] == 'tanh': + st += item[0] + continue + + elif item[1] == 'softmax': + ed = st + item[0] + ed_c = st_c + item[0] + tmp = F.cross_entropy( + data[:, st:ed], + torch.argmax(c[:, st_c:ed_c], dim=1), + reduction='none') + loss.append(tmp) + st = ed + st_c = ed_c + + loss = torch.stack(loss, dim=1) + return (loss * m).sum() / data.size()[0] + +class Sampler(object): + def __init__(self, data, output_info): + super(Sampler, self).__init__() + self.data = data + self.model = [] + self.n = len(data) + st = 0 + for item in output_info: + if item[1] == 'tanh': + st += item[0] + continue + elif item[1] == 'softmax': + ed = st + item[0] + tmp = [] + for j in range(item[0]): + tmp.append(np.nonzero(data[:, st + j])[0]) + self.model.append(tmp) + st = ed + + def sample(self, n, col, opt): + if col is None: + idx = np.random.choice(np.arange(self.n), n) + return self.data[idx] + idx = [] + for c, o in zip(col, opt): + idx.append(np.random.choice(self.model[c][o])) + return self.data[idx] + +class Discriminator(Module): + def __init__(self, side, layers): + super(Discriminator, self).__init__() + self.side = side + info = len(layers)-2 + self.seq = Sequential(*layers) + self.seq_info = Sequential(*layers[:info]) + + def forward(self, input): + return (self.seq(input)), self.seq_info(input) + +class Generator(Module): + def __init__(self, side, layers): + super(Generator, self).__init__() + self.side = side + self.seq = Sequential(*layers) + + def forward(self, input_): + return self.seq(input_) + +def determine_layers_disc(side, num_channels): + assert side >= 4 and side <= 64 + + layer_dims = [(1, side), (num_channels, side // 2)] + + while layer_dims[-1][1] > 3 and len(layer_dims) < 4: + layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2)) + + layerNorms = [] + num_c = num_channels + num_s = side / 2 + for l in range(len(layer_dims) - 1): + layerNorms.append([int(num_c), int(num_s), int(num_s)]) + num_c = num_c * 2 + num_s = num_s / 2 + + layers_D = [] + + for prev, curr, ln in zip(layer_dims, layer_dims[1:], layerNorms): + layers_D += [ + Conv2d(prev[0], curr[0], 4, 2, 1, bias=False), + LayerNorm(ln), + LeakyReLU(0.2, inplace=True), + ] + + layers_D += [Conv2d(layer_dims[-1][0], 1, layer_dims[-1][1], 1, 0), ReLU(True)] + + return layers_D + +def determine_layers_gen(side, random_dim, num_channels): + assert side >= 4 and side <= 64 + + layer_dims = [(1, side), (num_channels, side // 2)] + + while layer_dims[-1][1] > 3 and len(layer_dims) < 4: + layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2)) + + layerNorms = [] + + num_c = num_channels * (2 ** (len(layer_dims) - 2)) + num_s = int(side / (2 ** (len(layer_dims) - 1))) + for l in range(len(layer_dims) - 1): + layerNorms.append([int(num_c), int(num_s), int(num_s)]) + num_c = num_c / 2 + num_s = num_s * 2 + + layers_G = [ConvTranspose2d(random_dim, layer_dims[-1][0], layer_dims[-1][1], 1, 0, output_padding=0, bias=False)] + + for prev, curr, ln in zip(reversed(layer_dims), reversed(layer_dims[:-1]), layerNorms): + layers_G += [LayerNorm(ln), ReLU(True), ConvTranspose2d(prev[0], curr[0], 4, 2, 1, output_padding=0, bias=True)] + return layers_G + +def slerp(val, low, high): + low_norm = low/torch.norm(low, dim=1, keepdim=True) + high_norm = high/torch.norm(high, dim=1, keepdim=True) + omega = torch.acos((low_norm*high_norm).sum(1)).view(val.size(0), 1) + so = torch.sin(omega) + res = (torch.sin((1.0-val)*omega)/so)*low + (torch.sin(val*omega)/so) * high + + return res + +def calc_gradient_penalty_slerp(netD, real_data, fake_data, transformer, device='cpu', lambda_=10): + batchsize = real_data.shape[0] + alpha = torch.rand(batchsize, 1, device=device) + interpolates = slerp(alpha, real_data, fake_data) + interpolates = interpolates.to(device) + interpolates = transformer.transform(interpolates) + interpolates = torch.autograd.Variable(interpolates, requires_grad=True) + disc_interpolates,_ = netD(interpolates) + + gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolates, + grad_outputs=torch.ones(disc_interpolates.size()).to(device), + create_graph=True, retain_graph=True, only_inputs=True)[0] + + gradients_norm = gradients.norm(2, dim=1) + gradient_penalty = ((gradients_norm - 1) ** 2).mean() * lambda_ + + return gradient_penalty + +def weights_init(m): + classname = m.__class__.__name__ + + if classname.find('Conv') != -1: + init.normal_(m.weight.data, 0.0, 0.02) + + elif classname.find('BatchNorm') != -1: + init.normal_(m.weight.data, 1.0, 0.02) + init.constant_(m.bias.data, 0) + +class CTABGANSynthesizer: + def __init__(self, + class_dim=(256, 256, 256, 256), + random_dim=100, + num_channels=64, + l2scale=1e-5, + batch_size=500, + epochs=150, + lr=2e-4, + device="cpu"): + + + self.random_dim = random_dim + self.class_dim = class_dim + self.num_channels = num_channels + self.dside = None + self.gside = None + self.l2scale = l2scale + self.lr = lr + self.batch_size = batch_size + self.epochs = epochs + self.device = torch.device(device) + + def fit(self, train_data=pd.DataFrame, categorical=[], mixed={}, general=[], non_categorical=[], type={}): + + problem_type = None + target_index=None + if type: + problem_type = list(type.keys())[0] + if problem_type: + target_index = train_data.columns.get_loc(type[problem_type]) + + self.transformer = DataTransformer(train_data=train_data, categorical_list=categorical, mixed_dict=mixed, general_list=general, non_categorical_list=non_categorical) + self.transformer.fit() + train_data = self.transformer.transform(train_data.values) + data_sampler = Sampler(train_data, self.transformer.output_info) + data_dim = self.transformer.output_dim + self.cond_generator = Cond(train_data, self.transformer.output_info) + + sides = [4, 8, 16, 24, 32] + col_size_d = data_dim + self.cond_generator.n_opt + for i in sides: + if i * i >= col_size_d: + self.dside = i + break + + sides = [4, 8, 16, 24, 32] + col_size_g = data_dim + for i in sides: + if i * i >= col_size_g: + self.gside = i + break + + + layers_G = determine_layers_gen(self.gside, self.random_dim+self.cond_generator.n_opt, self.num_channels) + layers_D = determine_layers_disc(self.dside, self.num_channels) + + self.generator = Generator(self.gside, layers_G).to(self.device) + discriminator = Discriminator(self.dside, layers_D).to(self.device) + optimizer_params = dict(lr=self.lr, betas=(0.5, 0.9), eps=1e-3, weight_decay=self.l2scale) + optimizerG = Adam(self.generator.parameters(), **optimizer_params) + optimizerD = Adam(discriminator.parameters(), **optimizer_params) + + st_ed = None + classifier=None + optimizerC= None + if target_index != None: + st_ed= get_st_ed(target_index,self.transformer.output_info) + classifier = Classifier(data_dim,self.class_dim,st_ed).to(self.device) + optimizerC = optim.Adam(classifier.parameters(),**optimizer_params) + + + self.generator.apply(weights_init) + discriminator.apply(weights_init) + + self.Gtransformer = ImageTransformer(self.gside) + self.Dtransformer = ImageTransformer(self.dside) + + epsilon = 0 + epoch = 0 + steps = 0 + ci = 1 + + for i in tqdm(range(self.epochs)): + + + for _ in range(ci): + noisez = torch.randn(self.batch_size, self.random_dim, device=self.device) + condvec = self.cond_generator.sample_train(self.batch_size) + + c, m, col, opt = condvec + c = torch.from_numpy(c).to(self.device) + m = torch.from_numpy(m).to(self.device) + noisez = torch.cat([noisez, c], dim=1) + noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1) + + perm = np.arange(self.batch_size) + np.random.shuffle(perm) + real = data_sampler.sample(self.batch_size, col[perm], opt[perm]) + c_perm = c[perm] + + real = torch.from_numpy(real.astype('float32')).to(self.device) + + fake = self.generator(noisez) + faket = self.Gtransformer.inverse_transform(fake) + fakeact = apply_activate(faket, self.transformer.output_info) + + fake_cat = torch.cat([fakeact, c], dim=1) + real_cat = torch.cat([real, c_perm], dim=1) + + real_cat_d = self.Dtransformer.transform(real_cat) + fake_cat_d = self.Dtransformer.transform(fake_cat) + + optimizerD.zero_grad() + + d_real,_ = discriminator(real_cat_d) + + + d_real = -torch.mean(d_real) + d_real.backward() + + + d_fake,_ = discriminator(fake_cat_d) + + d_fake = torch.mean(d_fake) + + d_fake.backward() + + pen = calc_gradient_penalty_slerp(discriminator, real_cat, fake_cat, self.Dtransformer , self.device) + + pen.backward() + + optimizerD.step() + + noisez = torch.randn(self.batch_size, self.random_dim, device=self.device) + + condvec = self.cond_generator.sample_train(self.batch_size) + + c, m, col, opt = condvec + c = torch.from_numpy(c).to(self.device) + m = torch.from_numpy(m).to(self.device) + noisez = torch.cat([noisez, c], dim=1) + noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1) + + optimizerG.zero_grad() + + fake = self.generator(noisez) + faket = self.Gtransformer.inverse_transform(fake) + fakeact = apply_activate(faket, self.transformer.output_info) + + fake_cat = torch.cat([fakeact, c], dim=1) + fake_cat = self.Dtransformer.transform(fake_cat) + + y_fake,info_fake = discriminator(fake_cat) + + cross_entropy = cond_loss(faket, self.transformer.output_info, c, m) + + _,info_real = discriminator(real_cat_d) + + + g = -torch.mean(y_fake) + cross_entropy + g.backward(retain_graph=True) + 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) + 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) + loss_info = loss_mean + loss_std + loss_info.backward() + optimizerG.step() + + + if problem_type: + + fake = self.generator(noisez) + + faket = self.Gtransformer.inverse_transform(fake) + + fakeact = apply_activate(faket, self.transformer.output_info) + + real_pre, real_label = classifier(real) + fake_pre, fake_label = classifier(fakeact) + + c_loss = CrossEntropyLoss() + + if (st_ed[1] - st_ed[0])==1: + c_loss= SmoothL1Loss() + real_label = real_label.type_as(real_pre) + fake_label = fake_label.type_as(fake_pre) + real_label = torch.reshape(real_label,real_pre.size()) + fake_label = torch.reshape(fake_label,fake_pre.size()) + + + elif (st_ed[1] - st_ed[0])==2: + c_loss = BCELoss() + real_label = real_label.type_as(real_pre) + fake_label = fake_label.type_as(fake_pre) + + loss_cc = c_loss(real_pre, real_label) + loss_cg = c_loss(fake_pre, fake_label) + + optimizerG.zero_grad() + loss_cg.backward() + optimizerG.step() + + optimizerC.zero_grad() + loss_cc.backward() + optimizerC.step() + + + + + @torch.no_grad() + def sample(self, n, seed=0): + print(n) + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + sample_batch_size = 8092 + self.generator.eval() + + output_info = self.transformer.output_info + steps = n // sample_batch_size + 1 + + data = [] + + for i in range(steps): + noisez = torch.randn(sample_batch_size, self.random_dim, device=self.device) + condvec = self.cond_generator.sample(sample_batch_size) + c = condvec + c = torch.from_numpy(c).to(self.device) + noisez = torch.cat([noisez, c], dim=1) + noisez = noisez.view(sample_batch_size,self.random_dim+self.cond_generator.n_opt,1,1) + + fake = self.generator(noisez) + faket = self.Gtransformer.inverse_transform(fake) + fakeact = apply_activate(faket,output_info) + data.append(fakeact.detach().cpu().numpy()) + + data = np.concatenate(data, axis=0) + result,resample = self.transformer.inverse_transform(data) + + t0 = time.time() + while len(result) < n and (time.time() - t0) <= 600: + data_resample = [] + steps_left = resample// sample_batch_size + 1 + # print(f"Sampling: {len(result)}/{n}") + for i in range(steps_left): + noisez = torch.randn(sample_batch_size, self.random_dim, device=self.device) + condvec = self.cond_generator.sample(sample_batch_size) + c = condvec + c = torch.from_numpy(c).to(self.device) + noisez = torch.cat([noisez, c], dim=1) + noisez = noisez.view(sample_batch_size,self.random_dim+self.cond_generator.n_opt,1,1) + + fake = self.generator(noisez) + faket = self.Gtransformer.inverse_transform(fake) + fakeact = apply_activate(faket, output_info) + data_resample.append(fakeact.detach().cpu().numpy()) + + data_resample = np.concatenate(data_resample, axis=0) + + res,resample = self.transformer.inverse_transform(data_resample) + result = np.concatenate([result,res],axis=0) + + return result[0:n] + diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/transformer.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..ddad92266dc6d8b47e9ea1f4b4528795b9126e7d --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/transformer.py @@ -0,0 +1,429 @@ +import numpy as np +import pandas as pd +import torch +from sklearn.mixture import BayesianGaussianMixture + +class DataTransformer(): + + def __init__(self, train_data=pd.DataFrame, categorical_list=[], mixed_dict={}, general_list=[], non_categorical_list=[], n_clusters=10, eps=0.005): + self.meta = None + self.n_clusters = n_clusters + self.eps = eps + self.train_data = train_data + self.categorical_columns= categorical_list + self.mixed_columns= mixed_dict + self.general_columns = general_list + self.non_categorical_columns= non_categorical_list + + def get_metadata(self): + + meta = [] + + for index in range(self.train_data.shape[1]): + column = self.train_data.iloc[:,index] + if index in self.categorical_columns: + if index in self.non_categorical_columns: + meta.append({ + "name": index, + "type": "continuous", + "min": column.min(), + "max": column.max(), + }) + else: + mapper = column.value_counts().index.tolist() + meta.append({ + "name": index, + "type": "categorical", + "size": len(mapper), + "i2s": mapper + }) + + elif index in self.mixed_columns.keys(): + meta.append({ + "name": index, + "type": "mixed", + "min": column.min(), + "max": column.max(), + "modal": self.mixed_columns[index] + }) + else: + meta.append({ + "name": index, + "type": "continuous", + "min": column.min(), + "max": column.max(), + }) + + return meta + + def fit(self): + data = self.train_data.values + self.meta = self.get_metadata() + model = [] + self.ordering = [] + self.output_info = [] + self.output_dim = 0 + self.components = [] + self.filter_arr = [] + for id_, info in enumerate(self.meta): + if info['type'] == "continuous": + if id_ not in self.general_columns: + gm = BayesianGaussianMixture( + n_components = self.n_clusters, + weight_concentration_prior_type='dirichlet_process', + weight_concentration_prior=0.001, + max_iter=100,n_init=1, random_state=42) + gm.fit(data[:, id_].reshape([-1, 1])) + mode_freq = (pd.Series(gm.predict(data[:, id_].reshape([-1, 1]))).value_counts().keys()) + model.append(gm) + old_comp = gm.weights_ > self.eps + comp = [] + for i in range(self.n_clusters): + if (i in (mode_freq)) & old_comp[i]: + comp.append(True) + else: + comp.append(False) + self.components.append(comp) + self.output_info += [(1, 'tanh','no_g'), (np.sum(comp), 'softmax')] + self.output_dim += 1 + np.sum(comp) + else: + model.append(None) + self.components.append(None) + self.output_info += [(1, 'tanh','yes_g')] + self.output_dim += 1 + + elif info['type'] == "mixed": + + gm1 = BayesianGaussianMixture( + n_components = self.n_clusters, + weight_concentration_prior_type='dirichlet_process', + weight_concentration_prior=0.001, max_iter=100, + n_init=1,random_state=42) + gm2 = BayesianGaussianMixture( + n_components = self.n_clusters, + weight_concentration_prior_type='dirichlet_process', + weight_concentration_prior=0.001, max_iter=100, + n_init=1,random_state=42) + + gm1.fit(data[:, id_].reshape([-1, 1])) + + filter_arr = [] + for element in data[:, id_]: + if element not in info['modal']: + filter_arr.append(True) + else: + filter_arr.append(False) + + gm2.fit(data[:, id_][filter_arr].reshape([-1, 1])) + mode_freq = (pd.Series(gm2.predict(data[:, id_][filter_arr].reshape([-1, 1]))).value_counts().keys()) + self.filter_arr.append(filter_arr) + model.append((gm1,gm2)) + + old_comp = gm2.weights_ > self.eps + + comp = [] + + for i in range(self.n_clusters): + if (i in (mode_freq)) & old_comp[i]: + comp.append(True) + else: + comp.append(False) + + self.components.append(comp) + + self.output_info += [(1, 'tanh',"no_g"), (np.sum(comp) + len(info['modal']), 'softmax')] + self.output_dim += 1 + np.sum(comp) + len(info['modal']) + else: + model.append(None) + self.components.append(None) + self.output_info += [(info['size'], 'softmax')] + self.output_dim += info['size'] + self.model = model + + def transform(self, data, ispositive = False, positive_list = None): + values = [] + mixed_counter = 0 + for id_, info in enumerate(self.meta): + current = data[:, id_] + if info['type'] == "continuous": + if id_ not in self.general_columns: + current = current.reshape([-1, 1]) + means = self.model[id_].means_.reshape((1, self.n_clusters)) + stds = np.sqrt(self.model[id_].covariances_).reshape((1, self.n_clusters)) + features = np.empty(shape=(len(current),self.n_clusters)) + if ispositive == True: + if id_ in positive_list: + features = np.abs(current - means) / (4 * stds) + else: + features = (current - means) / (4 * stds) + + probs = self.model[id_].predict_proba(current.reshape([-1, 1])) + n_opts = sum(self.components[id_]) + features = features[:, self.components[id_]] + probs = probs[:, self.components[id_]] + + opt_sel = np.zeros(len(data), dtype='int') + for i in range(len(data)): + pp = probs[i] + 1e-6 + pp = pp / sum(pp) + opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp) + + idx = np.arange((len(features))) + features = features[idx, opt_sel].reshape([-1, 1]) + features = np.clip(features, -.99, .99) + probs_onehot = np.zeros_like(probs) + probs_onehot[np.arange(len(probs)), opt_sel] = 1 + + re_ordered_phot = np.zeros_like(probs_onehot) + + col_sums = probs_onehot.sum(axis=0) + + + n = probs_onehot.shape[1] + largest_indices = np.argsort(-1*col_sums)[:n] + self.ordering.append(largest_indices) + for id,val in enumerate(largest_indices): + re_ordered_phot[:,id] = probs_onehot[:,val] + + + values += [features, re_ordered_phot] + + else: + + self.ordering.append(None) + + if id_ in self.non_categorical_columns: + info['min'] = -1e-3 + info['max'] = info['max'] + 1e-3 + + current = (current - (info['min'])) / (info['max'] - info['min']) + current = current * 2 - 1 + current = current.reshape([-1, 1]) + values.append(current) + + elif info['type'] == "mixed": + + means_0 = self.model[id_][0].means_.reshape([-1]) + stds_0 = np.sqrt(self.model[id_][0].covariances_).reshape([-1]) + + zero_std_list = [] + means_needed = [] + stds_needed = [] + + for mode in info['modal']: + if mode!=-9999999: + dist = [] + for idx,val in enumerate(list(means_0.flatten())): + dist.append(abs(mode-val)) + index_min = np.argmin(np.array(dist)) + zero_std_list.append(index_min) + else: continue + + for idx in zero_std_list: + means_needed.append(means_0[idx]) + stds_needed.append(stds_0[idx]) + + + mode_vals = [] + + for i,j,k in zip(info['modal'],means_needed,stds_needed): + this_val = np.abs(i - j) / (4*k) + mode_vals.append(this_val) + + if -9999999 in info["modal"]: + mode_vals.append(0) + + current = current.reshape([-1, 1]) + filter_arr = self.filter_arr[mixed_counter] + current = current[filter_arr] + + means = self.model[id_][1].means_.reshape((1, self.n_clusters)) + stds = np.sqrt(self.model[id_][1].covariances_).reshape((1, self.n_clusters)) + features = np.empty(shape=(len(current),self.n_clusters)) + if ispositive == True: + if id_ in positive_list: + features = np.abs(current - means) / (4 * stds) + else: + features = (current - means) / (4 * stds) + + probs = self.model[id_][1].predict_proba(current.reshape([-1, 1])) + + n_opts = sum(self.components[id_]) # 8 + features = features[:, self.components[id_]] + probs = probs[:, self.components[id_]] + + opt_sel = np.zeros(len(current), dtype='int') + for i in range(len(current)): + pp = probs[i] + 1e-6 + pp = pp / sum(pp) + opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp) + idx = np.arange((len(features))) + features = features[idx, opt_sel].reshape([-1, 1]) + features = np.clip(features, -.99, .99) + probs_onehot = np.zeros_like(probs) + probs_onehot[np.arange(len(probs)), opt_sel] = 1 + extra_bits = np.zeros([len(current), len(info['modal'])]) + temp_probs_onehot = np.concatenate([extra_bits,probs_onehot], axis = 1) + final = np.zeros([len(data), 1 + probs_onehot.shape[1] + len(info['modal'])]) + features_curser = 0 + for idx, val in enumerate(data[:, id_]): + if val in info['modal']: + category_ = list(map(info['modal'].index, [val]))[0] + final[idx, 0] = mode_vals[category_] + final[idx, (category_+1)] = 1 + + else: + final[idx, 0] = features[features_curser] + final[idx, (1+len(info['modal'])):] = temp_probs_onehot[features_curser][len(info['modal']):] + features_curser = features_curser + 1 + + just_onehot = final[:,1:] + re_ordered_jhot= np.zeros_like(just_onehot) + n = just_onehot.shape[1] + col_sums = just_onehot.sum(axis=0) + largest_indices = np.argsort(-1*col_sums)[:n] + self.ordering.append(largest_indices) + for id,val in enumerate(largest_indices): + re_ordered_jhot[:,id] = just_onehot[:,val] + final_features = final[:,0].reshape([-1, 1]) + values += [final_features, re_ordered_jhot] + mixed_counter = mixed_counter + 1 + + else: + self.ordering.append(None) + col_t = np.zeros([len(data), info['size']]) + idx = list(map(info['i2s'].index, current)) + col_t[np.arange(len(data)), idx] = 1 + values.append(col_t) + + return np.concatenate(values, axis=1) + + def inverse_transform(self, data): + data_t = np.zeros([len(data), len(self.meta)]) + invalid_ids = [] + st = 0 + for id_, info in enumerate(self.meta): + if info['type'] == "continuous": + if id_ not in self.general_columns: + u = data[:, st] + v = data[:, st + 1:st + 1 + np.sum(self.components[id_])] + order = self.ordering[id_] + v_re_ordered = np.zeros_like(v) + + for id,val in enumerate(order): + v_re_ordered[:,val] = v[:,id] + + v = v_re_ordered + + u = np.clip(u, -1, 1) + v_t = np.ones((data.shape[0], self.n_clusters)) * -100 + v_t[:, self.components[id_]] = v + v = v_t + st += 1 + np.sum(self.components[id_]) + means = self.model[id_].means_.reshape([-1]) + stds = np.sqrt(self.model[id_].covariances_).reshape([-1]) + p_argmax = np.argmax(v, axis=1) + std_t = stds[p_argmax] + mean_t = means[p_argmax] + tmp = u * 4 * std_t + mean_t + + for idx,val in enumerate(tmp): + if (val < info["min"]) | (val > info['max']): + invalid_ids.append(idx) + + if id_ in self.non_categorical_columns: + + tmp = np.round(tmp) + + data_t[:, id_] = tmp + + else: + u = data[:, st] + u = (u + 1) / 2 + u = np.clip(u, 0, 1) + u = u * (info['max'] - info['min']) + info['min'] + if id_ in self.non_categorical_columns: + data_t[:, id_] = np.round(u) + else: data_t[:, id_] = u + + st += 1 + + elif info['type'] == "mixed": + + u = data[:, st] + full_v = data[:,(st+1):(st+1)+len(info['modal'])+np.sum(self.components[id_])] + order = self.ordering[id_] + full_v_re_ordered = np.zeros_like(full_v) + + for id,val in enumerate(order): + full_v_re_ordered[:,val] = full_v[:,id] + + full_v = full_v_re_ordered + + + mixed_v = full_v[:,:len(info['modal'])] + v = full_v[:,-np.sum(self.components[id_]):] + + u = np.clip(u, -1, 1) + v_t = np.ones((data.shape[0], self.n_clusters)) * -100 + v_t[:, self.components[id_]] = v + v = np.concatenate([mixed_v,v_t], axis=1) + + st += 1 + np.sum(self.components[id_]) + len(info['modal']) + means = self.model[id_][1].means_.reshape([-1]) + stds = np.sqrt(self.model[id_][1].covariances_).reshape([-1]) + p_argmax = np.argmax(v, axis=1) + + result = np.zeros_like(u) + + for idx in range(len(data)): + if p_argmax[idx] < len(info['modal']): + argmax_value = p_argmax[idx] + result[idx] = float(list(map(info['modal'].__getitem__, [argmax_value]))[0]) + else: + std_t = stds[(p_argmax[idx]-len(info['modal']))] + mean_t = means[(p_argmax[idx]-len(info['modal']))] + result[idx] = u[idx] * 4 * std_t + mean_t + + for idx,val in enumerate(result): + if (val < info["min"]) | (val > info['max']): + invalid_ids.append(idx) + + data_t[:, id_] = result + + else: + current = data[:, st:st + info['size']] + st += info['size'] + idx = np.argmax(current, axis=1) + data_t[:, id_] = list(map(info['i2s'].__getitem__, idx)) + + + invalid_ids = np.unique(np.array(invalid_ids)) + all_ids = np.arange(0,len(data)) + valid_ids = list(set(all_ids) - set(invalid_ids)) + + return data_t[valid_ids],len(invalid_ids) + + +class ImageTransformer(): + + def __init__(self, side): + + self.height = side + + def transform(self, data): + + if self.height * self.height > len(data[0]): + + padding = torch.zeros((len(data), self.height * self.height - len(data[0]))).to(data.device) + data = torch.cat([data, padding], axis=1) + + return data.view(-1, 1, self.height, self.height) + + def inverse_transform(self, data): + + data = data.view(-1, self.height * self.height) + + return data + + diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py new file mode 100644 index 0000000000000000000000000000000000000000..a584f91844e866d04f3c59297ca66017f1e7dd6c --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/pipeline_ctabganp.py @@ -0,0 +1,81 @@ +import tomli +import shutil +import os +import argparse +from train_sample_ctabganp import train_ctabgan, sample_ctabgan +from scripts.eval_catboost import train_catboost +import zero +import lib +from model.ctabgan import CTABGAN + +def load_config(path) : + with open(path, 'rb') as f: + return tomli.load(f) + +def save_file(parent_dir, config_path): + try: + dst = os.path.join(parent_dir) + os.makedirs(os.path.dirname(dst), exist_ok=True) + shutil.copyfile(os.path.abspath(config_path), dst) + except shutil.SameFileError: + pass + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--config', metavar='FILE') + parser.add_argument('--train', action='store_true', default=False) + parser.add_argument('--sample', action='store_true', default=False) + parser.add_argument('--eval', action='store_true', default=False) + parser.add_argument('--change_val', action='store_true', default=False) + + args = parser.parse_args() + raw_config = lib.load_config(args.config) + timer = zero.Timer() + timer.run() + save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config) + ctabgan = None + if args.train: + ctabgan = train_ctabgan( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + train_params=raw_config['train_params'], + change_val=args.change_val, + device=raw_config['device'] + ) + if args.sample: + sample_ctabgan( + synthesizer=ctabgan, + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + num_samples=raw_config['sample']['num_samples'], + train_params=raw_config['train_params'], + change_val=args.change_val, + seed=raw_config['sample']['seed'], + device=raw_config['device'] + ) + + save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json')) + if args.eval: + if raw_config['eval']['type']['eval_model'] == 'catboost': + train_catboost( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + eval_type=raw_config['eval']['type']['eval_type'], + T_dict=raw_config['eval']['T'], + seed=raw_config['seed'], + change_val=args.change_val + ) + # elif raw_config['eval']['type']['eval_model'] == 'mlp': + # train_mlp( + # parent_dir=raw_config['parent_dir'], + # real_data_path=raw_config['real_data_path'], + # eval_type=raw_config['eval']['type']['eval_type'], + # T_dict=raw_config['eval']['T'], + # seed=raw_config['seed'], + # change_val=args.change_val + # ) + + print(f'Elapsed time: {str(timer)}') + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py new file mode 100644 index 0000000000000000000000000000000000000000..c1f668fe5b5d3d5255a3587982e968276e60273d --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/train_sample_ctabganp.py @@ -0,0 +1,110 @@ +import lib +import os +import numpy as np +import argparse +from model.ctabgan import CTABGAN +from pathlib import Path +import torch +import pickle + + +def train_ctabgan( + parent_dir, + real_data_path, + train_params = {"batch_size": 512}, + change_val=False, + device = "cpu" +): + real_data_path = Path(real_data_path) + parent_dir = Path(parent_dir) + device = torch.device(device) + + if change_val: + X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) + else: + X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') + + X = lib.concat_to_pd(X_num_train, X_cat_train, y_train) + + X.columns = [str(_) for _ in X.columns] + + ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name] + train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"]) + + print(train_params) + synthesizer = CTABGAN( + df = X, + test_ratio = 0.0, + **ctabgan_params, + **train_params, + device=device + ) + + synthesizer.fit() + + # save_ctabgan(synthesizer, parent_dir) + with open(parent_dir / "ctabgan.obj", "wb") as f: + pickle.dump(synthesizer, f) + + return synthesizer + +def sample_ctabgan( + synthesizer, + parent_dir, + real_data_path, + num_samples, + train_params = {"batch_size": 512}, + change_val=False, + device="cpu", + seed=0 +): + real_data_path = Path(real_data_path) + parent_dir = Path(parent_dir) + device = torch.device(device) + + if change_val: + X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) + else: + X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') + + X = lib.concat_to_pd(X_num_train, X_cat_train, y_train) + + X.columns = [str(_) for _ in X.columns] + + ctabgan_params = lib.load_json("CTAB-GAN-Plus/columns.json")[real_data_path.name] + + cat_features = ctabgan_params["categorical_columns"] + # if synthesizer is None: + # synthesizer = load_ctabgan(X, ctabgan_params, train_params, parent_dir) + with open(parent_dir / "ctabgan.obj", 'rb') as f: + synthesizer = pickle.load(f) + synthesizer.synthesizer.generator = synthesizer.synthesizer.generator.to(device) + gen_data = synthesizer.generate_samples(num_samples, seed) + + y = gen_data['y'].values + if len(np.unique(y)) == 1: + y[0] = 0 + y[1] = 1 + + X_cat = gen_data[cat_features].drop('y', axis=1, errors="ignore").values if len(cat_features) else None + X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None + + if X_num_train is not None: + np.save(parent_dir / 'X_num_train', X_num.astype(float)) + if X_cat_train is not None: + np.save(parent_dir / 'X_cat_train', X_cat.astype(str)) + np.save(parent_dir / 'y_train', y.astype(float).astype(int)) # only clf !!! + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('real_data_path', type=str) + parser.add_argument('parent_dir', type=str) + parser.add_argument('train_size', type=int) + args = parser.parse_args() + + ctabgan = train_ctabgan(args.parent_dir, args.real_data_path, change_val=True) + sample_ctabgan(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py new file mode 100644 index 0000000000000000000000000000000000000000..ed19426b03246e546e234a2501a7c06f173d9f03 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/tune_ctabgan.py @@ -0,0 +1,153 @@ +from multiprocessing.sharedctypes import RawValue +from random import random +import tempfile +import subprocess +import lib +import os +import optuna +import argparse +from pathlib import Path +from train_sample_ctabganp import train_ctabgan, sample_ctabgan +from scripts.eval_catboost import train_catboost + +parser = argparse.ArgumentParser() +parser.add_argument('data_path', type=str) +parser.add_argument('train_size', type=int) +parser.add_argument('eval_type', type=str) +parser.add_argument('device', type=str) + +args = parser.parse_args() +real_data_path = args.data_path +eval_type = args.eval_type +train_size = args.train_size +device = args.device +assert eval_type in ('merged', 'synthetic') + +def objective(trial): + + lr = trial.suggest_loguniform('lr', 0.00001, 0.003) + + def suggest_dim(name): + t = trial.suggest_int(name, d_min, d_max) + return 2 ** t + + # construct model + min_n_layers, max_n_layers, d_min, d_max = 1, 4, 6, 8 + n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers) + d_first = [suggest_dim('d_first')] if n_layers else [] + d_middle = ( + [suggest_dim('d_middle')] * (n_layers - 2) + if n_layers > 2 + else [] + ) + d_last = [suggest_dim('d_last')] if n_layers > 1 else [] + d_layers = d_first + d_middle + d_last + #### + + steps = trial.suggest_categorical('steps', [1000, 5000, 10000]) + # steps = trial.suggest_categorical('steps', [10]) + batch_size = 2 ** trial.suggest_int('batch_size', 9, 11) + random_dim = 2 ** trial.suggest_int('random_dim', 4, 7) + num_channels = 2 ** trial.suggest_int('num_channels', 4, 6) + + # steps = trial.suggest_categorical('steps', [1000]) + + num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3))) + + train_params = { + "lr": lr, + "epochs": steps, + "class_dim": d_layers, + "batch_size": batch_size, + "random_dim": random_dim, + "num_channels": num_channels + } + trial.set_user_attr("train_params", train_params) + trial.set_user_attr("num_samples", num_samples) + + score = 0.0 + with tempfile.TemporaryDirectory() as dir_: + dir_ = Path(dir_) + ctabgan = train_ctabgan( + parent_dir=dir_, + real_data_path=real_data_path, + train_params=train_params, + change_val=True, + device=device + ) + + for sample_seed in range(5): + sample_ctabgan( + ctabgan, + parent_dir=dir_, + real_data_path=real_data_path, + num_samples=num_samples, + train_params=train_params, + change_val=True, + seed=sample_seed, + device=device + ) + + T_dict = { + "seed": 0, + "normalization": None, + "num_nan_policy": None, + "cat_nan_policy": None, + "cat_min_frequency": None, + "cat_encoding": None, + "y_policy": "default" + } + metrics = train_catboost( + parent_dir=dir_, + real_data_path=real_data_path, + eval_type=eval_type, + T_dict=T_dict, + change_val=True, + seed = 0 + ) + + score += metrics.get_val_score() + return score / 5 + + +study = optuna.create_study( + direction='maximize', + sampler=optuna.samplers.TPESampler(seed=0), +) + +study.optimize(objective, n_trials=35, show_progress_bar=True) + +os.makedirs(f"exp/{Path(real_data_path).name}/ctabgan-plus/", exist_ok=True) +config = { + "parent_dir": f"exp/{Path(real_data_path).name}/ctabgan-plus/", + "real_data_path": real_data_path, + "seed": 0, + "device": args.device, + "train_params": study.best_trial.user_attrs["train_params"], + "sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]}, + "eval": { + "type": {"eval_model": "catboost", "eval_type": eval_type}, + "T": { + "seed": 0, + "normalization": None, + "num_nan_policy": None, + "cat_nan_policy": None, + "cat_min_frequency": None, + "cat_encoding": None, + "y_policy": "default" + }, + } +} + +train_ctabgan( + parent_dir=f"exp/{Path(real_data_path).name}/ctabgan-plus/", + real_data_path=real_data_path, + train_params=study.best_trial.user_attrs["train_params"], + change_val=False, + device=device +) + +lib.dump_config(config, config["parent_dir"]+"config.toml") + +subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}', + '10', "ctabgan-plus", eval_type, "catboost", "5"], check=True) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/.gitignore b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2473a164760acb3c77f225f094e19e2e0f523912 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/.gitignore @@ -0,0 +1 @@ +**/**.csv \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/LICENSE b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/License.txt b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..5404b6f9e08e11c3a28a214518830c963060c885 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/License.txt @@ -0,0 +1,15 @@ +Distributed learning systems Lab at TU Delft & Generatrix, hereby disclaims all copyright interest in the program "CTAB-GAN" (which synthesizes tabular data) + +Copyright 2020-2022 Distributed learning systems Lab at TU Delft & Generatrix. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/README.md b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7fd4f2ac92abf9b244313a9ecf7d8328932cfc8c --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/README.md @@ -0,0 +1,50 @@ +# CTAB-GAN +This is the official git paper [CTAB-GAN: Effective Table Data Synthesizing](https://proceedings.mlr.press/v157/zhao21a.html). The paper is published on Asian Conference on Machine Learning (ACML 2021), please check our pdf on PMLR website for our newest version of [paper](https://proceedings.mlr.press/v157/zhao21a.html), it adds more content on time consumption analysis of training CTAB-GAN. If you have any question, please contact `z.zhao-8@tudelft.nl` for more information. + + +## Prerequisite + +The required package version +``` +numpy==1.21.0 +torch==1.9.1 +pandas==1.2.4 +sklearn==0.24.1 +dython==0.6.4.post1 +scipy==1.4.1 +``` + +## Example +`Experiment_Script_Adult.ipynb` is an example notebook for training CTAB-GAN with Adult dataset. The dataset is alread under `Real_Datasets` folder. +The evaluation code is also provided. + +## For large dataset + +If your dataset has large number of column, you may encounter the problem that our currnet code cannot encode all of your data since CTAB-GAN will wrap the encoded data into an image-like format. What you can do is changing the line 341 and 348 in `model/synthesizer/ctabgan_synthesizer.py`. The number in the `slide` list +``` +sides = [4, 8, 16, 24, 32] +``` +is the side size of image. You can enlarge the list to [4, 8, 16, 24, 32, 64] or [4, 8, 16, 24, 32, 64, 128] for accepting larger dataset. + +## Bibtex + +To cite this paper, you could use this bibtex + +``` +@InProceedings{zhao21, + title = {CTAB-GAN: Effective Table Data Synthesizing}, + author = {Zhao, Zilong and Kunar, Aditya and Birke, Robert and Chen, Lydia Y.}, + booktitle = {Proceedings of The 13th Asian Conference on Machine Learning}, + pages = {97--112}, + year = {2021}, + editor = {Balasubramanian, Vineeth N. and Tsang, Ivor}, + volume = {157}, + series = {Proceedings of Machine Learning Research}, + month = {17--19 Nov}, + publisher = {PMLR}, + pdf = {https://proceedings.mlr.press/v157/zhao21a/zhao21a.pdf}, + url = {https://proceedings.mlr.press/v157/zhao21a.html} +} + + +``` diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json new file mode 100644 index 0000000000000000000000000000000000000000..5acd6bbcc72f8df4869e43a9e55e4dca4b32c616 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c59fb02cb7f4a153aecb9e18dd81bbbb6946e55c3e6928c748811fcf5a85ad79 +size 3179 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/__init__.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py new file mode 100644 index 0000000000000000000000000000000000000000..d12c1a3c05d486c698bca7012d45bf31bc50ffbf --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py @@ -0,0 +1,58 @@ +""" +Generative model training algorithm based on the CTABGANSynthesiser + +""" +import pandas as pd +import time +from model.pipeline.data_preparation import DataPrep +from model.synthesizer.ctabgan_synthesizer import CTABGANSynthesizer + +import warnings + +warnings.filterwarnings("ignore") + +class CTABGAN(): + + def __init__(self, + df, + test_ratio = 0.20, + categorical_columns = [ 'workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'gender', 'native-country', 'income'], + log_columns = [], + mixed_columns= {'capital-loss':[0.0],'capital-gain':[0.0]}, + integer_columns = ['age', 'fnlwgt','capital-gain', 'capital-loss','hours-per-week'], + problem_type= {"Classification": 'income'}, + batch_size = 512, + class_dim = (256, 256, 256, 256), + lr = 2e-4, + epochs = 10, + device=None): + + self.__name__ = 'CTABGAN' + + self.synthesizer = CTABGANSynthesizer(lr = lr, epochs = epochs, batch_size = batch_size, class_dim = class_dim, device = device) + self.raw_df = df + print(self.raw_df.shape) + self.test_ratio = test_ratio + self.categorical_columns = categorical_columns + self.log_columns = log_columns + self.mixed_columns = mixed_columns + self.integer_columns = integer_columns + self.problem_type = problem_type + + def fit(self, no_train=False): + print("-"*100) + start_time = time.time() + 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) + self.synthesizer.fit(train_data=self.data_prep.df, categorical = self.data_prep.column_types["categorical"], + mixed = self.data_prep.column_types["mixed"],type=self.problem_type, no_train=no_train) + end_time = time.time() + print('Finished training in',end_time-start_time," seconds.") + print("-"*100) + + + def generate_samples(self, num_samples, seed=0): + + sample = self.synthesizer.sample(num_samples, seed) + sample_df = self.data_prep.inverse_prep(sample) + + return sample_df diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc965efb802eac7263640e94ffba0cbdfff8c7e --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py @@ -0,0 +1,191 @@ +import numpy as np +import pandas as pd +from sklearn import metrics +from sklearn import model_selection +from sklearn.preprocessing import MinMaxScaler,StandardScaler +from sklearn.neural_network import MLPClassifier +from sklearn.linear_model import LogisticRegression +from sklearn import svm,tree +from sklearn.ensemble import RandomForestClassifier +from dython.nominal import compute_associations +from scipy.stats import wasserstein_distance +from scipy.spatial import distance +import warnings + +warnings.filterwarnings("ignore") + +def supervised_model_training(x_train, y_train, x_test, + y_test, model_name): + + if model_name == 'lr': + model = LogisticRegression(random_state=42,max_iter=500) + elif model_name == 'svm': + model = svm.SVC(random_state=42,probability=True) + elif model_name == 'dt': + model = tree.DecisionTreeClassifier(random_state=42) + elif model_name == 'rf': + model = RandomForestClassifier(random_state=42) + elif model_name == "mlp": + model = MLPClassifier(random_state=42,max_iter=100) + + model.fit(x_train, y_train) + pred = model.predict(x_test) + + if len(np.unique(y_train))>2: + predict = model.predict_proba(x_test) + acc = metrics.accuracy_score(y_test,pred)*100 + auc = metrics.roc_auc_score(y_test, predict,average="weighted",multi_class="ovr") + f1_score = metrics.precision_recall_fscore_support(y_test, pred,average="weighted")[2] + return [acc, auc,f1_score] + + else: + predict = model.predict_proba(x_test)[:,1] + acc = metrics.accuracy_score(y_test,pred)*100 + auc = metrics.roc_auc_score(y_test, predict) + f1_score = metrics.precision_recall_fscore_support(y_test,pred)[2].mean() + return [acc, auc,f1_score] + + +def get_utility_metrics(real_path,fake_paths,scaler="MinMax",classifiers=["lr","dt","rf","mlp"],test_ratio=.20): + + data_real = pd.read_csv(real_path).to_numpy() + data_dim = data_real.shape[1] + + data_real_y = data_real[:,-1] + data_real_X = data_real[:,:data_dim-1] + 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) + + if scaler=="MinMax": + scaler_real = MinMaxScaler() + else: + scaler_real = StandardScaler() + + scaler_real.fit(X_train_real) + X_train_real_scaled = scaler_real.transform(X_train_real) + X_test_real_scaled = scaler_real.transform(X_test_real) + + all_real_results = [] + for classifier in classifiers: + real_results = supervised_model_training(X_train_real_scaled,y_train_real,X_test_real_scaled,y_test_real,classifier) + all_real_results.append(real_results) + + all_fake_results_avg = [] + + for fake_path in fake_paths: + data_fake = pd.read_csv(fake_path).to_numpy() + data_fake_y = data_fake[:,-1] + data_fake_X = data_fake[:,:data_dim-1] + 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) + + if scaler=="MinMax": + scaler_fake = MinMaxScaler() + else: + scaler_fake = StandardScaler() + + scaler_fake.fit(data_fake_X) + + X_train_fake_scaled = scaler_fake.transform(X_train_fake) + + all_fake_results = [] + for classifier in classifiers: + fake_results = supervised_model_training(X_train_fake_scaled,y_train_fake,X_test_real_scaled,y_test_real,classifier) + all_fake_results.append(fake_results) + + all_fake_results_avg.append(all_fake_results) + + diff_results = np.array(all_real_results)- np.array(all_fake_results_avg).mean(axis=0) + + return diff_results + +def stat_sim(real_path,fake_path,cat_cols=None): + + Stat_dict={} + + real = pd.read_csv(real_path) + fake = pd.read_csv(fake_path) + + really = real.copy() + fakey = fake.copy() + + real_corr = compute_associations(real, nominal_columns=cat_cols) + + fake_corr = compute_associations(fake, nominal_columns=cat_cols) + + corr_dist = np.linalg.norm(real_corr - fake_corr) + + cat_stat = [] + num_stat = [] + + for column in real.columns: + + if column in cat_cols: + real_pdf=(really[column].value_counts()/really[column].value_counts().sum()) + fake_pdf=(fakey[column].value_counts()/fakey[column].value_counts().sum()) + categories = (fakey[column].value_counts()/fakey[column].value_counts().sum()).keys().tolist() + sorted_categories = sorted(categories) + + real_pdf_values = [] + fake_pdf_values = [] + + for i in sorted_categories: + real_pdf_values.append(real_pdf[i]) + fake_pdf_values.append(fake_pdf[i]) + + if len(real_pdf)!=len(fake_pdf): + zero_cats = set(really[column].value_counts().keys())-set(fakey[column].value_counts().keys()) + for z in zero_cats: + real_pdf_values.append(real_pdf[z]) + fake_pdf_values.append(0) + Stat_dict[column]=(distance.jensenshannon(real_pdf_values,fake_pdf_values, 2.0)) + cat_stat.append(Stat_dict[column]) + else: + scaler = MinMaxScaler() + scaler.fit(real[column].values.reshape(-1,1)) + l1 = scaler.transform(real[column].values.reshape(-1,1)).flatten() + l2 = scaler.transform(fake[column].values.reshape(-1,1)).flatten() + Stat_dict[column]= (wasserstein_distance(l1,l2)) + num_stat.append(Stat_dict[column]) + + return [np.mean(num_stat),np.mean(cat_stat),corr_dist] + +def privacy_metrics(real_path,fake_path,data_percent=15): + + real = pd.read_csv(real_path).drop_duplicates(keep=False) + fake = pd.read_csv(fake_path).drop_duplicates(keep=False) + + real_refined = real.sample(n=int(len(real)*(.01*data_percent)), random_state=42).to_numpy() + fake_refined = fake.sample(n=int(len(fake)*(.01*data_percent)), random_state=42).to_numpy() + + scalerR = StandardScaler() + scalerR.fit(real_refined) + scalerF = StandardScaler() + scalerF.fit(fake_refined) + df_real_scaled = scalerR.transform(real_refined) + df_fake_scaled = scalerF.transform(fake_refined) + + dist_rf = metrics.pairwise_distances(df_real_scaled, Y=df_fake_scaled, metric='minkowski', n_jobs=-1) + dist_rr = metrics.pairwise_distances(df_real_scaled, Y=None, metric='minkowski', n_jobs=-1) + rd_dist_rr = dist_rr[~np.eye(dist_rr.shape[0],dtype=bool)].reshape(dist_rr.shape[0],-1) + dist_ff = metrics.pairwise_distances(df_fake_scaled, Y=None, metric='minkowski', n_jobs=-1) + rd_dist_ff = dist_ff[~np.eye(dist_ff.shape[0],dtype=bool)].reshape(dist_ff.shape[0],-1) + smallest_two_indexes_rf = [dist_rf[i].argsort()[:2] for i in range(len(dist_rf))] + smallest_two_rf = [dist_rf[i][smallest_two_indexes_rf[i]] for i in range(len(dist_rf))] + smallest_two_indexes_rr = [rd_dist_rr[i].argsort()[:2] for i in range(len(rd_dist_rr))] + smallest_two_rr = [rd_dist_rr[i][smallest_two_indexes_rr[i]] for i in range(len(rd_dist_rr))] + smallest_two_indexes_ff = [rd_dist_ff[i].argsort()[:2] for i in range(len(rd_dist_ff))] + smallest_two_ff = [rd_dist_ff[i][smallest_two_indexes_ff[i]] for i in range(len(rd_dist_ff))] + nn_ratio_rr = np.array([i[0]/i[1] for i in smallest_two_rr]) + nn_ratio_ff = np.array([i[0]/i[1] for i in smallest_two_ff]) + nn_ratio_rf = np.array([i[0]/i[1] for i in smallest_two_rf]) + nn_fifth_perc_rr = np.percentile(nn_ratio_rr,5) + nn_fifth_perc_ff = np.percentile(nn_ratio_ff,5) + nn_fifth_perc_rf = np.percentile(nn_ratio_rf,5) + + min_dist_rf = np.array([i[0] for i in smallest_two_rf]) + fifth_perc_rf = np.percentile(min_dist_rf,5) + min_dist_rr = np.array([i[0] for i in smallest_two_rr]) + fifth_perc_rr = np.percentile(min_dist_rr,5) + min_dist_ff = np.array([i[0] for i in smallest_two_ff]) + fifth_perc_ff = np.percentile(min_dist_ff,5) + + 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) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/pipeline/data_preparation.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/pipeline/data_preparation.py new file mode 100644 index 0000000000000000000000000000000000000000..dec2dc9715af03ecabf6efb3cff333588e5aa25c --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/pipeline/data_preparation.py @@ -0,0 +1,114 @@ +import numpy as np +import pandas as pd +from sklearn import preprocessing +from sklearn import model_selection + +class DataPrep(object): + + def __init__(self, raw_df: pd.DataFrame, categorical: list, log:list, mixed:dict, integer:list, type:dict, test_ratio:float): + + + self.categorical_columns = categorical + self.log_columns = log + self.mixed_columns = mixed + self.integer_columns = integer + self.column_types = dict() + self.column_types["categorical"] = [] + self.column_types["mixed"] = {} + self.lower_bounds = {} + self.label_encoder_list = [] + + + target_col = list(type.values())[0] + y_real = raw_df[target_col] + X_real = raw_df.drop(columns=[target_col]) + # 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) + X_train_real, y_train_real = X_real, y_real + X_train_real[target_col]= y_train_real + + self.df = X_train_real + + self.df = self.df.replace(r' ', np.nan) + self.df = self.df.fillna('empty') + + all_columns= set(self.df.columns) + irrelevant_missing_columns = set(self.categorical_columns) + relevant_missing_columns = list(all_columns - irrelevant_missing_columns) + + for i in relevant_missing_columns: + if i in self.log_columns: + if "empty" in list(self.df[i].values): + self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x) + self.mixed_columns[i] = [-9999999] + elif i in list(self.mixed_columns.keys()): + if "empty" in list(self.df[i].values): + self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x ) + self.mixed_columns[i].append(-9999999) + else: + if "empty" in list(self.df[i].values): + self.df[i] = self.df[i].apply(lambda x: -9999999 if x=="empty" else x) + self.mixed_columns[i] = [-9999999] + + if self.log_columns: + for log_column in self.log_columns: + valid_indices = [] + for idx,val in enumerate(self.df[log_column].values): + if val!=-9999999: + valid_indices.append(idx) + eps = 1 + lower = np.min(self.df[log_column].iloc[valid_indices].values) + self.lower_bounds[log_column] = lower + if lower>0: + self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x) if x!=-9999999 else -9999999) + elif lower == 0: + self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x+eps) if x!=-9999999 else -9999999) + else: + self.df[log_column] = self.df[log_column].apply(lambda x: np.log(x-lower+eps) if x!=-9999999 else -9999999) + + for column_index, column in enumerate(self.df.columns): + if column in self.categorical_columns: + label_encoder = preprocessing.LabelEncoder() + self.df[column] = self.df[column].astype(str) + label_encoder.fit(self.df[column]) + current_label_encoder = dict() + current_label_encoder['column'] = column + current_label_encoder['label_encoder'] = label_encoder + transformed_column = label_encoder.transform(self.df[column]) + self.df[column] = transformed_column + self.label_encoder_list.append(current_label_encoder) + self.column_types["categorical"].append(column_index) + + elif column in self.mixed_columns: + self.column_types["mixed"][column_index] = self.mixed_columns[column] + + super().__init__() + + def inverse_prep(self, data, eps=1): + + df_sample = pd.DataFrame(data,columns=self.df.columns) + + for i in range(len(self.label_encoder_list)): + le = self.label_encoder_list[i]["label_encoder"] + df_sample[self.label_encoder_list[i]["column"]] = df_sample[self.label_encoder_list[i]["column"]].astype(int) + df_sample[self.label_encoder_list[i]["column"]] = le.inverse_transform(df_sample[self.label_encoder_list[i]["column"]]) + + if self.log_columns: + for i in df_sample: + if i in self.log_columns: + lower_bound = self.lower_bounds[i] + if lower_bound>0: + df_sample[i].apply(lambda x: np.exp(x)) + elif lower_bound==0: + 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)) + else: + df_sample[i] = df_sample[i].apply(lambda x: np.exp(x)-eps+lower_bound) + + if self.integer_columns: + for column in self.integer_columns: + df_sample[column]= (np.round(df_sample[column].values)) + df_sample[column] = df_sample[column].astype(int) + + df_sample.replace(-9999999, np.nan,inplace=True) + df_sample.replace('empty', np.nan,inplace=True) + + return df_sample diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/ctabgan_synthesizer.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/ctabgan_synthesizer.py new file mode 100644 index 0000000000000000000000000000000000000000..7e4dd5cc2ecfb7c730b8cdab498c3cba332a318f --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/ctabgan_synthesizer.py @@ -0,0 +1,526 @@ +import numpy as np +import pandas as pd +import torch +import torch.utils.data +import torch.optim as optim +from torch.optim import Adam +from torch.nn import functional as F +from torch.nn import (Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, +Conv2d, ConvTranspose2d, BatchNorm2d, Sigmoid, init, BCELoss, CrossEntropyLoss,SmoothL1Loss) +from model.synthesizer.transformer import ImageTransformer,DataTransformer +from tqdm import tqdm + + +class Classifier(Module): + def __init__(self,input_dim, dis_dims,st_ed): + super(Classifier,self).__init__() + dim = input_dim-(st_ed[1]-st_ed[0]) + seq = [] + self.str_end = st_ed + for item in list(dis_dims): + seq += [ + Linear(dim, item), + LeakyReLU(0.2), + Dropout(0.5) + ] + dim = item + + if (st_ed[1]-st_ed[0])==1: + seq += [Linear(dim, 1)] + + elif (st_ed[1]-st_ed[0])==2: + seq += [Linear(dim, 1),Sigmoid()] + else: + seq += [Linear(dim,(st_ed[1]-st_ed[0]))] + + self.seq = Sequential(*seq) + + def forward(self, input): + + label=None + + if (self.str_end[1]-self.str_end[0])==1: + label = input[:, self.str_end[0]:self.str_end[1]] + else: + label = torch.argmax(input[:, self.str_end[0]:self.str_end[1]], axis=-1) + + new_imp = torch.cat((input[:,:self.str_end[0]],input[:,self.str_end[1]:]),1) + + if ((self.str_end[1]-self.str_end[0])==2) | ((self.str_end[1]-self.str_end[0])==1): + return self.seq(new_imp).view(-1), label + else: + return self.seq(new_imp), label + +def apply_activate(data, output_info): + data_t = [] + st = 0 + for item in output_info: + if item[1] == 'tanh': + ed = st + item[0] + data_t.append(torch.tanh(data[:, st:ed])) + st = ed + elif item[1] == 'softmax': + ed = st + item[0] + data_t.append(F.gumbel_softmax(data[:, st:ed], tau=0.2)) + st = ed + return torch.cat(data_t, dim=1) + +def get_st_ed(target_col_index,output_info): + st = 0 + c= 0 + tc= 0 + for item in output_info: + if c==target_col_index: + break + if item[1]=='tanh': + st += item[0] + elif item[1] == 'softmax': + st += item[0] + c+=1 + tc+=1 + ed= st+output_info[tc][0] + return (st,ed) + +def random_choice_prob_index_sampling(probs,col_idx): + option_list = [] + for i in col_idx: + pp = probs[i] + option_list.append(np.random.choice(np.arange(len(probs[i])), p=pp)) + + return np.array(option_list).reshape(col_idx.shape) + +def random_choice_prob_index(a, axis=1): + r = np.expand_dims(np.random.rand(a.shape[1 - axis]), axis=axis) + return (a.cumsum(axis=axis) > r).argmax(axis=axis) + +def maximum_interval(output_info): + max_interval = 0 + for item in output_info: + max_interval = max(max_interval, item[0]) + return max_interval + +class Cond(object): + def __init__(self, data, output_info): + + self.model = [] + st = 0 + counter = 0 + for item in output_info: + + if item[1] == 'tanh': + st += item[0] + continue + elif item[1] == 'softmax': + ed = st + item[0] + counter += 1 + self.model.append(np.argmax(data[:, st:ed], axis=-1)) + st = ed + + self.interval = [] + self.n_col = 0 + self.n_opt = 0 + st = 0 + self.p = np.zeros((counter, maximum_interval(output_info))) + self.p_sampling = [] + for item in output_info: + if item[1] == 'tanh': + st += item[0] + continue + elif item[1] == 'softmax': + ed = st + item[0] + tmp = np.sum(data[:, st:ed], axis=0) + tmp_sampling = np.sum(data[:, st:ed], axis=0) + tmp = np.log(tmp + 1) + tmp = tmp / np.sum(tmp) + tmp_sampling = tmp_sampling / np.sum(tmp_sampling) + self.p_sampling.append(tmp_sampling) + self.p[self.n_col, :item[0]] = tmp + self.interval.append((self.n_opt, item[0])) + self.n_opt += item[0] + self.n_col += 1 + st = ed + + self.interval = np.asarray(self.interval) + + def sample_train(self, batch): + if self.n_col == 0: + return None + batch = batch + + idx = np.random.choice(np.arange(self.n_col), batch) + + vec = np.zeros((batch, self.n_opt), dtype='float32') + mask = np.zeros((batch, self.n_col), dtype='float32') + mask[np.arange(batch), idx] = 1 + opt1prime = random_choice_prob_index(self.p[idx]) + for i in np.arange(batch): + vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1 + + return vec, mask, idx, opt1prime + + def sample(self, batch): + if self.n_col == 0: + return None + batch = batch + + idx = np.random.choice(np.arange(self.n_col), batch) + + vec = np.zeros((batch, self.n_opt), dtype='float32') + opt1prime = random_choice_prob_index_sampling(self.p_sampling,idx) + + for i in np.arange(batch): + vec[i, self.interval[idx[i], 0] + opt1prime[i]] = 1 + + return vec + +def cond_loss(data, output_info, c, m): + loss = [] + st = 0 + st_c = 0 + for item in output_info: + if item[1] == 'tanh': + st += item[0] + continue + + elif item[1] == 'softmax': + ed = st + item[0] + ed_c = st_c + item[0] + tmp = F.cross_entropy( + data[:, st:ed], + torch.argmax(c[:, st_c:ed_c], dim=1), + reduction='none') + loss.append(tmp) + st = ed + st_c = ed_c + + loss = torch.stack(loss, dim=1) + return (loss * m).sum() / data.size()[0] + +class Sampler(object): + def __init__(self, data, output_info): + super(Sampler, self).__init__() + self.data = data + self.model = [] + self.n = len(data) + st = 0 + for item in output_info: + if item[1] == 'tanh': + st += item[0] + continue + elif item[1] == 'softmax': + ed = st + item[0] + tmp = [] + for j in range(item[0]): + tmp.append(np.nonzero(data[:, st + j])[0]) + self.model.append(tmp) + st = ed + + def sample(self, n, col, opt): + if col is None: + idx = np.random.choice(np.arange(self.n), n) + return self.data[idx] + idx = [] + for c, o in zip(col, opt): + idx.append(np.random.choice(self.model[c][o])) + return self.data[idx] + +class Discriminator(Module): + def __init__(self, side, layers): + super(Discriminator, self).__init__() + self.side = side + info = len(layers)-2 + self.seq = Sequential(*layers) + self.seq_info = Sequential(*layers[:info]) + + def forward(self, input): + return (self.seq(input)), self.seq_info(input) + +class Generator(Module): + def __init__(self, side, layers): + super(Generator, self).__init__() + self.side = side + self.seq = Sequential(*layers) + + def forward(self, input_): + return self.seq(input_) + +def determine_layers_disc(side, num_channels): + assert side >= 4 and side <= 32 + + layer_dims = [(1, side), (num_channels, side // 2)] + + while layer_dims[-1][1] > 3 and len(layer_dims) < 4: + layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2)) + + layers_D = [] + for prev, curr in zip(layer_dims, layer_dims[1:]): + layers_D += [ + Conv2d(prev[0], curr[0], 4, 2, 1, bias=False), + BatchNorm2d(curr[0]), + LeakyReLU(0.2, inplace=True) + ] + print() + layers_D += [ + + Conv2d(layer_dims[-1][0], 1, layer_dims[-1][1], 1, 0), + Sigmoid() + ] + + return layers_D + +def determine_layers_gen(side, random_dim, num_channels): + assert side >= 4 and side <= 32 + + layer_dims = [(1, side), (num_channels, side // 2)] + + while layer_dims[-1][1] > 3 and len(layer_dims) < 4: + layer_dims.append((layer_dims[-1][0] * 2, layer_dims[-1][1] // 2)) + + layers_G = [ + ConvTranspose2d( + random_dim, layer_dims[-1][0], layer_dims[-1][1], 1, 0, output_padding=0, bias=False) + ] + + for prev, curr in zip(reversed(layer_dims), reversed(layer_dims[:-1])): + layers_G += [ + BatchNorm2d(prev[0]), + ReLU(True), + ConvTranspose2d(prev[0], curr[0], 4, 2, 1, output_padding=0, bias=True) + ] + return layers_G + + +def weights_init(m): + classname = m.__class__.__name__ + + if classname.find('Conv') != -1: + init.normal_(m.weight.data, 0.0, 0.02) + + elif classname.find('BatchNorm') != -1: + init.normal_(m.weight.data, 1.0, 0.02) + init.constant_(m.bias.data, 0) + +class CTABGANSynthesizer: + def __init__(self, + lr=2e-4, + class_dim=(256, 256, 256, 256), + random_dim=128, + num_channels=64, + l2scale=1e-5, + batch_size=1024, + epochs=1, + device=torch.device("cpu")): + + + self.random_dim = random_dim + self.class_dim = class_dim + self.num_channels = num_channels + self.dside = None + self.gside = None + self.l2scale = l2scale + self.lr = lr + self.batch_size = batch_size + self.epochs = epochs + self.device = device + + def fit(self, train_data=pd.DataFrame, categorical=[], mixed={}, type={}, no_train=False): + print("Fit started.") + problem_type = None + target_index=None + if type: + problem_type = list(type.keys())[0] + if problem_type: + target_index = train_data.columns.get_loc(type[problem_type]) + + self.transformer = DataTransformer(train_data=train_data, categorical_list=categorical, mixed_dict=mixed) + self.transformer.fit() + + train_data = self.transformer.transform(train_data.values) + + data_sampler = Sampler(train_data, self.transformer.output_info) + data_dim = self.transformer.output_dim + self.cond_generator = Cond(train_data, self.transformer.output_info) + + sides = [4, 8, 16, 24, 32] + col_size_d = data_dim + self.cond_generator.n_opt + for i in sides: + if i * i >= col_size_d: + self.dside = i + break + + sides = [4, 8, 16, 24, 32] + col_size_g = data_dim + for i in sides: + if i * i >= col_size_g: + self.gside = i + break + + layers_G = determine_layers_gen(self.gside, self.random_dim+self.cond_generator.n_opt, self.num_channels) + layers_D = determine_layers_disc(self.dside, self.num_channels) + + self.generator = Generator(self.gside, layers_G).to(self.device) + discriminator = Discriminator(self.dside, layers_D).to(self.device) + optimizer_params = dict(lr=self.lr, betas=(0.5, 0.9), eps=1e-3, weight_decay=self.l2scale) + optimizerG = Adam(self.generator.parameters(), **optimizer_params) + optimizerD = Adam(discriminator.parameters(), **optimizer_params) + + st_ed = None + classifier=None + optimizerC= None + if target_index != None: + st_ed= get_st_ed(target_index,self.transformer.output_info) + classifier = Classifier(data_dim,self.class_dim,st_ed).to(self.device) + optimizerC = optim.Adam(classifier.parameters(),**optimizer_params) + + + self.generator.apply(weights_init) + discriminator.apply(weights_init) + + self.Gtransformer = ImageTransformer(self.gside) + self.Dtransformer = ImageTransformer(self.dside) + + + if no_train: return + + print("Training started.") + for i in range(self.epochs): + # for _ in range(steps_per_epoch): + + noisez = torch.randn(self.batch_size, self.random_dim, device=self.device) + condvec = self.cond_generator.sample_train(self.batch_size) + + c, m, col, opt = condvec + c = torch.from_numpy(c).to(self.device) + m = torch.from_numpy(m).to(self.device) + noisez = torch.cat([noisez, c], dim=1) + noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1) + + perm = np.arange(self.batch_size) + np.random.shuffle(perm) + real = data_sampler.sample(self.batch_size, col[perm], opt[perm]) + c_perm = c[perm] + + real = torch.from_numpy(real.astype('float32')).to(self.device) + + fake = self.generator(noisez) + faket = self.Gtransformer.inverse_transform(fake) + fakeact = apply_activate(faket, self.transformer.output_info) + + fake_cat = torch.cat([fakeact, c], dim=1) + real_cat = torch.cat([real, c_perm], dim=1) + + real_cat_d = self.Dtransformer.transform(real_cat) + fake_cat_d = self.Dtransformer.transform(fake_cat) + + optimizerD.zero_grad() + y_real,_ = discriminator(real_cat_d) + y_fake,_ = discriminator(fake_cat_d) + loss_d = (-(torch.log(y_real + 1e-4).mean()) - (torch.log(1. - y_fake + 1e-4).mean())) + loss_d.backward() + optimizerD.step() + + noisez = torch.randn(self.batch_size, self.random_dim, device=self.device) + + condvec = self.cond_generator.sample_train(self.batch_size) + + c, m, col, opt = condvec + c = torch.from_numpy(c).to(self.device) + m = torch.from_numpy(m).to(self.device) + noisez = torch.cat([noisez, c], dim=1) + noisez = noisez.view(self.batch_size,self.random_dim+self.cond_generator.n_opt,1,1) + + optimizerG.zero_grad() + + fake = self.generator(noisez) + faket = self.Gtransformer.inverse_transform(fake) + fakeact = apply_activate(faket, self.transformer.output_info) + + fake_cat = torch.cat([fakeact, c], dim=1) + fake_cat = self.Dtransformer.transform(fake_cat) + + y_fake,info_fake = discriminator(fake_cat) + + cross_entropy = cond_loss(faket, self.transformer.output_info, c, m) + + _,info_real = discriminator(real_cat_d) + + g = -(torch.log(y_fake + 1e-4).mean()) + cross_entropy + g.backward(retain_graph=True) + 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) + 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) + loss_info = loss_mean + loss_std + loss_info.backward() + optimizerG.step() + + if (i + 1) % 500 == 0: + print(f"Step: {i}/{self.epochs} Loss: {loss_mean:.4f}") + + if problem_type: + + fake = self.generator(noisez) + + faket = self.Gtransformer.inverse_transform(fake) + + fakeact = apply_activate(faket, self.transformer.output_info) + + real_pre, real_label = classifier(real) + fake_pre, fake_label = classifier(fakeact) + + c_loss = CrossEntropyLoss() + + if (st_ed[1] - st_ed[0])==1: + c_loss= SmoothL1Loss() + real_label = real_label.type_as(real_pre) + fake_label = fake_label.type_as(fake_pre) + real_label = torch.reshape(real_label,real_pre.size()) + fake_label = torch.reshape(fake_label,fake_pre.size()) + + + elif (st_ed[1] - st_ed[0])==2: + c_loss = BCELoss() + real_label = real_label.type_as(real_pre) + fake_label = fake_label.type_as(fake_pre) + + loss_cc = c_loss(real_pre, real_label) + loss_cg = c_loss(fake_pre, fake_label) + + optimizerG.zero_grad() + loss_cg.backward() + optimizerG.step() + + optimizerC.zero_grad() + loss_cc.backward() + optimizerC.step() + + @torch.no_grad() + def sample(self, n, seed=0): + + torch.manual_seed(seed) + torch.cuda.manual_seed(seed) + sample_batch_size = 8092 + self.generator.eval() + + output_info = self.transformer.output_info + steps = n // sample_batch_size + 1 + + data = [] + + for i in range(steps): + noisez = torch.randn(sample_batch_size, self.random_dim, device=self.device) + condvec = self.cond_generator.sample(sample_batch_size) + c = condvec + c = torch.from_numpy(c).to(self.device) + noisez = torch.cat([noisez, c], dim=1) + noisez = noisez.view(sample_batch_size,self.random_dim+self.cond_generator.n_opt,1,1) + + fake = self.generator(noisez) + faket = self.Gtransformer.inverse_transform(fake) + fakeact = apply_activate(faket,output_info) + # print(len(data)) + data.append(fakeact.detach().cpu().numpy()) + + data = np.concatenate(data, axis=0) + result = self.transformer.inverse_transform(data) + + return result[0:n] + diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/transformer.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..18fc3c492a99c7f2455ebf2c2cddf09525333b92 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/transformer.py @@ -0,0 +1,363 @@ +import numpy as np +import pandas as pd +import torch +from sklearn.mixture import BayesianGaussianMixture + +class DataTransformer(): + + def __init__(self, train_data=pd.DataFrame, categorical_list=[], mixed_dict={}, n_clusters=10, eps=0.005): + self.meta = None + self.n_clusters = n_clusters + self.eps = eps + self.train_data = train_data + self.categorical_columns= categorical_list + self.mixed_columns= mixed_dict + + def get_metadata(self): + + meta = [] + + for index in range(self.train_data.shape[1]): + column = self.train_data.iloc[:,index] + if index in self.categorical_columns: + mapper = column.value_counts().index.tolist() + meta.append({ + "name": index, + "type": "categorical", + "size": len(mapper), + "i2s": mapper + }) + elif index in self.mixed_columns.keys(): + meta.append({ + "name": index, + "type": "mixed", + "min": column.min(), + "max": column.max(), + "modal": self.mixed_columns[index] + }) + else: + meta.append({ + "name": index, + "type": "continuous", + "min": column.min(), + "max": column.max(), + }) + + return meta + + def fit(self): + data = self.train_data.values + self.meta = self.get_metadata() + model = [] + self.ordering = [] + self.output_info = [] + self.output_dim = 0 + self.components = [] + self.filter_arr = [] + for id_, info in enumerate(self.meta): + if info['type'] == "continuous": + gm = BayesianGaussianMixture(n_components=self.n_clusters, + weight_concentration_prior_type='dirichlet_process', + weight_concentration_prior=0.001, + max_iter=100,n_init=1, random_state=42) + gm.fit(data[:, id_].reshape([-1, 1])) + mode_freq = (pd.Series(gm.predict(data[:, id_].reshape([-1, 1]))).value_counts().keys()) + model.append(gm) + old_comp = gm.weights_ > self.eps + comp = [] + for i in range(self.n_clusters): + if (i in (mode_freq)) & old_comp[i]: + comp.append(True) + else: + comp.append(False) + self.components.append(comp) + self.output_info += [(1, 'tanh'), (np.sum(comp), 'softmax')] + self.output_dim += 1 + np.sum(comp) + + elif info['type'] == "mixed": + + gm1 = BayesianGaussianMixture(n_components=self.n_clusters, + weight_concentration_prior_type='dirichlet_process', + weight_concentration_prior=0.001, max_iter=100, + n_init=1,random_state=42) + gm2 = BayesianGaussianMixture(n_components=self.n_clusters, + weight_concentration_prior_type='dirichlet_process', + weight_concentration_prior=0.001, max_iter=100, + n_init=1,random_state=42) + + gm1.fit(data[:, id_].reshape([-1, 1])) + + filter_arr = [] + for element in data[:, id_]: + if element not in info['modal']: + filter_arr.append(True) + else: + filter_arr.append(False) + + gm2.fit(data[:, id_][filter_arr].reshape([-1, 1])) + mode_freq = (pd.Series(gm2.predict(data[:, id_][filter_arr].reshape([-1, 1]))).value_counts().keys()) + self.filter_arr.append(filter_arr) + model.append((gm1,gm2)) + + old_comp = gm2.weights_ > self.eps + + comp = [] + + for i in range(self.n_clusters): + if (i in (mode_freq)) & old_comp[i]: + comp.append(True) + else: + comp.append(False) + + self.components.append(comp) + + self.output_info += [(1, 'tanh'), (np.sum(comp) + len(info['modal']), 'softmax')] + self.output_dim += 1 + np.sum(comp) + len(info['modal']) + + else: + model.append(None) + self.components.append(None) + self.output_info += [(info['size'], 'softmax')] + self.output_dim += info['size'] + + self.model = model + + def transform(self, data, ispositive = False, positive_list = None): + values = [] + mixed_counter = 0 + for id_, info in enumerate(self.meta): + current = data[:, id_] + if info['type'] == "continuous": + current = current.reshape([-1, 1]) + means = self.model[id_].means_.reshape((1, self.n_clusters)) + stds = np.sqrt(self.model[id_].covariances_).reshape((1, self.n_clusters)) + features = np.empty(shape=(len(current),self.n_clusters)) + if ispositive == True: + if id_ in positive_list: + features = np.abs(current - means) / (4 * stds) + else: + features = (current - means) / (4 * stds) + + probs = self.model[id_].predict_proba(current.reshape([-1, 1])) + n_opts = sum(self.components[id_]) + features = features[:, self.components[id_]] + probs = probs[:, self.components[id_]] + + opt_sel = np.zeros(len(data), dtype='int') + for i in range(len(data)): + pp = probs[i] + 1e-6 + pp = pp / sum(pp) + opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp) + + idx = np.arange((len(features))) + features = features[idx, opt_sel].reshape([-1, 1]) + features = np.clip(features, -.99, .99) + probs_onehot = np.zeros_like(probs) + probs_onehot[np.arange(len(probs)), opt_sel] = 1 + + re_ordered_phot = np.zeros_like(probs_onehot) + + col_sums = probs_onehot.sum(axis=0) + + + n = probs_onehot.shape[1] + largest_indices = np.argsort(-1*col_sums)[:n] + self.ordering.append(largest_indices) + for id,val in enumerate(largest_indices): + re_ordered_phot[:,id] = probs_onehot[:,val] + + + values += [features, re_ordered_phot] + + elif info['type'] == "mixed": + + means_0 = self.model[id_][0].means_.reshape([-1]) + stds_0 = np.sqrt(self.model[id_][0].covariances_).reshape([-1]) + + zero_std_list = [] + means_needed = [] + stds_needed = [] + + for mode in info['modal']: + if mode!=-9999999: + dist = [] + for idx,val in enumerate(list(means_0.flatten())): + dist.append(abs(mode-val)) + index_min = np.argmin(np.array(dist)) + zero_std_list.append(index_min) + else: continue + + for idx in zero_std_list: + means_needed.append(means_0[idx]) + stds_needed.append(stds_0[idx]) + + + mode_vals = [] + + for i,j,k in zip(info['modal'],means_needed,stds_needed): + this_val = np.abs(i - j) / (4*k) + mode_vals.append(this_val) + + if -9999999 in info["modal"]: + mode_vals.append(0) + + current = current.reshape([-1, 1]) + filter_arr = self.filter_arr[mixed_counter] + current = current[filter_arr] + + means = self.model[id_][1].means_.reshape((1, self.n_clusters)) + stds = np.sqrt(self.model[id_][1].covariances_).reshape((1, self.n_clusters)) + features = np.empty(shape=(len(current),self.n_clusters)) + if ispositive == True: + if id_ in positive_list: + features = np.abs(current - means) / (4 * stds) + else: + features = (current - means) / (4 * stds) + + probs = self.model[id_][1].predict_proba(current.reshape([-1, 1])) + + n_opts = sum(self.components[id_]) # 8 + features = features[:, self.components[id_]] + probs = probs[:, self.components[id_]] + + opt_sel = np.zeros(len(current), dtype='int') + for i in range(len(current)): + pp = probs[i] + 1e-6 + pp = pp / sum(pp) + opt_sel[i] = np.random.choice(np.arange(n_opts), p=pp) + idx = np.arange((len(features))) + features = features[idx, opt_sel].reshape([-1, 1]) + features = np.clip(features, -.99, .99) + probs_onehot = np.zeros_like(probs) + probs_onehot[np.arange(len(probs)), opt_sel] = 1 + extra_bits = np.zeros([len(current), len(info['modal'])]) + temp_probs_onehot = np.concatenate([extra_bits,probs_onehot], axis = 1) + final = np.zeros([len(data), 1 + probs_onehot.shape[1] + len(info['modal'])]) + features_curser = 0 + for idx, val in enumerate(data[:, id_]): + if val in info['modal']: + category_ = list(map(info['modal'].index, [val]))[0] + final[idx, 0] = mode_vals[category_] + final[idx, (category_+1)] = 1 + + else: + final[idx, 0] = features[features_curser] + final[idx, (1+len(info['modal'])):] = temp_probs_onehot[features_curser][len(info['modal']):] + features_curser = features_curser + 1 + + just_onehot = final[:,1:] + re_ordered_jhot= np.zeros_like(just_onehot) + n = just_onehot.shape[1] + col_sums = just_onehot.sum(axis=0) + largest_indices = np.argsort(-1*col_sums)[:n] + self.ordering.append(largest_indices) + for id,val in enumerate(largest_indices): + re_ordered_jhot[:,id] = just_onehot[:,val] + final_features = final[:,0].reshape([-1, 1]) + values += [final_features, re_ordered_jhot] + mixed_counter = mixed_counter + 1 + + else: + self.ordering.append(None) + col_t = np.zeros([len(data), info['size']]) + idx = list(map(info['i2s'].index, current)) + col_t[np.arange(len(data)), idx] = 1 + values.append(col_t) + + return np.concatenate(values, axis=1) + + def inverse_transform(self, data): + data_t = np.zeros([len(data), len(self.meta)]) + st = 0 + for id_, info in enumerate(self.meta): + if info['type'] == "continuous": + u = data[:, st] + v = data[:, st + 1:st + 1 + np.sum(self.components[id_])] + order = self.ordering[id_] + v_re_ordered = np.zeros_like(v) + + for id,val in enumerate(order): + v_re_ordered[:,val] = v[:,id] + + v = v_re_ordered + + u = np.clip(u, -1, 1) + v_t = np.ones((data.shape[0], self.n_clusters)) * -100 + v_t[:, self.components[id_]] = v + v = v_t + st += 1 + np.sum(self.components[id_]) + means = self.model[id_].means_.reshape([-1]) + stds = np.sqrt(self.model[id_].covariances_).reshape([-1]) + p_argmax = np.argmax(v, axis=1) + std_t = stds[p_argmax] + mean_t = means[p_argmax] + tmp = u * 4 * std_t + mean_t + data_t[:, id_] = tmp + + elif info['type'] == "mixed": + + u = data[:, st] + full_v = data[:,(st+1):(st+1)+len(info['modal'])+np.sum(self.components[id_])] + order = self.ordering[id_] + full_v_re_ordered = np.zeros_like(full_v) + + for id,val in enumerate(order): + full_v_re_ordered[:,val] = full_v[:,id] + + full_v = full_v_re_ordered + mixed_v = full_v[:,:len(info['modal'])] + v = full_v[:,-np.sum(self.components[id_]):] + + u = np.clip(u, -1, 1) + v_t = np.ones((data.shape[0], self.n_clusters)) * -100 + v_t[:, self.components[id_]] = v + v = np.concatenate([mixed_v,v_t], axis=1) + + st += 1 + np.sum(self.components[id_]) + len(info['modal']) + means = self.model[id_][1].means_.reshape([-1]) + stds = np.sqrt(self.model[id_][1].covariances_).reshape([-1]) + p_argmax = np.argmax(v, axis=1) + + result = np.zeros_like(u) + + for idx in range(len(data)): + if p_argmax[idx] < len(info['modal']): + argmax_value = p_argmax[idx] + result[idx] = float(list(map(info['modal'].__getitem__, [argmax_value]))[0]) + else: + std_t = stds[(p_argmax[idx]-len(info['modal']))] + mean_t = means[(p_argmax[idx]-len(info['modal']))] + result[idx] = u[idx] * 4 * std_t + mean_t + + data_t[:, id_] = result + + else: + current = data[:, st:st + info['size']] + st += info['size'] + idx = np.argmax(current, axis=1) + data_t[:, id_] = list(map(info['i2s'].__getitem__, idx)) + + return data_t + +class ImageTransformer(): + + def __init__(self, side): + + self.height = side + + def transform(self, data): + + if self.height * self.height > len(data[0]): + + padding = torch.zeros((len(data), self.height * self.height - len(data[0]))).to(data.device) + data = torch.cat([data, padding], axis=1) + + return data.view(-1, 1, self.height, self.height) + + def inverse_transform(self, data): + + data = data.view(-1, self.height * self.height) + + return data + + diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/pipeline_ctabgan.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/pipeline_ctabgan.py new file mode 100644 index 0000000000000000000000000000000000000000..9ed3e80f4a226ec8e973f5f15db87540e4fa01a5 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/pipeline_ctabgan.py @@ -0,0 +1,80 @@ +import tomli +import shutil +import os +import argparse +from train_sample_ctabgan import train_ctabgan, sample_ctabgan +from scripts.eval_catboost import train_catboost +import zero +import lib + +def load_config(path) : + with open(path, 'rb') as f: + return tomli.load(f) + +def save_file(parent_dir, config_path): + try: + dst = os.path.join(parent_dir) + os.makedirs(os.path.dirname(dst), exist_ok=True) + shutil.copyfile(os.path.abspath(config_path), dst) + except shutil.SameFileError: + pass + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('--config', metavar='FILE') + parser.add_argument('--train', action='store_true', default=False) + parser.add_argument('--sample', action='store_true', default=False) + parser.add_argument('--eval', action='store_true', default=False) + parser.add_argument('--change_val', action='store_true', default=False) + + args = parser.parse_args() + raw_config = lib.load_config(args.config) + timer = zero.Timer() + timer.run() + save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config) + ctabgan = None + if args.train: + ctabgan = train_ctabgan( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + train_params=raw_config['train_params'], + change_val=args.change_val, + device=raw_config['device'] + ) + if args.sample: + sample_ctabgan( + synthesizer=ctabgan, + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + num_samples=raw_config['sample']['num_samples'], + train_params=raw_config['train_params'], + change_val=args.change_val, + seed=raw_config['sample']['seed'], + device=raw_config['device'] + ) + + save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json')) + if args.eval: + if raw_config['eval']['type']['eval_model'] == 'catboost': + train_catboost( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + eval_type=raw_config['eval']['type']['eval_type'], + T_dict=raw_config['eval']['T'], + seed=raw_config['seed'], + change_val=args.change_val + ) + # elif raw_config['eval']['type']['eval_model'] == 'mlp': + # train_mlp( + # parent_dir=raw_config['parent_dir'], + # real_data_path=raw_config['real_data_path'], + # eval_type=raw_config['eval']['type']['eval_type'], + # T_dict=raw_config['eval']['T'], + # seed=raw_config['seed'], + # change_val=args.change_val + # ) + + print(f'Elapsed time: {str(timer)}') + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/requirements.txt b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..1144dbbc7b9c35690b609f5717d766abd4ba9567 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/requirements.txt @@ -0,0 +1,6 @@ +numpy==1.21.0 +torch==1.9.1 +pandas==1.2.4 +sklearn==0.24.1 +dython==0.6.4.post1 +scipy==1.4.1 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/train_sample_ctabgan.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/train_sample_ctabgan.py new file mode 100644 index 0000000000000000000000000000000000000000..be74a48ec44624d341dda0f684780ac698ec3851 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/train_sample_ctabgan.py @@ -0,0 +1,108 @@ +import lib +import os +import numpy as np +import argparse +from pathlib import Path +from model.ctabgan import CTABGAN +import torch +import pickle + +def train_ctabgan( + parent_dir, + real_data_path, + train_params = {"batch_size": 512}, + change_val=False, + device = "cpu" +): + real_data_path = Path(real_data_path) + parent_dir = Path(parent_dir) + device = torch.device(device) + + if change_val: + X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) + else: + X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') + + X = lib.concat_to_pd(X_num_train, X_cat_train, y_train) + + X.columns = [str(_) for _ in X.columns] + + ctabgan_params = lib.load_json("CTAB-GAN/columns.json")[real_data_path.name] + train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"]) + + print(train_params) + synthesizer = CTABGAN( + df = X, + test_ratio = 0.0, + **ctabgan_params, + **train_params, + device=device + ) + + synthesizer.fit() + + # save_ctabgan(synthesizer, parent_dir) + with open(parent_dir / "ctabgan.obj", "wb") as f: + pickle.dump(synthesizer, f) + + return synthesizer + +def sample_ctabgan( + synthesizer, + parent_dir, + real_data_path, + num_samples, + train_params = {"batch_size": 512}, + change_val=False, + device="cpu", + seed=0 +): + real_data_path = Path(real_data_path) + parent_dir = Path(parent_dir) + device = torch.device(device) + + if change_val: + X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) + else: + X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') + + X = lib.concat_to_pd(X_num_train, X_cat_train, y_train) + + X.columns = [str(_) for _ in X.columns] + + ctabgan_params = lib.load_json("CTAB-GAN/columns.json")[real_data_path.name] + + cat_features = ctabgan_params["categorical_columns"] + # if synthesizer is None: + # synthesizer = load_ctabgan(X, ctabgan_params, train_params, parent_dir) + with open(parent_dir / "ctabgan.obj", 'rb') as f: + synthesizer = pickle.load(f) + synthesizer.synthesizer.generator = synthesizer.synthesizer.generator.to(device) + gen_data = synthesizer.generate_samples(num_samples, seed) + + y = gen_data['y'].values + if len(np.unique(y)) == 1: + y[0] = 1 + + X_cat = gen_data[cat_features].drop('y', axis=1).values if len(cat_features) else None + X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None + + if X_num_train is not None: + np.save(parent_dir / 'X_num_train', X_num.astype(float)) + if X_cat_train is not None: + np.save(parent_dir / 'X_cat_train', X_cat.astype(str)) + np.save(parent_dir / 'y_train', y.astype(float).astype(int)) # only clf !!! + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('real_data_path', type=str) + parser.add_argument('parent_dir', type=str) + parser.add_argument('train_size', type=int) + args = parser.parse_args() + + ctabgan = train_ctabgan(args.parent_dir, args.real_data_path, change_val=True) + sample_ctabgan(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True) + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/tune_ctabgan.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/tune_ctabgan.py new file mode 100644 index 0000000000000000000000000000000000000000..71e73f1edc23821ea1ea099a10095a6b1de032ee --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/tune_ctabgan.py @@ -0,0 +1,150 @@ +from multiprocessing.sharedctypes import RawValue +import tempfile +import subprocess +import lib +import os +import optuna +import argparse +from pathlib import Path +from train_sample_ctabgan import train_ctabgan, sample_ctabgan +from scripts.eval_catboost import train_catboost + +parser = argparse.ArgumentParser() +parser.add_argument('data_path', type=str) +parser.add_argument('train_size', type=int) +parser.add_argument('eval_type', type=str) +parser.add_argument('device', type=str) + +args = parser.parse_args() +real_data_path = args.data_path +eval_type = args.eval_type +train_size = args.train_size +device = args.device +assert eval_type in ('merged', 'synthetic') + +def objective(trial): + + lr = trial.suggest_loguniform('lr', 0.00001, 0.003) + + def suggest_dim(name): + t = trial.suggest_int(name, d_min, d_max) + return 2 ** t + + # construct model + min_n_layers, max_n_layers, d_min, d_max = 1, 4, 6, 8 + n_layers = trial.suggest_int('n_layers', min_n_layers, max_n_layers) + d_first = [suggest_dim('d_first')] if n_layers else [] + d_middle = ( + [suggest_dim('d_middle')] * (n_layers - 2) + if n_layers > 2 + else [] + ) + d_last = [suggest_dim('d_last')] if n_layers > 1 else [] + d_layers = d_first + d_middle + d_last + #### + + steps = trial.suggest_categorical('steps', [1000, 5000, 10000]) + # steps = trial.suggest_categorical('steps', [10]) + batch_size = 2 ** trial.suggest_int('batch_size', 9, 11) + random_dim = 2 ** trial.suggest_int('random_dim', 4, 7) + num_channels = 2 ** trial.suggest_int('num_channels', 4, 6) + + num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3))) + + train_params = { + "lr": lr, + "epochs": steps, + "class_dim": d_layers, + "batch_size": batch_size, + "random_dim": random_dim, + "num_channels": num_channels + } + trial.set_user_attr("train_params", train_params) + trial.set_user_attr("num_samples", num_samples) + + score = 0.0 + with tempfile.TemporaryDirectory() as dir_: + dir_ = Path(dir_) + ctabgan = train_ctabgan( + parent_dir=dir_, + real_data_path=real_data_path, + train_params=train_params, + change_val=True, + device=device + ) + + for sample_seed in range(5): + sample_ctabgan( + ctabgan, + parent_dir=dir_, + real_data_path=real_data_path, + num_samples=num_samples, + train_params=train_params, + change_val=True, + seed=sample_seed, + device=device + ) + + T_dict = { + "seed": 0, + "normalization": None, + "num_nan_policy": None, + "cat_nan_policy": None, + "cat_min_frequency": None, + "cat_encoding": None, + "y_policy": "default" + } + metrics = train_catboost( + parent_dir=dir_, + real_data_path=real_data_path, + eval_type=eval_type, + T_dict=T_dict, + change_val=True, + seed = 0 + ) + + score += metrics.get_val_score() + return score / 5 + + +study = optuna.create_study( + direction='maximize', + sampler=optuna.samplers.TPESampler(seed=0), +) + +study.optimize(objective, n_trials=35, show_progress_bar=True) + +os.makedirs(f"exp/{Path(real_data_path).name}/ctabgan/", exist_ok=True) +config = { + "parent_dir": f"exp/{Path(real_data_path).name}/ctabgan/", + "real_data_path": real_data_path, + "seed": 0, + "device": args.device, + "train_params": study.best_trial.user_attrs["train_params"], + "sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]}, + "eval": { + "type": {"eval_model": "catboost", "eval_type": eval_type}, + "T": { + "seed": 0, + "normalization": None, + "num_nan_policy": None, + "cat_nan_policy": None, + "cat_min_frequency": None, + "cat_encoding": None, + "y_policy": "default" + }, + } +} + +train_ctabgan( + parent_dir=f"exp/{Path(real_data_path).name}/ctabgan/", + real_data_path=real_data_path, + train_params=study.best_trial.user_attrs["train_params"], + change_val=False, + device=device +) + +lib.dump_config(config, config["parent_dir"]+"config.toml") + +subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}', + '10', "ctabgan", eval_type, "catboost", "5"], check=True) \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.editorconfig b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..8558c49851ee32e7577c83758bf92941054d2c5c --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.editorconfig @@ -0,0 +1,24 @@ +# http://editorconfig.org + +root = true + +[*] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true +insert_final_newline = true +charset = utf-8 +end_of_line = lf + +[*.py] +max_line_length = 99 + +[*.bat] +indent_style = tab +end_of_line = crlf + +[LICENSE] +insert_final_newline = false + +[Makefile] +indent_style = tab diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/CODEOWNERS b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..e4db0356f3f62a8480ae07791b86c28adff16739 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/CODEOWNERS @@ -0,0 +1,2 @@ +# Global rule: +* @sdv-dev/core-contributors diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/bug_report.md b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000000000000000000000000000000000000..16e0decde54dd915131ba85aa981029946dc53aa --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,33 @@ +--- +name: Bug report +about: Report an error that you found when using CTGAN +title: '' +labels: bug, pending review +assignees: '' + +--- + +### Environment Details + +Please indicate the following details about the environment in which you found the bug: + +* CTGAN version: +* Python version: +* Operating System: + +### Error Description + + + +### Steps to reproduce + + + +``` +Paste the command(s) you ran and the output. +If there was a crash, please include the traceback here. +``` diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/feature_request.md b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000000000000000000000000000000000000..54d7b6a17c3456c79fd59efaa5819d071e0101b0 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,24 @@ +--- +name: Feature request +about: Request a new feature that you would like to see implemented in CTGAN +title: '' +labels: new feature, pending review +assignees: '' + +--- + +### Problem Description + + + +### Expected behavior + + + +### Additional context + + diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/question.md b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000000000000000000000000000000000000..20aca671d77560c3c52bd7d00ae129ca2f160f8a --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,33 @@ +--- +name: Question +about: Doubts about CTGAN usage +title: '' +labels: question, pending review +assignees: '' + +--- + +### Environment details + +If you are already running CTGAN, please indicate the following details about the environment in +which you are running it: + +* CTGAN version: +* Python version: +* Operating System: + +### Problem description + + + +### What I already tried + + + +``` +Paste the command(s) you ran and the output. +If there was a crash, please include the traceback here. +``` diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/integration.yml b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/integration.yml new file mode 100644 index 0000000000000000000000000000000000000000..fdc744eeec5f5a1a18ce12ab91a8796f1c25d9fc --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/integration.yml @@ -0,0 +1,31 @@ +name: Integration Tests + +on: + - push + - pull_request + +jobs: + unit: + runs-on: ${{ matrix.os }} + strategy: + matrix: + python-version: [3.6, 3.7, 3.8, 3.9] + os: [ubuntu-latest, macos-10.15, windows-latest] + steps: + - uses: actions/checkout@v1 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - if: matrix.os == 'windows-latest' + name: Install dependencies - Windows + run: | + python -m pip install --upgrade pip + python -m pip install 'torch>=1.8,<2' -f https://download.pytorch.org/whl/cpu/torch/ + python -m pip install 'torchvision>=0.9.0,<1' -f https://download.pytorch.org/whl/cpu/torchvision/ + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install invoke .[test] + - name: Run integration tests + run: invoke integration diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/lint.yml b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/lint.yml new file mode 100644 index 0000000000000000000000000000000000000000..07dde39e9f898c598379e9bd39dac1304be9456e --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/lint.yml @@ -0,0 +1,21 @@ +name: Style Checks + +on: + - push + - pull_request + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - name: Set up Python 3.8 + uses: actions/setup-python@v2 + with: + python-version: 3.8 + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install invoke .[dev] + - name: Run lint checks + run: invoke lint diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/minimum.yml b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/minimum.yml new file mode 100644 index 0000000000000000000000000000000000000000..1989c957943adecaf4e9fb851971e961c9188b3d --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/minimum.yml @@ -0,0 +1,31 @@ +name: Unit Tests Minimum Versions + +on: + - push + - pull_request + +jobs: + minimum: + runs-on: ${{ matrix.os }} + strategy: + matrix: + python-version: [3.6, 3.7, 3.8, 3.9] + os: [ubuntu-latest, macos-10.15, windows-latest] + steps: + - uses: actions/checkout@v1 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - if: matrix.os == 'windows-latest' + name: Install dependencies - Windows + run: | + python -m pip install --upgrade pip + python -m pip install 'torch==1.8' -f https://download.pytorch.org/whl/cpu/torch/ + python -m pip install 'torchvision==0.9.0' -f https://download.pytorch.org/whl/cpu/torchvision/ + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install invoke .[test] + - name: Test with minimum versions + run: invoke minimum diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/readme.yml b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/readme.yml new file mode 100644 index 0000000000000000000000000000000000000000..5a623b543050f215dce8a6ba0d9aeecf2875b779 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/readme.yml @@ -0,0 +1,25 @@ +name: Test README + +on: + - push + - pull_request + +jobs: + readme: + runs-on: ${{ matrix.os }} + strategy: + matrix: + python-version: [3.6, 3.7, 3.8, 3.9] + os: [ubuntu-latest, macos-10.15] # skip windows bc rundoc fails + steps: + - uses: actions/checkout@v1 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install invoke rundoc . + - name: Run the README.md + run: invoke readme diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/unit.yml b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/unit.yml new file mode 100644 index 0000000000000000000000000000000000000000..6a63f0e006e1c8d3b635c441661c5ceb0282066b --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/unit.yml @@ -0,0 +1,34 @@ +name: Unit Tests + +on: + - push + - pull_request + +jobs: + unit: + runs-on: ${{ matrix.os }} + strategy: + matrix: + python-version: [3.6, 3.7, 3.8, 3.9] + os: [ubuntu-latest, macos-10.15, windows-latest] + steps: + - uses: actions/checkout@v1 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v2 + with: + python-version: ${{ matrix.python-version }} + - if: matrix.os == 'windows-latest' + name: Install dependencies - Windows + run: | + python -m pip install --upgrade pip + python -m pip install 'torch>=1.8,<2' -f https://download.pytorch.org/whl/cpu/torch/ + python -m pip install 'torchvision>=0.9.0,<1' -f https://download.pytorch.org/whl/cpu/torchvision/ + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install invoke .[test] + - name: Run unit tests + run: invoke unit + - if: matrix.os == 'ubuntu-latest' && matrix.python-version == 3.8 + name: Upload codecov report + uses: codecov/codecov-action@v2 diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.gitignore b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1609a70e22920b86a4a717e9c9aae645184b0831 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.gitignore @@ -0,0 +1,107 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ +tests/readme_test/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ +docs/api/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +# Vim +.*.swp diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.travis.yml b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..ecfa96045b11d59a33951d94e2358ea6b30646b9 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.travis.yml @@ -0,0 +1,15 @@ +# Config file for automatic testing at travis-ci.org +dist: bionic +language: python +python: + - 3.8 + - 3.7 + - 3.6 + +# Command to install dependencies +install: pip install -U tox-travis codecov + +after_success: codecov + +# Command to run tests +script: tox diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/AUTHORS.rst b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/AUTHORS.rst new file mode 100644 index 0000000000000000000000000000000000000000..1ea30d0908426597369b5193f52f1ec2b6ff4826 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/AUTHORS.rst @@ -0,0 +1,13 @@ +Credits +======= + +Research and Development Lead +----------------------------- + +* Lei Xu + +Contributors +------------ + +* Carles Sala +* Kevin Kuo diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/CONTRIBUTING.rst b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/CONTRIBUTING.rst new file mode 100644 index 0000000000000000000000000000000000000000..a21b70abaec7c75cf14208a5438d0af3dfac03b3 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/CONTRIBUTING.rst @@ -0,0 +1,237 @@ +.. highlight:: shell + +============ +Contributing +============ + +Contributions are welcome, and they are greatly appreciated! Every little bit +helps, and credit will always be given. + +You can contribute in many ways: + +Types of Contributions +---------------------- + +Report Bugs +~~~~~~~~~~~ + +Report bugs at the `GitHub Issues page`_. + +If you are reporting a bug, please include: + +* Your operating system name and version. +* Any details about your local setup that might be helpful in troubleshooting. +* Detailed steps to reproduce the bug. + +Fix Bugs +~~~~~~~~ + +Look through the GitHub issues for bugs. Anything tagged with "bug" and "help +wanted" is open to whoever wants to implement it. + +Implement Features +~~~~~~~~~~~~~~~~~~ + +Look through the GitHub issues for features. Anything tagged with "enhancement" +and "help wanted" is open to whoever wants to implement it. + +Write Documentation +~~~~~~~~~~~~~~~~~~~ + +CTGAN could always use more documentation, whether as part of the +official CTGAN docs, in docstrings, or even on the web in blog posts, +articles, and such. + +Submit Feedback +~~~~~~~~~~~~~~~ + +The best way to send feedback is to file an issue at the `GitHub Issues page`_. + +If you are proposing a feature: + +* Explain in detail how it would work. +* Keep the scope as narrow as possible, to make it easier to implement. +* Remember that this is a volunteer-driven project, and that contributions + are welcome :) + +Get Started! +------------ + +Ready to contribute? Here's how to set up `CTGAN` for local development. + +1. Fork the `CTGAN` repo on GitHub. +2. Clone your fork locally:: + + $ git clone git@github.com:your_name_here/CTGAN.git + +3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, + this is how you set up your fork for local development:: + + $ mkvirtualenv CTGAN + $ cd CTGAN/ + $ make install-develop + +4. Create a branch for local development:: + + $ git checkout -b name-of-your-bugfix-or-feature + + Try to use the naming scheme of prefixing your branch with ``gh-X`` where X is + the associated issue, such as ``gh-3-fix-foo-bug``. And if you are not + developing on your own fork, further prefix the branch with your GitHub + username, like ``githubusername/gh-3-fix-foo-bug``. + + Now you can make your changes locally. + +5. While hacking your changes, make sure to cover all your developments with the required + unit tests, and that none of the old tests fail as a consequence of your changes. + For this, make sure to run the tests suite and check the code coverage:: + + $ make lint # Check code styling + $ make test # Run the tests + $ make coverage # Get the coverage report + +6. When you're done making changes, check that your changes pass all the styling checks and + tests, including other Python supported versions, using:: + + $ make test-all + +7. Make also sure to include the necessary documentation in the code as docstrings following + the `Google docstrings style`_. + If you want to view how your documentation will look like when it is published, you can + generate and view the docs with this command:: + + $ make view-docs + +8. Commit your changes and push your branch to GitHub:: + + $ git add . + $ git commit -m "Your detailed description of your changes." + $ git push origin name-of-your-bugfix-or-feature + +9. Submit a pull request through the GitHub website. + +Pull Request Guidelines +----------------------- + +Before you submit a pull request, check that it meets these guidelines: + +1. It resolves an open GitHub Issue and contains its reference in the title or + the comment. If there is no associated issue, feel free to create one. +2. Whenever possible, it resolves only **one** issue. If your PR resolves more than + one issue, try to split it in more than one pull request. +3. The pull request should include unit tests that cover all the changed code +4. If the pull request adds functionality, the docs should be updated. Put + your new functionality into a function with a docstring, and add the + feature to the documentation in an appropriate place. +5. The pull request should work for all the supported Python versions. Check the `Travis Build + Status page`_ and make sure that all the checks pass. + +Unit Testing Guidelines +----------------------- + +All the Unit Tests should comply with the following requirements: + +1. Unit Tests should be based only in unittest and pytest modules. + +2. The tests that cover a module called ``ctgan/path/to/a_module.py`` + should be implemented in a separated module called + ``tests/ctgan/path/to/test_a_module.py``. + Note that the module name has the ``test_`` prefix and is located in a path similar + to the one of the tested module, just inside the ``tests`` folder. + +3. Each method of the tested module should have at least one associated test method, and + each test method should cover only **one** use case or scenario. + +4. Test case methods should start with the ``test_`` prefix and have descriptive names + that indicate which scenario they cover. + Names such as ``test_some_methed_input_none``, ``test_some_method_value_error`` or + ``test_some_method_timeout`` are right, but names like ``test_some_method_1``, + ``some_method`` or ``test_error`` are not. + +5. Each test should validate only what the code of the method being tested does, and not + cover the behavior of any third party package or tool being used, which is assumed to + work properly as far as it is being passed the right values. + +6. Any third party tool that may have any kind of random behavior, such as some Machine + Learning models, databases or Web APIs, will be mocked using the ``mock`` library, and + the only thing that will be tested is that our code passes the right values to them. + +7. Unit tests should not use anything from outside the test and the code being tested. This + includes not reading or writing to any file system or database, which will be properly + mocked. + +Tips +---- + +To run a subset of tests:: + + $ python -m pytest tests.test_ctgan + $ python -m pytest -k 'foo' + +Release Workflow +---------------- + +The process of releasing a new version involves several steps combining both ``git`` and +``bumpversion`` which, briefly: + +1. Merge what is in ``master`` branch into ``stable`` branch. +2. Update the version in ``setup.cfg``, ``ctgan/__init__.py`` and + ``HISTORY.md`` files. +3. Create a new git tag pointing at the corresponding commit in ``stable`` branch. +4. Merge the new commit from ``stable`` into ``master``. +5. Update the version in ``setup.cfg`` and ``ctgan/__init__.py`` + to open the next development iteration. + +.. note:: Before starting the process, make sure that ``HISTORY.md`` has been updated with a new + entry that explains the changes that will be included in the new version. + Normally this is just a list of the Pull Requests that have been merged to master + since the last release. + +Once this is done, run of the following commands: + +1. If you are releasing a patch version:: + + make release + +2. If you are releasing a minor version:: + + make release-minor + +3. If you are releasing a major version:: + + make release-major + +Release Candidates +~~~~~~~~~~~~~~~~~~ + +Sometimes it is necessary or convenient to upload a release candidate to PyPi as a pre-release, +in order to make some of the new features available for testing on other projects before they +are included in an actual full-blown release. + +In order to perform such an action, you can execute:: + + make release-candidate + +This will perform the following actions: + +1. Build and upload the current version to PyPi as a pre-release, with the format ``X.Y.Z.devN`` + +2. Bump the current version to the next release candidate, ``X.Y.Z.dev(N+1)`` + +After this is done, the new pre-release can be installed by including the ``dev`` section in the +dependency specification, either in ``setup.py``:: + + install_requires = [ + ... + 'ctgan>=X.Y.Z.dev', + ... + ] + +or in command line:: + + pip install 'ctgan>=X.Y.Z.dev' + + +.. _GitHub issues page: https://github.com/sdv-dev/CTGAN/issues +.. _Travis Build Status page: https://travis-ci.org/sdv-dev/CTGAN/pull_requests +.. _Google docstrings style: https://google.github.io/styleguide/pyguide.html?showone=Comments#Comments diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/HISTORY.md b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..df2595e5dbbc2a9c44d571d9ae63bf86670e6cf2 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/HISTORY.md @@ -0,0 +1,147 @@ +# History + +## v0.5.1 - 2022-02-25 + +This release fixes a bug with the decoder instantiation, and also allows users to set a random state for the model +fitting and sampling. + +### Issues closed + +* Update self.decoder with correct variable name - Issue [#203](https://github.com/sdv-dev/CTGAN/issues/203) by @tejuafonja +* Add random state - Issue [#204](https://github.com/sdv-dev/CTGAN/issues/204) by @katxiao + +## v0.5.0 - 2021-11-18 + +This release adds support for Python 3.9 and updates dependencies to ensure compatibility with the +rest of the SDV ecosystem, and upgrades to the latests [RDT](https://github.com/sdv-dev/RDT/releases/tag/v0.6.1) +release. + +### Issues closed + +* Add support for Python 3.9 - Issue [#177](https://github.com/sdv-dev/CTGAN/issues/177) by @pvk-developer +* Add pip check to CI workflows - Issue [#174](https://github.com/sdv-dev/CTGAN/issues/174) by @pvk-developer +* Typo in `CTGAN` code - Issue [#158](https://github.com/sdv-dev/CTGAN/issues/158) by @ori-katz100 and @fealho + +## v0.4.3 - 2021-07-12 + +Dependency upgrades to ensure compatibility with the rest of the SDV ecosystem. + +## v0.4.2 - 2021-04-27 + +In this release, the way in which the loss function of the TVAE model was computed has been fixed. +In addition, the default value of the `discriminator_decay` has been changed to a more optimal +value. Also some improvements to the tests were added. + +### Issues closed + +* `TVAE`: loss function - Issue [#143](https://github.com/sdv-dev/CTGAN/issues/143) by @fealho and @DingfanChen +* Set `discriminator_decay` to `1e-6` - Pull request [#145](https://github.com/sdv-dev/CTGAN/pull/145/) by @fealho +* Adds unit tests - Pull requests [#140](https://github.com/sdv-dev/CTGAN/pull/140) by @fealho + +## v0.4.1 - 2021-03-30 + +This release exposes all the hyperparameters which the user may find useful for both `CTGAN` +and `TVAE`. Also `TVAE` can now be fitted on datasets that are shorter than the batch +size and drops the last batch only if the data size is not divisible by the batch size. + +### Issues closed + +* `TVAE`: Adapt `batch_size` to data size - Issue [#135](https://github.com/sdv-dev/CTGAN/issues/135) by @fealho and @csala +* `ValueError` from `validate_discre_columns` with `uniqueCombinationConstraint` - Issue [133](https://github.com/sdv-dev/CTGAN/issues/133) by @fealho and @MLjungg + +## v0.4.0 - 2021-02-24 + +Maintenance relese to upgrade dependencies to ensure compatibility with the rest +of the SDV libraries. + +Also add a validation on the CTGAN `condition_column` and `condition_value` inputs. + +### Improvements + +* Validate condition_column and condition_value - Issue [#124](https://github.com/sdv-dev/CTGAN/issues/124) by @fealho + +## v0.3.1 - 2021-01-27 + +### Improvements + +* Check discrete_columns valid before fitting - [Issue #35](https://github.com/sdv-dev/CTGAN/issues/35) by @fealho + +## Bugs fixed + +* ValueError: max() arg is an empty sequence - [Issue #115](https://github.com/sdv-dev/CTGAN/issues/115) by @fealho + +## v0.3.0 - 2020-12-18 + +In this release we add a new TVAE model which was presented in the original CTGAN paper. +It also exposes more hyperparameters and moves epochs and log_frequency from fit to the constructor. + +A new verbose argument has been added to optionally disable unnecessary printing, and a new hyperparameter +called `discriminator_steps` has been added to CTGAN to control the number of optimization steps performed +in the discriminator for each generator epoch. + +The code has also been reorganized and cleaned up for better readability and interpretability. + +Special thanks to @Baukebrenninkmeijer @fealho @leix28 @csala for the contributions! + +### Improvements + +* Add TVAE - [Issue #111](https://github.com/sdv-dev/CTGAN/issues/111) by @fealho +* Move `log_frequency` to `__init__` - [Issue #102](https://github.com/sdv-dev/CTGAN/issues/102) by @fealho +* Add discriminator steps hyperparameter - [Issue #101](https://github.com/sdv-dev/CTGAN/issues/101) by @Baukebrenninkmeijer +* Code cleanup / Expose hyperparameters - [Issue #59](https://github.com/sdv-dev/CTGAN/issues/59) by @fealho and @leix28 +* Publish to conda repo - [Issue #54](https://github.com/sdv-dev/CTGAN/issues/54) by @fealho + +### Bugs fixed + +* Fixed NaN != NaN counting bug. - [Issue #100](https://github.com/sdv-dev/CTGAN/issues/100) by @fealho +* Update dependencies and testing - [Issue #90](https://github.com/sdv-dev/CTGAN/issues/90) by @csala + +## v0.2.2 - 2020-11-13 + +In this release we introduce several minor improvements to make CTGAN more versatile and +propertly support new types of data, such as categorical NaN values, as well as conditional +sampling and features to save and load models. + +Additionally, the dependency ranges and python versions have been updated to support up +to date runtimes. + +Many thanks @fealho @leix28 @csala @oregonpillow and @lurosenb for working on making this release possible! + +### Improvements + +* Drop Python 3.5 support - [Issue #79](https://github.com/sdv-dev/CTGAN/issues/79) by @fealho +* Support NaN values in categorical variables - [Issue #78](https://github.com/sdv-dev/CTGAN/issues/78) by @fealho +* Sample synthetic data conditioning on a discrete column - [Issue #69](https://github.com/sdv-dev/CTGAN/issues/69) by @leix28 +* Support recent versions of pandas - [Issue #57](https://github.com/sdv-dev/CTGAN/issues/57) by @csala +* Easy solution for restoring original dtypes - [Issue #26](https://github.com/sdv-dev/CTGAN/issues/26) by @oregonpillow + +### Bugs fixed + +* Loss to nan - [Issue #73](https://github.com/sdv-dev/CTGAN/issues/73) by @fealho +* Swapped the sklearn utils testing import statement - [Issue #53](https://github.com/sdv-dev/CTGAN/issues/53) by @lurosenb + +## v0.2.1 - 2020-01-27 + +Minor version including changes to ensure the logs are properly printed and +the option to disable the log transformation to the discrete column frequencies. + +Special thanks to @kevinykuo for the contributions! + +### Issues Resolved: + +* Option to sample from true data frequency instead of logged frequency - [Issue #16](https://github.com/sdv-dev/CTGAN/issues/16) by @kevinykuo +* Flush stdout buffer for epoch updates - [Issue #14](https://github.com/sdv-dev/CTGAN/issues/14) by @kevinykuo + +## v0.2.0 - 2019-12-18 + +Reorganization of the project structure with a new Python API, new Command Line Interface +and increased data format support. + +### Issues Resolved: + +* Reorganize the project structure - [Issue #10](https://github.com/sdv-dev/CTGAN/issues/10) by @csala +* Move epochs to the fit method - [Issue #5](https://github.com/sdv-dev/CTGAN/issues/5) by @csala + +## v0.1.0 - 2019-11-07 + +First Release - NeurIPS 2019 Version. diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/LICENSE b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f6f8213bcfc525df1b533a0dd4b06f05f9a14ea8 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2019, MIT Data To AI Lab + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/MANIFEST.in b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..469520f584a4ffc098d13e23c0d273f89e01a06e --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/MANIFEST.in @@ -0,0 +1,11 @@ +include AUTHORS.rst +include CONTRIBUTING.rst +include HISTORY.md +include LICENSE +include README.md + +recursive-include tests * +recursive-exclude * __pycache__ +recursive-exclude * *.py[co] + +recursive-include docs *.md *.rst conf.py Makefile make.bat *.jpg *.png *.gif diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/Makefile b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..bb667a145994b12c34f88661ec6a566f06a4518d --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/Makefile @@ -0,0 +1,240 @@ +.DEFAULT_GOAL := help + +define BROWSER_PYSCRIPT +import os, webbrowser, sys + +try: + from urllib import pathname2url +except: + from urllib.request import pathname2url + +webbrowser.open("file://" + pathname2url(os.path.abspath(sys.argv[1]))) +endef +export BROWSER_PYSCRIPT + +define PRINT_HELP_PYSCRIPT +import re, sys + +for line in sys.stdin: + match = re.match(r'^([a-zA-Z_-]+):.*?## (.*)$$', line) + if match: + target, help = match.groups() + print("%-20s %s" % (target, help)) +endef +export PRINT_HELP_PYSCRIPT + +BROWSER := python -c "$$BROWSER_PYSCRIPT" + +.PHONY: help +help: + @python -c "$$PRINT_HELP_PYSCRIPT" < $(MAKEFILE_LIST) + + +# CLEAN TARGETS + +.PHONY: clean-build +clean-build: ## remove build artifacts + rm -fr build/ + rm -fr dist/ + rm -fr .eggs/ + find . -name '*.egg-info' -exec rm -fr {} + + find . -name '*.egg' -exec rm -f {} + + +.PHONY: clean-pyc +clean-pyc: ## remove Python file artifacts + find . -name '*.pyc' -exec rm -f {} + + find . -name '*.pyo' -exec rm -f {} + + find . -name '*~' -exec rm -f {} + + find . -name '__pycache__' -exec rm -fr {} + + +.PHONY: clean-coverage +clean-coverage: ## remove coverage artifacts + rm -f .coverage + rm -f .coverage.* + rm -fr htmlcov/ + +.PHONY: clean-test +clean-test: ## remove test artifacts + rm -fr .tox/ + rm -fr .pytest_cache + +.PHONY: clean +clean: clean-build clean-pyc clean-test clean-coverage ## remove all build, test, coverage and Python artifacts + + +# INSTALL TARGETS + +.PHONY: install +install: clean-build clean-pyc ## install the package to the active Python's site-packages + pip install . + +.PHONY: install-test +install-test: clean-build clean-pyc ## install the package and test dependencies + pip install .[test] + +.PHONY: install-develop +install-develop: clean-build clean-pyc ## install the package in editable mode and dependencies for development + pip install -e .[dev] + +MINIMUM := $(shell sed -n '/install_requires = \[/,/]/p' setup.py | head -n-1 | tail -n+2 | sed 's/ *\(.*\),$?$$/\1/g' | tr '>' '=') + +.PHONY: install-minimum +install-minimum: ## install the minimum supported versions of the package dependencies + pip install $(MINIMUM) + + +# LINT TARGETS + + +.PHONY: lint +lint: ## check style with flake8 and isort + invoke lint + +.PHONY: fix-lint +fix-lint: ## fix lint issues using autoflake, autopep8, and isort + find ctgan tests -name '*.py' | xargs autoflake --in-place --remove-all-unused-imports --remove-unused-variables + autopep8 --in-place --recursive --aggressive ctgan tests + isort --apply --atomic --recursive ctgan tests + + +# TEST TARGETS + +.PHONY: test-unit +test-unit: ## run unit tests using pytest + invoke unit + +.PHONY: test-integration +test-integration: ## run integration tests using pytest + invoke integration + +.PHONY: test-readme +test-readme: ## run the readme snippets + invoke readme + +.PHONY: check-dependencies +check-dependencies: ## test if there are any broken dependencies + pip check + +.PHONY: test +test: test-unit test-integration test-readme ## test everything that needs test dependencies + +.PHONY: test-devel +test-devel: lint ## test everything that needs development dependencies + +.PHONY: test-all +test-all: ## run tests on every Python version with tox + tox -r + + +.PHONY: coverage +coverage: ## check code coverage quickly with the default Python + coverage run --source ctgan -m pytest + coverage report -m + coverage html + $(BROWSER) htmlcov/index.html + + +# RELEASE TARGETS + +.PHONY: dist +dist: clean ## builds source and wheel package + python setup.py sdist + python setup.py bdist_wheel + ls -l dist + +.PHONY: publish-confirm +publish-confirm: + @echo "WARNING: This will irreversibly upload a new version to PyPI!" + @echo -n "Please type 'confirm' to proceed: " \ + && read answer \ + && [ "$${answer}" = "confirm" ] + +.PHONY: publish-test +publish-test: dist publish-confirm ## package and upload a release on TestPyPI + twine upload --repository-url https://test.pypi.org/legacy/ dist/* + +.PHONY: publish +publish: dist publish-confirm ## package and upload a release + twine upload dist/* + +.PHONY: bumpversion-release +bumpversion-release: ## Merge master to stable and bumpversion release + git checkout stable || git checkout -b stable + git merge --no-ff master -m"make release-tag: Merge branch 'master' into stable" + bumpversion release + git push --tags origin stable + +.PHONY: bumpversion-release-test +bumpversion-release-test: ## Merge master to stable and bumpversion release + git checkout stable || git checkout -b stable + git merge --no-ff master -m"make release-tag: Merge branch 'master' into stable" + bumpversion release --no-tag + @echo git push --tags origin stable + +.PHONY: bumpversion-patch +bumpversion-patch: ## Merge stable to master and bumpversion patch + git checkout master + git merge stable + bumpversion --no-tag patch + git push + +.PHONY: bumpversion-candidate +bumpversion-candidate: ## Bump the version to the next candidate + bumpversion candidate --no-tag + +.PHONY: bumpversion-minor +bumpversion-minor: ## Bump the version the next minor skipping the release + bumpversion --no-tag minor + +.PHONY: bumpversion-major +bumpversion-major: ## Bump the version the next major skipping the release + bumpversion --no-tag major + +.PHONY: bumpversion-revert +bumpversion-revert: ## Undo a previous bumpversion-release + git checkout master + git branch -D stable + +CLEAN_DIR := $(shell git status --short | grep -v ??) +CURRENT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD 2>/dev/null) +CHANGELOG_LINES := $(shell git diff HEAD..origin/stable HISTORY.md 2>&1 | wc -l) + +.PHONY: check-clean +check-clean: ## Check if the directory has uncommitted changes +ifneq ($(CLEAN_DIR),) + $(error There are uncommitted changes) +endif + +.PHONY: check-master +check-master: ## Check if we are in master branch +ifneq ($(CURRENT_BRANCH),master) + $(error Please make the release from master branch\n) +endif + +.PHONY: check-history +check-history: ## Check if HISTORY.md has been modified +ifeq ($(CHANGELOG_LINES),0) + $(error Please insert the release notes in HISTORY.md before releasing) +endif + +.PHONY: check-release +check-release: check-clean check-master check-history ## Check if the release can be made + @echo "A new release can be made" + +.PHONY: release +release: check-release bumpversion-release publish bumpversion-patch + +.PHONY: release-test +release-test: check-release bumpversion-release-test publish-test bumpversion-revert + +.PHONY: release-candidate +release-candidate: check-master publish bumpversion-candidate + +.PHONY: release-candidate-test +release-candidate-test: check-clean check-master publish-test + +.PHONY: release-minor +release-minor: check-release bumpversion-minor release + +.PHONY: release-major +release-major: check-release bumpversion-major release diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/README.md b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6c8ab04c4ff5f505eaf5f1bf68c55f0161593f07 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/README.md @@ -0,0 +1,182 @@ +
+
+

+ This repository is part of The Synthetic Data Vault Project, a project from DataCebo. +

+ +[![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) +[![PyPI Shield](https://img.shields.io/pypi/v/ctgan.svg)](https://pypi.python.org/pypi/ctgan) +[![Unit Tests](https://github.com/sdv-dev/CTGAN/actions/workflows/unit.yml/badge.svg)](https://github.com/sdv-dev/CTGAN/actions/workflows/unit.yml) +[![Downloads](https://pepy.tech/badge/ctgan)](https://pepy.tech/project/ctgan) +[![Coverage Status](https://codecov.io/gh/sdv-dev/CTGAN/branch/master/graph/badge.svg)](https://codecov.io/gh/sdv-dev/CTGAN) + +
+
+

+ + + +

+
+ +
+ +# Overview + +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. + +| Important Links | | +| --------------------------------------------- | -------------------------------------------------------------------- | +| :computer: **[Website]** | Check out the SDV Website for more information about the project. | +| :orange_book: **[SDV Blog]** | Regular publshing of useful content about Synthetic Data Generation. | +| :book: **[Documentation]** | Quickstarts, User and Development Guides, and API Reference. | +| :octocat: **[Repository]** | The link to the Github Repository of this library. | +| :scroll: **[License]** | The entire ecosystem is published under the MIT License. | +| :keyboard: **[Development Status]** | This software is in its Pre-Alpha stage. | +| [![][Slack Logo] **Community**][Community] | Join our Slack Workspace for announcements and discussions. | +| [![][MyBinder Logo] **Tutorials**][Tutorials] | Run the SDV Tutorials in a Binder environment. | + +[Website]: https://sdv.dev +[SDV Blog]: https://sdv.dev/blog +[Documentation]: https://sdv.dev/SDV +[Repository]: https://github.com/sdv-dev/CTGAN +[License]: https://github.com/sdv-dev/CTGAN/blob/master/LICENSE +[Development Status]: https://pypi.org/search/?c=Development+Status+%3A%3A+2+-+Pre-Alpha +[Slack Logo]: https://github.com/sdv-dev/SDV/blob/master/docs/images/slack.png +[Community]: https://join.slack.com/t/sdv-space/shared_invite/zt-gdsfcb5w-0QQpFMVoyB2Yd6SRiMplcw +[MyBinder Logo]: https://github.com/sdv-dev/SDV/blob/master/docs/images/mybinder.png +[Tutorials]: https://mybinder.org/v2/gh/sdv-dev/SDV/master?filepath=tutorials + +## Implemented Models + +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: +* [CTGAN User Guide](https://sdv.dev/SDV/user_guides/single_table/ctgan.html). +* [TVAE User Guide](https://sdv.dev/SDV/user_guides/single_table/tvae.html). + +# Install + +**CTGAN** is part of the **SDV** project and is automatically installed alongside it. For +details about this process please visit the [SDV Installation Guide]( +https://sdv.dev/SDV/getting_started/install.html) + +Optionally, **CTGAN** can also be installed as a standalone library using the following commands: + +**Using `pip`:** + +```bash +pip install ctgan +``` + +**Using `conda`:** + +```bash +conda install -c pytorch -c conda-forge ctgan +``` + +For more installation options please visit the [CTGAN installation Guide](INSTALL.md) + +# Usage Example + +> :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). + +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: + +* **Continuous Columns**: can contain any numerical value. +* **Discrete Columns**: contain a finite number values, whether these are string values or not. + +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. + + +```python3 +from ctgan import CTGANSynthesizer +from ctgan import load_demo + +data = load_demo() + +# Names of the columns that are discrete +discrete_columns = [ + 'workclass', + 'education', + 'marital-status', + 'occupation', + 'relationship', + 'race', + 'sex', + 'native-country', + 'income' +] + +ctgan = CTGANSynthesizer(epochs=10) +ctgan.fit(data, discrete_columns) + +# Synthetic copy +samples = ctgan.sample(1000) +``` + + + +# Join our community + + +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. +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#/). +3. Also, do not forget to check the [project documentation site](https://sdv.dev/SDV/)! + + +# Citing TGAN + +If you use CTGAN, please cite the following work: + +- *Lei Xu, Maria Skoularidou, Alfredo Cuesta-Infante, Kalyan Veeramachaneni.* **Modeling Tabular data using Conditional GAN**. NeurIPS, 2019. + +```LaTeX +@inproceedings{xu2019modeling, + title={Modeling Tabular data using Conditional GAN}, + author={Xu, Lei and Skoularidou, Maria and Cuesta-Infante, Alfredo and Veeramachaneni, Kalyan}, + booktitle={Advances in Neural Information Processing Systems}, + year={2019} +} +``` + +# Related Projects +Please note that these libraries are external contributions and are not maintained nor supervised by +the MIT DAI-Lab team. + +## R interface for CTGAN + +A wrapper around **CTGAN** has been implemented by Kevin Kuo @kevinykuo, bringing the functionalities +of **CTGAN** to **R** users. + +More details can be found in the corresponding repository: https://github.com/kasaai/ctgan + +## CTGAN Server CLI + +A package to easily deploy **CTGAN** onto a remote server. This package is developed by Timothy Pillow @oregonpillow. + +More details can be found in the corresponding repository: https://github.com/oregonpillow/ctgan-server-cli + +--- + + +
+ +
+
+
+ +[The Synthetic Data Vault Project](https://sdv.dev) was first created at MIT's [Data to AI Lab]( +https://dai.lids.mit.edu/) in 2016. After 4 years of research and traction with enterprise, we +created [DataCebo](https://datacebo.com) in 2020 with the goal of growing the project. +Today, DataCebo is the proud developer of SDV, the largest ecosystem for +synthetic data generation & evaluation. It is home to multiple libraries that support synthetic +data, including: + +* 🔄 Data discovery & transformation. Reverse the transforms to reproduce realistic data. +* 🧠 Multiple machine learning models -- ranging from Copulas to Deep Learning -- to create tabular, + multi table and time series data. +* 📊 Measuring quality and privacy of synthetic data, and comparing different synthetic data + generation models. + +[Get started using the SDV package](https://sdv.dev/SDV/getting_started/install.html) -- a fully +integrated solution and your one-stop shop for synthetic data. Or, use the standalone libraries +for specific needs. diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/README.md b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/README.md new file mode 100644 index 0000000000000000000000000000000000000000..92e2ec5aa40b081c940ac1e918efaeeed8623584 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/README.md @@ -0,0 +1,29 @@ +## Instructions + +These are instructions to deploy the latest version of **CTGAN** to [conda](https://docs.conda.io/en/latest/). +It should be done after every new release. + +## Update the recipe +Prior to making the release on PyPI, you should update the meta.yaml to reflect any changes in the dependencies. +Note that you do not need to edit the version number as that is managed by bumpversion. + +## Make the PyPI release +Follow the standard release instructions to make a PyPI release. Then, return here to make the conda release. + +## Build a package +As part of the PyPI release, you will have updated the stable branch. You should now check out the stable +branch and build the conda package. + +```bash +git checkout stable +cd conda +conda build -c sdv-dev -c pytorch -c conda-forge . +``` + +## Upload to Anaconda +Finally, you can upload the resulting package to Anaconda. + +```bash +anaconda login +anaconda upload -u sdv-dev +``` \ No newline at end of file diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/meta.yaml b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/meta.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9d26c28c6ada4f4977d517986a05ceca138c7090 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/meta.yaml @@ -0,0 +1,51 @@ +{% set name = 'ctgan' %} +{% set version = '0.5.2.dev0' %} + +package: + name: "{{ name|lower }}" + version: "{{ version }}" + +source: + url: "https://pypi.io/packages/source/{{ name[0] }}/{{ name }}/{{ name }}-{{ version }}.tar.gz" + +build: + number: 0 + noarch: python + entry_points: + - ctgan=ctgan.__main__:main + script: "{{ PYTHON }} -m pip install . -vv" + +requirements: + host: + - pip + - pytest-runner + - packaging >=20,<22 + - python >=3.6,<3.10 + - numpy >=1.18.0,<2 + - pandas >=1.1.3,<2 + - scikit-learn >=0.24,<1 + - pytorch >=1.8.0,<2 + - torchvision >=0.9.0,<1 + - rdt >=0.6.2,<0.7 + run: + - packaging >=20,<22 + - python >=3.6,<3.10 + - numpy >=1.18.0,<2 + - pandas >=1.1.3,<2 + - scikit-learn >=0.24,<1 + - pytorch >=1.8.0,<2 + - torchvision >=0.9.0,<1 + - rdt >=0.6.2,<0.7 + +about: + home: "https://github.com/sdv-dev/CTGAN" + license: MIT + license_family: MIT + license_file: + summary: "Conditional GAN for Tabular Data" + doc_url: + dev_url: + +extra: + recipe-maintainers: + - sdv-dev diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__init__.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3abb1c03b685802c21428ba050b1620e1a435fa --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__init__.py @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- + +"""Top-level package for ctgan.""" + +__author__ = 'MIT Data To AI Lab' +__email__ = 'dailabmit@gmail.com' +__version__ = '0.5.2.dev0' + +from .demo import load_demo +from .synthesizers.ctgan import CTGANSynthesizer +from .synthesizers.tvae import TVAESynthesizer + +__all__ = ( + 'CTGANSynthesizer', + 'TVAESynthesizer', + 'load_demo' +) diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__main__.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..8291c1879b60d0de49db79fb6ca60d33f09c8763 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__main__.py @@ -0,0 +1,102 @@ +"""CLI.""" + +import argparse + +from ctgan.data import read_csv, read_tsv, write_tsv +from ctgan.synthesizers.ctgan import CTGANSynthesizer + + +def _parse_args(): + parser = argparse.ArgumentParser(description='CTGAN Command Line Interface') + parser.add_argument('-e', '--epochs', default=300, type=int, + help='Number of training epochs') + parser.add_argument('-t', '--tsv', action='store_true', + help='Load data in TSV format instead of CSV') + parser.add_argument('--no-header', dest='header', action='store_false', + help='The CSV file has no header. Discrete columns will be indices.') + + parser.add_argument('-m', '--metadata', help='Path to the metadata') + parser.add_argument('-d', '--discrete', + help='Comma separated list of discrete columns without whitespaces.') + parser.add_argument('-n', '--num-samples', type=int, + help='Number of rows to sample. Defaults to the training data size') + + parser.add_argument('--generator_lr', type=float, default=2e-4, + help='Learning rate for the generator.') + parser.add_argument('--discriminator_lr', type=float, default=2e-4, + help='Learning rate for the discriminator.') + + parser.add_argument('--generator_decay', type=float, default=1e-6, + help='Weight decay for the generator.') + parser.add_argument('--discriminator_decay', type=float, default=0, + help='Weight decay for the discriminator.') + + parser.add_argument('--embedding_dim', type=int, default=128, + help='Dimension of input z to the generator.') + parser.add_argument('--generator_dim', type=str, default='256,256', + help='Dimension of each generator layer. ' + 'Comma separated integers with no whitespaces.') + parser.add_argument('--discriminator_dim', type=str, default='256,256', + help='Dimension of each discriminator layer. ' + 'Comma separated integers with no whitespaces.') + + parser.add_argument('--batch_size', type=int, default=500, + help='Batch size. Must be an even number.') + parser.add_argument('--save', default=None, type=str, + help='A filename to save the trained synthesizer.') + parser.add_argument('--load', default=None, type=str, + help='A filename to load a trained synthesizer.') + + parser.add_argument('--sample_condition_column', default=None, type=str, + help='Select a discrete column name.') + parser.add_argument('--sample_condition_column_value', default=None, type=str, + help='Specify the value of the selected discrete column.') + + parser.add_argument('data', help='Path to training data') + parser.add_argument('output', help='Path of the output file') + + return parser.parse_args() + + +def main(): + """CLI.""" + args = _parse_args() + if args.tsv: + data, discrete_columns = read_tsv(args.data, args.metadata) + else: + data, discrete_columns = read_csv(args.data, args.metadata, args.header, args.discrete) + + if args.load: + model = CTGANSynthesizer.load(args.load) + else: + generator_dim = [int(x) for x in args.generator_dim.split(',')] + discriminator_dim = [int(x) for x in args.discriminator_dim.split(',')] + model = CTGANSynthesizer( + embedding_dim=args.embedding_dim, generator_dim=generator_dim, + discriminator_dim=discriminator_dim, generator_lr=args.generator_lr, + generator_decay=args.generator_decay, discriminator_lr=args.discriminator_lr, + discriminator_decay=args.discriminator_decay, batch_size=args.batch_size, + epochs=args.epochs) + model.fit(data, discrete_columns) + + if args.save is not None: + model.save(args.save) + + num_samples = args.num_samples or len(data) + + if args.sample_condition_column is not None: + assert args.sample_condition_column_value is not None + + sampled = model.sample( + num_samples, + args.sample_condition_column, + args.sample_condition_column_value) + + if args.tsv: + write_tsv(sampled, args.metadata, args.output) + else: + sampled.to_csv(args.output, index=False) + + +if __name__ == '__main__': + main() diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3ec72e9ec972f9c7d148b66f212bf3e366a340 --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data.py @@ -0,0 +1,94 @@ +"""Data loading.""" + +import json + +import numpy as np +import pandas as pd + + +def read_csv(csv_filename, meta_filename=None, header=True, discrete=None): + """Read a csv file.""" + data = pd.read_csv(csv_filename, header='infer' if header else None) + + if meta_filename: + with open(meta_filename) as meta_file: + metadata = json.load(meta_file) + + discrete_columns = [ + column['name'] + for column in metadata['columns'] + if column['type'] != 'continuous' + ] + + elif discrete: + discrete_columns = discrete.split(',') + if not header: + discrete_columns = [int(i) for i in discrete_columns] + + else: + discrete_columns = [] + + return data, discrete_columns + + +def read_tsv(data_filename, meta_filename): + """Read a tsv file.""" + with open(meta_filename) as f: + column_info = f.readlines() + + column_info_raw = [ + x.replace('{', ' ').replace('}', ' ').split() + for x in column_info + ] + + discrete = [] + continuous = [] + column_info = [] + + for idx, item in enumerate(column_info_raw): + if item[0] == 'C': + continuous.append(idx) + column_info.append((float(item[1]), float(item[2]))) + else: + assert item[0] == 'D' + discrete.append(idx) + column_info.append(item[1:]) + + meta = { + 'continuous_columns': continuous, + 'discrete_columns': discrete, + 'column_info': column_info + } + + with open(data_filename) as f: + lines = f.readlines() + + data = [] + for row in lines: + row_raw = row.split() + row = [] + for idx, col in enumerate(row_raw): + if idx in continuous: + row.append(col) + else: + assert idx in discrete + row.append(column_info[idx].index(col)) + + data.append(row) + + return np.asarray(data, dtype='float32'), meta['discrete_columns'] + + +def write_tsv(data, meta, output_filename): + """Write to a tsv file.""" + with open(output_filename, 'w') as f: + + for row in data: + for idx, col in enumerate(row): + if idx in meta['continuous_columns']: + print(col, end=' ', file=f) + else: + assert idx in meta['discrete_columns'] + print(meta['column_info'][idx][int(col)], end=' ', file=f) + + print(file=f) diff --git a/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_sampler.py b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..5cbf339dac0980c5368d2d11e2934a268fb9d43a --- /dev/null +++ b/SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_sampler.py @@ -0,0 +1,156 @@ +"""DataSampler module.""" + +import numpy as np + + +class DataSampler(object): + """DataSampler samples the conditional vector and corresponding data for CTGAN.""" + + def __init__(self, data, output_info, log_frequency): + self._data = data + + def is_discrete_column(column_info): + return (len(column_info) == 1 + and column_info[0].activation_fn == 'softmax') + + n_discrete_columns = sum( + [1 for column_info in output_info if is_discrete_column(column_info)]) + + self._discrete_column_matrix_st = np.zeros( + n_discrete_columns, dtype='int32') + + # Store the row id for each category in each discrete column. + # For example _rid_by_cat_cols[a][b] is a list of all rows with the + # a-th discrete column equal value b. + self._rid_by_cat_cols = [] + + # Compute _rid_by_cat_cols + st = 0 + for column_info in output_info: + if is_discrete_column(column_info): + span_info = column_info[0] + ed = st + span_info.dim + + rid_by_cat = [] + for j in range(span_info.dim): + rid_by_cat.append(np.nonzero(data[:, st + j])[0]) + self._rid_by_cat_cols.append(rid_by_cat) + st = ed + else: + st += sum([span_info.dim for span_info in column_info]) + assert st == data.shape[1] + + # Prepare an interval matrix for efficiently sample conditional vector + max_category = max([ + column_info[0].dim + for column_info in output_info + if is_discrete_column(column_info) + ], default=0) + + self._discrete_column_cond_st = np.zeros(n_discrete_columns, dtype='int32') + self._discrete_column_n_category = np.zeros(n_discrete_columns, dtype='int32') + self._discrete_column_category_prob = np.zeros((n_discrete_columns, max_category)) + self._n_discrete_columns = n_discrete_columns + self._n_categories = sum([ + column_info[0].dim + for column_info in output_info + if is_discrete_column(column_info) + ]) + + st = 0 + current_id = 0 + current_cond_st = 0 + for column_info in output_info: + if is_discrete_column(column_info): + span_info = column_info[0] + ed = st + span_info.dim + category_freq = np.sum(data[:, st:ed], axis=0) + if log_frequency: + category_freq = np.log(category_freq + 1) + category_prob = category_freq / np.sum(category_freq) + self._discrete_column_category_prob[current_id, :span_info.dim] = category_prob + self._discrete_column_cond_st[current_id] = current_cond_st + self._discrete_column_n_category[current_id] = span_info.dim + current_cond_st += span_info.dim + current_id += 1 + st = ed + else: + st += sum([span_info.dim for span_info in column_info]) + + def _random_choice_prob_index(self, discrete_column_id): + probs = self._discrete_column_category_prob[discrete_column_id] + r = np.expand_dims(np.random.rand(probs.shape[0]), axis=1) + return (probs.cumsum(axis=1) > r).argmax(axis=1) + + def sample_condvec(self, batch): + """Generate the conditional vector for training. + + Returns: + cond (batch x #categories): + The conditional vector. + mask (batch x #discrete columns): + A one-hot vector indicating the selected discrete column. + discrete column id (batch): + Integer representation of mask. + category_id_in_col (batch): + Selected category in the selected discrete column. + """ + if self._n_discrete_columns == 0: + return None + + discrete_column_id = np.random.choice( + np.arange(self._n_discrete_columns), batch) + + cond = np.zeros((batch, self._n_categories), dtype='float32') + mask = np.zeros((batch, self._n_discrete_columns), dtype='float32') + mask[np.arange(batch), discrete_column_id] = 1 + category_id_in_col = self._random_choice_prob_index(discrete_column_id) + category_id = (self._discrete_column_cond_st[discrete_column_id] + category_id_in_col) + cond[np.arange(batch), category_id] = 1 + + return cond, mask, discrete_column_id, category_id_in_col + + def sample_original_condvec(self, batch): + """Generate the conditional vector for generation use original frequency.""" + if self._n_discrete_columns == 0: + return None + + cond = np.zeros((batch, self._n_categories), dtype='float32') + + for i in range(batch): + row_idx = np.random.randint(0, len(self._data)) + col_idx = np.random.randint(0, self._n_discrete_columns) + matrix_st = self._discrete_column_matrix_st[col_idx] + matrix_ed = matrix_st + self._discrete_column_n_category[col_idx] + pick = np.argmax(self._data[row_idx, matrix_st:matrix_ed]) + cond[i, pick + self._discrete_column_cond_st[col_idx]] = 1 + + return cond + + def sample_data(self, n, col, opt): + """Sample data from original training data satisfying the sampled conditional vector. + + Returns: + n rows of matrix data. + """ + if col is None: + idx = np.random.randint(len(self._data), size=n) + return self._data[idx] + + idx = [] + for c, o in zip(col, opt): + idx.append(np.random.choice(self._rid_by_cat_cols[c][o])) + + return self._data[idx] + + def dim_cond_vec(self): + """Return the total number of categories.""" + return self._n_categories + + def generate_cond_from_condition_column_info(self, condition_info, batch): + """Generate the condition vector.""" + vec = np.zeros((batch, self._n_categories), dtype='float32') + id_ = self._discrete_column_matrix_st[condition_info['discrete_column_id']] + id_ += condition_info['value_id'] + vec[:, id_] = 1 + return vec