diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/ctabgan.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/ctabgan.py new file mode 100644 index 0000000000000000000000000000000000000000..81782dcde9f07f3d8178c29ba08ceb129c40f58f --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/ctabgan.py @@ -0,0 +1,70 @@ +""" +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]}, + general_columns = ["age"], + non_categorical_columns = [], + integer_columns = ['age', 'fnlwgt','capital-gain', 'capital-loss','hours-per-week'], + problem_type= {"Classification": "income"}, + class_dim=(256, 256, 256, 256), + random_dim=100, + num_channels=64, + l2scale=1e-5, + batch_size=500, + epochs=150, + device="cpu"): + + self.__name__ = 'CTABGAN' + + self.synthesizer = CTABGANSynthesizer( + class_dim=class_dim, + random_dim=random_dim, + num_channels=num_channels, + l2scale=l2scale, + 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, seed=0): + + sample = self.synthesizer.sample(len(self.raw_df), seed) + sample_df = self.data_prep.inverse_prep(sample) + + return sample_df diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/eval/evaluation.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/eval/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..1492fcf80cfb907f95b3844e4c0f38f15effbdb0 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/pipeline/data_preparation.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/pipeline/data_preparation.py new file mode 100644 index 0000000000000000000000000000000000000000..abe1f725f7d09f7284abef0dd9c1187f0e3c96bf --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/pipeline/data_preparation.py @@ -0,0 +1,130 @@ +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[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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/privacy_utils/rdp_accountant.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/privacy_utils/rdp_accountant.py new file mode 100644 index 0000000000000000000000000000000000000000..5e225cbb0994fa6b9e9726f38d873754bbfe82cf --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/ctabgan_synthesizer.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/ctabgan_synthesizer.py new file mode 100644 index 0000000000000000000000000000000000000000..9fd6845ffaf8f3a991acceba92af143941e5c11f --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/ctabgan_synthesizer.py @@ -0,0 +1,601 @@ +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 + + +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, + 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.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, 64] + 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, 64] + 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=2e-4, 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): + + 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(self.batch_size, self.random_dim, device=self.device) + condvec = self.cond_generator.sample(self.batch_size) + c = condvec + c = torch.from_numpy(c).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) + + 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) + + while len(result) < n: + data_resample = [] + steps_left = resample// self.batch_size + 1 + + for i in range(steps_left): + noisez = torch.randn(self.batch_size, self.random_dim, device=self.device) + condvec = self.cond_generator.sample(self.batch_size) + c = condvec + c = torch.from_numpy(c).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) + + 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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model copy/synthesizer/transformer.py b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/ctabgan.py new file mode 100644 index 0000000000000000000000000000000000000000..a99b5d587da5f3e49b3923e43975e02e9c11e6e1 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/eval/evaluation.py b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/pipeline/data_preparation.py b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/privacy_utils/rdp_accountant.py b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/ctabgan_synthesizer.py b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/model/synthesizer/transformer.py b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/__init__.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/ctabgan.py new file mode 100644 index 0000000000000000000000000000000000000000..d12c1a3c05d486c698bca7012d45bf31bc50ffbf --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/eval/evaluation.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc965efb802eac7263640e94ffba0cbdfff8c7e --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/pipeline/data_preparation.py b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/ctabgan_synthesizer.py b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/transformer.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/model/synthesizer/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..18fc3c492a99c7f2455ebf2c2cddf09525333b92 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.editorconfig b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.editorconfig new file mode 100644 index 0000000000000000000000000000000000000000..8558c49851ee32e7577c83758bf92941054d2c5c --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/CODEOWNERS b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/CODEOWNERS new file mode 100644 index 0000000000000000000000000000000000000000..e4db0356f3f62a8480ae07791b86c28adff16739 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/bug_report.md b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/feature_request.md b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/ISSUE_TEMPLATE/question.md b/syntheticSuccess/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/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/integration.yml b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/integration.yml new file mode 100644 index 0000000000000000000000000000000000000000..fdc744eeec5f5a1a18ce12ab91a8796f1c25d9fc --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/lint.yml b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/lint.yml new file mode 100644 index 0000000000000000000000000000000000000000..07dde39e9f898c598379e9bd39dac1304be9456e --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/minimum.yml b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/minimum.yml new file mode 100644 index 0000000000000000000000000000000000000000..1989c957943adecaf4e9fb851971e961c9188b3d --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/readme.yml b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/readme.yml new file mode 100644 index 0000000000000000000000000000000000000000..5a623b543050f215dce8a6ba0d9aeecf2875b779 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/unit.yml b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.github/workflows/unit.yml new file mode 100644 index 0000000000000000000000000000000000000000..6a63f0e006e1c8d3b635c441661c5ceb0282066b --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.gitignore b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..1609a70e22920b86a4a717e9c9aae645184b0831 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.travis.yml b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..ecfa96045b11d59a33951d94e2358ea6b30646b9 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/AUTHORS.rst b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/AUTHORS.rst new file mode 100644 index 0000000000000000000000000000000000000000..1ea30d0908426597369b5193f52f1ec2b6ff4826 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/CONTRIBUTING.rst b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/CONTRIBUTING.rst new file mode 100644 index 0000000000000000000000000000000000000000..a21b70abaec7c75cf14208a5438d0af3dfac03b3 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/HISTORY.md b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/HISTORY.md new file mode 100644 index 0000000000000000000000000000000000000000..df2595e5dbbc2a9c44d571d9ae63bf86670e6cf2 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/LICENSE b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f6f8213bcfc525df1b533a0dd4b06f05f9a14ea8 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/MANIFEST.in b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..469520f584a4ffc098d13e23c0d273f89e01a06e --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/Makefile b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..bb667a145994b12c34f88661ec6a566f06a4518d --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/README.md b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/README.md new file mode 100644 index 0000000000000000000000000000000000000000..6c8ab04c4ff5f505eaf5f1bf68c55f0161593f07 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/README.md b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/README.md new file mode 100644 index 0000000000000000000000000000000000000000..92e2ec5aa40b081c940ac1e918efaeeed8623584 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/meta.yaml b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/conda/meta.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9d26c28c6ada4f4977d517986a05ceca138c7090 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__init__.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e3abb1c03b685802c21428ba050b1620e1a435fa --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__main__.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..8291c1879b60d0de49db79fb6ca60d33f09c8763 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data.py new file mode 100644 index 0000000000000000000000000000000000000000..1c3ec72e9ec972f9c7d148b66f212bf3e366a340 --- /dev/null +++ b/syntheticSuccess/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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_sampler.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_sampler.py new file mode 100644 index 0000000000000000000000000000000000000000..5cbf339dac0980c5368d2d11e2934a268fb9d43a --- /dev/null +++ b/syntheticSuccess/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 diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_transformer.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..06cfd128247f187be963c4b8c26067b06a02cbce --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_transformer.py @@ -0,0 +1,217 @@ +"""DataTransformer module.""" + +from collections import namedtuple + +import numpy as np +import pandas as pd +from rdt.transformers import BayesGMMTransformer, OneHotEncodingTransformer + +SpanInfo = namedtuple('SpanInfo', ['dim', 'activation_fn']) +ColumnTransformInfo = namedtuple( + 'ColumnTransformInfo', [ + 'column_name', 'column_type', 'transform', 'output_info', 'output_dimensions' + ] +) + + +class DataTransformer(object): + """Data Transformer. + + Model continuous columns with a BayesianGMM and normalized to a scalar [0, 1] and a vector. + Discrete columns are encoded using a scikit-learn OneHotEncoder. + """ + + def __init__(self, max_clusters=10, weight_threshold=0.005): + """Create a data transformer. + + Args: + max_clusters (int): + Maximum number of Gaussian distributions in Bayesian GMM. + weight_threshold (float): + Weight threshold for a Gaussian distribution to be kept. + """ + self._max_clusters = max_clusters + self._weight_threshold = weight_threshold + + def _fit_continuous(self, data): + """Train Bayesian GMM for continuous columns. + + Args: + data (pd.DataFrame): + A dataframe containing a column. + + Returns: + namedtuple: + A ``ColumnTransformInfo`` object. + """ + column_name = data.columns[0] + gm = BayesGMMTransformer(max_clusters=min(len(data), 10)) + gm.fit(data, [column_name]) + num_components = sum(gm.valid_component_indicator) + + return ColumnTransformInfo( + column_name=column_name, column_type='continuous', transform=gm, + output_info=[SpanInfo(1, 'tanh'), SpanInfo(num_components, 'softmax')], + output_dimensions=1 + num_components) + + def _fit_discrete(self, data): + """Fit one hot encoder for discrete column. + + Args: + data (pd.DataFrame): + A dataframe containing a column. + + Returns: + namedtuple: + A ``ColumnTransformInfo`` object. + """ + column_name = data.columns[0] + ohe = OneHotEncodingTransformer() + ohe.fit(data, [column_name]) + num_categories = len(ohe.dummies) + + return ColumnTransformInfo( + column_name=column_name, column_type='discrete', transform=ohe, + output_info=[SpanInfo(num_categories, 'softmax')], + output_dimensions=num_categories) + + def fit(self, raw_data, discrete_columns=()): + """Fit the ``DataTransformer``. + + Fits a ``BayesGMMTransformer`` for continuous columns and a + ``OneHotEncodingTransformer`` for discrete columns. + + This step also counts the #columns in matrix data and span information. + """ + self.output_info_list = [] + self.output_dimensions = 0 + self.dataframe = True + + if not isinstance(raw_data, pd.DataFrame): + self.dataframe = False + # work around for RDT issue #328 Fitting with numerical column names fails + discrete_columns = [str(column) for column in discrete_columns] + column_names = [str(num) for num in range(raw_data.shape[1])] + raw_data = pd.DataFrame(raw_data, columns=column_names) + + self._column_raw_dtypes = raw_data.infer_objects().dtypes + self._column_transform_info_list = [] + for column_name in raw_data.columns: + if column_name in discrete_columns: + column_transform_info = self._fit_discrete(raw_data[[column_name]]) + else: + column_transform_info = self._fit_continuous(raw_data[[column_name]]) + + self.output_info_list.append(column_transform_info.output_info) + self.output_dimensions += column_transform_info.output_dimensions + self._column_transform_info_list.append(column_transform_info) + + def _transform_continuous(self, column_transform_info, data): + column_name = data.columns[0] + data.loc[:, column_name] = data[column_name].to_numpy().flatten() + gm = column_transform_info.transform + transformed = gm.transform(data, [column_name]) + + # Converts the transformed data to the appropriate output format. + # The first column (ending in '.normalized') stays the same, + # but the lable encoded column (ending in '.component') is one hot encoded. + output = np.zeros((len(transformed), column_transform_info.output_dimensions)) + output[:, 0] = transformed[f'{column_name}.normalized'].to_numpy() + index = transformed[f'{column_name}.component'].to_numpy().astype(int) + output[np.arange(index.size), index + 1] = 1.0 + + return output + + def _transform_discrete(self, column_transform_info, data): + ohe = column_transform_info.transform + return ohe.transform(data).to_numpy() + + def transform(self, raw_data): + """Take raw data and output a matrix data.""" + if not isinstance(raw_data, pd.DataFrame): + column_names = [str(num) for num in range(raw_data.shape[1])] + raw_data = pd.DataFrame(raw_data, columns=column_names) + + column_data_list = [] + for column_transform_info in self._column_transform_info_list: + column_name = column_transform_info.column_name + data = raw_data[[column_name]] + if column_transform_info.column_type == 'continuous': + column_data_list.append(self._transform_continuous(column_transform_info, data)) + else: + column_data_list.append(self._transform_discrete(column_transform_info, data)) + + return np.concatenate(column_data_list, axis=1).astype(float) + + def _inverse_transform_continuous(self, column_transform_info, column_data, sigmas, st): + gm = column_transform_info.transform + data = pd.DataFrame(column_data[:, :2], columns=list(gm.get_output_types())) + data.iloc[:, 1] = np.argmax(column_data[:, 1:], axis=1) + if sigmas is not None: + selected_normalized_value = np.random.normal(data.iloc[:, 0], sigmas[st]) + data.iloc[:, 0] = selected_normalized_value + + return gm.reverse_transform(data, [column_transform_info.column_name]) + + def _inverse_transform_discrete(self, column_transform_info, column_data): + ohe = column_transform_info.transform + data = pd.DataFrame(column_data, columns=list(ohe.get_output_types())) + return ohe.reverse_transform(data)[column_transform_info.column_name] + + def inverse_transform(self, data, sigmas=None): + """Take matrix data and output raw data. + + Output uses the same type as input to the transform function. + Either np array or pd dataframe. + """ + st = 0 + recovered_column_data_list = [] + column_names = [] + for column_transform_info in self._column_transform_info_list: + dim = column_transform_info.output_dimensions + column_data = data[:, st:st + dim] + if column_transform_info.column_type == 'continuous': + recovered_column_data = self._inverse_transform_continuous( + column_transform_info, column_data, sigmas, st) + else: + recovered_column_data = self._inverse_transform_discrete( + column_transform_info, column_data) + + recovered_column_data_list.append(recovered_column_data) + column_names.append(column_transform_info.column_name) + st += dim + + recovered_data = np.column_stack(recovered_column_data_list) + recovered_data = (pd.DataFrame(recovered_data, columns=column_names) + .astype(self._column_raw_dtypes)) + if not self.dataframe: + recovered_data = recovered_data.to_numpy() + + return recovered_data + + def convert_column_name_value_to_id(self, column_name, value): + """Get the ids of the given `column_name`.""" + discrete_counter = 0 + column_id = 0 + for column_transform_info in self._column_transform_info_list: + if column_transform_info.column_name == column_name: + break + if column_transform_info.column_type == 'discrete': + discrete_counter += 1 + + column_id += 1 + + else: + raise ValueError(f"The column_name `{column_name}` doesn't exist in the data.") + + ohe = column_transform_info.transform + data = pd.DataFrame([value], columns=[column_transform_info.column_name]) + one_hot = ohe.transform(data).to_numpy()[0] + if sum(one_hot) == 0: + raise ValueError(f"The value `{value}` doesn't exist in the column `{column_name}`.") + + return { + 'discrete_column_id': discrete_counter, + 'column_id': column_id, + 'value_id': np.argmax(one_hot) + } diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/demo.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/demo.py new file mode 100644 index 0000000000000000000000000000000000000000..a99f90aa576a31f07ebfa7081ee6e4e7817ed02f --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/demo.py @@ -0,0 +1,10 @@ +"""Demo module.""" + +import pandas as pd + +DEMO_URL = 'http://ctgan-data.s3.amazonaws.com/census.csv.gz' + + +def load_demo(): + """Load the demo.""" + return pd.read_csv(DEMO_URL, compression='gzip') diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/__init__.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2f67c77a7892dad39ae429b80b46e8672a3c69df --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/__init__.py @@ -0,0 +1,16 @@ +"""Synthesizers module.""" + +from .ctgan import CTGANSynthesizer +from .tvae import TVAESynthesizer + +__all__ = ( + 'CTGANSynthesizer', + 'TVAESynthesizer' +) + + +def get_all_synthesizers(): + return { + name: globals()[name] + for name in __all__ + } diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/base.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..5afb66d4a6d2700c27516d8a322ab7b30a9356eb --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/base.py @@ -0,0 +1,105 @@ +"""BaseSynthesizer module.""" + +import contextlib + +import numpy as np +import torch + + +@contextlib.contextmanager +def set_random_states(random_state, set_model_random_state): + """Context manager for managing the random state. + + Args: + random_state (int or tuple): + The random seed or a tuple of (numpy.random.RandomState, torch.Generator). + set_model_random_state (function): + Function to set the random state on the model. + """ + original_np_state = np.random.get_state() + original_torch_state = torch.get_rng_state() + + random_np_state, random_torch_state = random_state + + np.random.set_state(random_np_state.get_state()) + torch.set_rng_state(random_torch_state.get_state()) + + try: + yield + finally: + current_np_state = np.random.RandomState() + current_np_state.set_state(np.random.get_state()) + current_torch_state = torch.Generator() + current_torch_state.set_state(torch.get_rng_state()) + set_model_random_state((current_np_state, current_torch_state)) + + np.random.set_state(original_np_state) + torch.set_rng_state(original_torch_state) + + +def random_state(function): + """Set the random state before calling the function. + + Args: + function (Callable): + The function to wrap around. + """ + def wrapper(self, *args, **kwargs): + if self.random_states is None: + return function(self, *args, **kwargs) + + else: + with set_random_states(self.random_states, self.set_random_state): + return function(self, *args, **kwargs) + + return wrapper + + +class BaseSynthesizer: + """Base class for all default synthesizers of ``CTGAN``. + + This should contain the save/load methods. + """ + + random_states = None + + def save(self, path): + """Save the model in the passed `path`.""" + device_backup = self._device + self.set_device(torch.device('cpu')) + torch.save(self, path) + self.set_device(device_backup) + + @classmethod + def load(cls, path): + """Load the model stored in the passed `path`.""" + device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') + model = torch.load(path) + model.set_device(device) + return model + + def set_random_state(self, random_state): + """Set the random state. + + Args: + random_state (int, tuple, or None): + Either a tuple containing the (numpy.random.RandomState, torch.Generator) + or an int representing the random seed to use for both random states. + """ + if random_state is None: + self.random_states = random_state + elif isinstance(random_state, int): + self.random_states = ( + np.random.RandomState(seed=random_state), + torch.Generator().manual_seed(random_state), + ) + elif ( + isinstance(random_state, tuple) and + isinstance(random_state[0], np.random.RandomState) and + isinstance(random_state[1], torch.Generator) + ): + self.random_states = random_state + else: + raise TypeError( + f'`random_state` {random_state} expected to be an int or a tuple of ' + '(`np.random.RandomState`, `torch.Generator`)') diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/ctgan.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/ctgan.py new file mode 100644 index 0000000000000000000000000000000000000000..e4253e87d6349cd2bccb669f46146edfd61e23a8 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/ctgan.py @@ -0,0 +1,482 @@ +"""CTGANSynthesizer module.""" + +import warnings + +import numpy as np +import pandas as pd +import torch +from packaging import version +from torch import optim +from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, functional + +from ..data_sampler import DataSampler +from ..data_transformer import DataTransformer +from .base import BaseSynthesizer, random_state + + +class Discriminator(Module): + """Discriminator for the CTGANSynthesizer.""" + + def __init__(self, input_dim, discriminator_dim, pac=10): + super(Discriminator, self).__init__() + dim = input_dim * pac + self.pac = pac + self.pacdim = dim + seq = [] + for item in list(discriminator_dim): + seq += [Linear(dim, item), LeakyReLU(0.2), Dropout(0.5)] + dim = item + + seq += [Linear(dim, 1)] + self.seq = Sequential(*seq) + + def calc_gradient_penalty(self, real_data, fake_data, device='cpu', pac=10, lambda_=10): + """Compute the gradient penalty.""" + alpha = torch.rand(real_data.size(0) // pac, 1, 1, device=device) + alpha = alpha.repeat(1, pac, real_data.size(1)) + alpha = alpha.view(-1, real_data.size(1)) + + interpolates = alpha * real_data + ((1 - alpha) * fake_data) + + disc_interpolates = self(interpolates) + + gradients = torch.autograd.grad( + outputs=disc_interpolates, inputs=interpolates, + grad_outputs=torch.ones(disc_interpolates.size(), device=device), + create_graph=True, retain_graph=True, only_inputs=True + )[0] + + gradients_view = gradients.view(-1, pac * real_data.size(1)).norm(2, dim=1) - 1 + gradient_penalty = ((gradients_view) ** 2).mean() * lambda_ + + return gradient_penalty + + def forward(self, input_): + """Apply the Discriminator to the `input_`.""" + assert input_.size()[0] % self.pac == 0 + return self.seq(input_.view(-1, self.pacdim)) + + +class Residual(Module): + """Residual layer for the CTGANSynthesizer.""" + + def __init__(self, i, o): + super(Residual, self).__init__() + self.fc = Linear(i, o) + self.bn = BatchNorm1d(o) + self.relu = ReLU() + + def forward(self, input_): + """Apply the Residual layer to the `input_`.""" + out = self.fc(input_) + out = self.bn(out) + out = self.relu(out) + return torch.cat([out, input_], dim=1) + + +class Generator(Module): + """Generator for the CTGANSynthesizer.""" + + def __init__(self, embedding_dim, generator_dim, data_dim): + super(Generator, self).__init__() + dim = embedding_dim + seq = [] + for item in list(generator_dim): + seq += [Residual(dim, item)] + dim += item + seq.append(Linear(dim, data_dim)) + self.seq = Sequential(*seq) + + def forward(self, input_): + """Apply the Generator to the `input_`.""" + data = self.seq(input_) + return data + + +class CTGANSynthesizer(BaseSynthesizer): + """Conditional Table GAN Synthesizer. + + This is the core class of the CTGAN project, where the different components + are orchestrated together. + For more details about the process, please check the [Modeling Tabular data using + Conditional GAN](https://arxiv.org/abs/1907.00503) paper. + + Args: + embedding_dim (int): + Size of the random sample passed to the Generator. Defaults to 128. + generator_dim (tuple or list of ints): + Size of the output samples for each one of the Residuals. A Residual Layer + will be created for each one of the values provided. Defaults to (256, 256). + discriminator_dim (tuple or list of ints): + Size of the output samples for each one of the Discriminator Layers. A Linear Layer + will be created for each one of the values provided. Defaults to (256, 256). + generator_lr (float): + Learning rate for the generator. Defaults to 2e-4. + generator_decay (float): + Generator weight decay for the Adam Optimizer. Defaults to 1e-6. + discriminator_lr (float): + Learning rate for the discriminator. Defaults to 2e-4. + discriminator_decay (float): + Discriminator weight decay for the Adam Optimizer. Defaults to 1e-6. + batch_size (int): + Number of data samples to process in each step. + discriminator_steps (int): + Number of discriminator updates to do for each generator update. + From the WGAN paper: https://arxiv.org/abs/1701.07875. WGAN paper + default is 5. Default used is 1 to match original CTGAN implementation. + log_frequency (boolean): + Whether to use log frequency of categorical levels in conditional + sampling. Defaults to ``True``. + verbose (boolean): + Whether to have print statements for progress results. Defaults to ``False``. + epochs (int): + Number of training epochs. Defaults to 300. + pac (int): + Number of samples to group together when applying the discriminator. + Defaults to 10. + cuda (bool): + Whether to attempt to use cuda for GPU computation. + If this is False or CUDA is not available, CPU will be used. + Defaults to ``True``. + """ + + def __init__(self, embedding_dim=128, generator_dim=(256, 256), discriminator_dim=(256, 256), + generator_lr=2e-4, generator_decay=1e-6, discriminator_lr=2e-4, + discriminator_decay=1e-6, batch_size=500, discriminator_steps=1, + log_frequency=True, verbose=False, epochs=300, pac=10, cuda=True): + + assert batch_size % 2 == 0 + + self._embedding_dim = embedding_dim + self._generator_dim = generator_dim + self._discriminator_dim = discriminator_dim + + self._generator_lr = generator_lr + self._generator_decay = generator_decay + self._discriminator_lr = discriminator_lr + self._discriminator_decay = discriminator_decay + + self._batch_size = batch_size + self._discriminator_steps = discriminator_steps + self._log_frequency = log_frequency + self._verbose = verbose + self._epochs = epochs + self.pac = pac + + if not cuda or not torch.cuda.is_available(): + device = 'cpu' + elif isinstance(cuda, str): + device = cuda + else: + device = 'cuda' + + self._device = torch.device(device) + + self._transformer = None + self._data_sampler = None + self._generator = None + + @staticmethod + def _gumbel_softmax(logits, tau=1, hard=False, eps=1e-10, dim=-1): + """Deals with the instability of the gumbel_softmax for older versions of torch. + + For more details about the issue: + https://drive.google.com/file/d/1AA5wPfZ1kquaRtVruCd6BiYZGcDeNxyP/view?usp=sharing + + Args: + logits […, num_features]: + Unnormalized log probabilities + tau: + Non-negative scalar temperature + hard (bool): + If True, the returned samples will be discretized as one-hot vectors, + but will be differentiated as if it is the soft sample in autograd + dim (int): + A dimension along which softmax will be computed. Default: -1. + + Returns: + Sampled tensor of same shape as logits from the Gumbel-Softmax distribution. + """ + if version.parse(torch.__version__) < version.parse('1.2.0'): + for i in range(10): + transformed = functional.gumbel_softmax(logits, tau=tau, hard=hard, + eps=eps, dim=dim) + if not torch.isnan(transformed).any(): + return transformed + raise ValueError('gumbel_softmax returning NaN.') + + return functional.gumbel_softmax(logits, tau=tau, hard=hard, eps=eps, dim=dim) + + def _apply_activate(self, data): + """Apply proper activation function to the output of the generator.""" + data_t = [] + st = 0 + for column_info in self._transformer.output_info_list: + for span_info in column_info: + if span_info.activation_fn == 'tanh': + ed = st + span_info.dim + data_t.append(torch.tanh(data[:, st:ed])) + st = ed + elif span_info.activation_fn == 'softmax': + ed = st + span_info.dim + transformed = self._gumbel_softmax(data[:, st:ed], tau=0.2) + data_t.append(transformed) + st = ed + else: + raise ValueError(f'Unexpected activation function {span_info.activation_fn}.') + + return torch.cat(data_t, dim=1) + + def _cond_loss(self, data, c, m): + """Compute the cross entropy loss on the fixed discrete column.""" + loss = [] + st = 0 + st_c = 0 + for column_info in self._transformer.output_info_list: + for span_info in column_info: + if len(column_info) != 1 or span_info.activation_fn != 'softmax': + # not discrete column + st += span_info.dim + else: + ed = st + span_info.dim + ed_c = st_c + span_info.dim + tmp = functional.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) # noqa: PD013 + + return (loss * m).sum() / data.size()[0] + + def _validate_discrete_columns(self, train_data, discrete_columns): + """Check whether ``discrete_columns`` exists in ``train_data``. + + Args: + train_data (numpy.ndarray or pandas.DataFrame): + Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. + discrete_columns (list-like): + List of discrete columns to be used to generate the Conditional + Vector. If ``train_data`` is a Numpy array, this list should + contain the integer indices of the columns. Otherwise, if it is + a ``pandas.DataFrame``, this list should contain the column names. + """ + if isinstance(train_data, pd.DataFrame): + invalid_columns = set(discrete_columns) - set(train_data.columns) + elif isinstance(train_data, np.ndarray): + invalid_columns = [] + for column in discrete_columns: + if column < 0 or column >= train_data.shape[1]: + invalid_columns.append(column) + else: + raise TypeError('``train_data`` should be either pd.DataFrame or np.array.') + + if invalid_columns: + raise ValueError(f'Invalid columns found: {invalid_columns}') + + @random_state + def fit(self, train_data, discrete_columns=(), epochs=None): + """Fit the CTGAN Synthesizer models to the training data. + + Args: + train_data (numpy.ndarray or pandas.DataFrame): + Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. + discrete_columns (list-like): + List of discrete columns to be used to generate the Conditional + Vector. If ``train_data`` is a Numpy array, this list should + contain the integer indices of the columns. Otherwise, if it is + a ``pandas.DataFrame``, this list should contain the column names. + """ + self._validate_discrete_columns(train_data, discrete_columns) + + if epochs is None: + epochs = self._epochs + else: + warnings.warn( + ('`epochs` argument in `fit` method has been deprecated and will be removed ' + 'in a future version. Please pass `epochs` to the constructor instead'), + DeprecationWarning + ) + + self._transformer = DataTransformer() + self._transformer.fit(train_data, discrete_columns) + + train_data = self._transformer.transform(train_data) + + self._data_sampler = DataSampler( + train_data, + self._transformer.output_info_list, + self._log_frequency) + + data_dim = self._transformer.output_dimensions + + self._generator = Generator( + self._embedding_dim + self._data_sampler.dim_cond_vec(), + self._generator_dim, + data_dim + ).to(self._device) + + discriminator = Discriminator( + data_dim + self._data_sampler.dim_cond_vec(), + self._discriminator_dim, + pac=self.pac + ).to(self._device) + + optimizerG = optim.Adam( + self._generator.parameters(), lr=self._generator_lr, betas=(0.5, 0.9), + weight_decay=self._generator_decay + ) + + optimizerD = optim.Adam( + discriminator.parameters(), lr=self._discriminator_lr, + betas=(0.5, 0.9), weight_decay=self._discriminator_decay + ) + + mean = torch.zeros(self._batch_size, self._embedding_dim, device=self._device) + std = mean + 1 + + print('CTGAN training') + steps_per_epoch = max(len(train_data) // self._batch_size, 1) + for i in range(epochs): + for n in range(self._discriminator_steps): + fakez = torch.normal(mean=mean, std=std) + + condvec = self._data_sampler.sample_condvec(self._batch_size) + if condvec is None: + c1, m1, col, opt = None, None, None, None + real = self._data_sampler.sample_data(self._batch_size, col, opt) + else: + c1, m1, col, opt = condvec + c1 = torch.from_numpy(c1).to(self._device) + m1 = torch.from_numpy(m1).to(self._device) + fakez = torch.cat([fakez, c1], dim=1) + + perm = np.arange(self._batch_size) + np.random.shuffle(perm) + real = self._data_sampler.sample_data( + self._batch_size, col[perm], opt[perm]) + c2 = c1[perm] + + fake = self._generator(fakez) + fakeact = self._apply_activate(fake) + + real = torch.from_numpy(real.astype('float32')).to(self._device) + + if c1 is not None: + fake_cat = torch.cat([fakeact, c1], dim=1) + real_cat = torch.cat([real, c2], dim=1) + else: + real_cat = real + fake_cat = fakeact + + y_fake = discriminator(fake_cat) + y_real = discriminator(real_cat) + + pen = discriminator.calc_gradient_penalty( + real_cat, fake_cat, self._device, self.pac) + loss_d = -(torch.mean(y_real) - torch.mean(y_fake)) + + optimizerD.zero_grad() + pen.backward(retain_graph=True) + loss_d.backward() + optimizerD.step() + + fakez = torch.normal(mean=mean, std=std) + condvec = self._data_sampler.sample_condvec(self._batch_size) + + if condvec is None: + c1, m1, col, opt = None, None, None, None + else: + c1, m1, col, opt = condvec + c1 = torch.from_numpy(c1).to(self._device) + m1 = torch.from_numpy(m1).to(self._device) + fakez = torch.cat([fakez, c1], dim=1) + + fake = self._generator(fakez) + fakeact = self._apply_activate(fake) + + if c1 is not None: + y_fake = discriminator(torch.cat([fakeact, c1], dim=1)) + else: + y_fake = discriminator(fakeact) + + if condvec is None: + cross_entropy = 0 + else: + cross_entropy = self._cond_loss(fake, c1, m1) + + loss_g = -torch.mean(y_fake) + cross_entropy + + optimizerG.zero_grad() + loss_g.backward() + optimizerG.step() + + if self._verbose and (i + 1) % 1000 == 0: + print(f'Epoch {i+1}, Loss G: {loss_g.detach().cpu(): .4f},' # noqa: T001 + f'Loss D: {loss_d.detach().cpu(): .4f}', + flush=True) + + @random_state + def sample(self, n, condition_column=None, condition_value=None): + """Sample data similar to the training data. + + Choosing a condition_column and condition_value will increase the probability of the + discrete condition_value happening in the condition_column. + + Args: + n (int): + Number of rows to sample. + condition_column (string): + Name of a discrete column. + condition_value (string): + Name of the category in the condition_column which we wish to increase the + probability of happening. + + Returns: + numpy.ndarray or pandas.DataFrame + """ + if condition_column is not None and condition_value is not None: + condition_info = self._transformer.convert_column_name_value_to_id( + condition_column, condition_value) + global_condition_vec = self._data_sampler.generate_cond_from_condition_column_info( + condition_info, self._batch_size) + else: + global_condition_vec = None + + steps = n // self._batch_size + 1 + data = [] + for i in range(steps): + mean = torch.zeros(self._batch_size, self._embedding_dim) + std = mean + 1 + fakez = torch.normal(mean=mean, std=std).to(self._device) + + if global_condition_vec is not None: + condvec = global_condition_vec.copy() + else: + condvec = self._data_sampler.sample_original_condvec(self._batch_size) + + if condvec is None: + pass + else: + c1 = condvec + c1 = torch.from_numpy(c1).to(self._device) + fakez = torch.cat([fakez, c1], dim=1) + + fake = self._generator(fakez) + fakeact = self._apply_activate(fake) + data.append(fakeact.detach().cpu().numpy()) + + data = np.concatenate(data, axis=0) + data = data[:n] + + return self._transformer.inverse_transform(data) + + def set_device(self, device): + """Set the `device` to be used ('GPU' or 'CPU).""" + self._device = device + if self._generator is not None: + self._generator.to(self._device) diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/tvae.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/tvae.py new file mode 100644 index 0000000000000000000000000000000000000000..1baa3f38a8157b80fb866c205491616543fb0470 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/tvae.py @@ -0,0 +1,218 @@ +"""TVAESynthesizer module.""" + +import numpy as np +import torch +from torch.nn import Linear, Module, Parameter, ReLU, Sequential +from torch.nn.functional import cross_entropy +from torch.optim import Adam +from torch.utils.data import DataLoader, TensorDataset + +from ..data_transformer import DataTransformer +from .base import BaseSynthesizer, random_state + + +class Encoder(Module): + """Encoder for the TVAESynthesizer. + + Args: + data_dim (int): + Dimensions of the data. + compress_dims (tuple or list of ints): + Size of each hidden layer. + embedding_dim (int): + Size of the output vector. + """ + + def __init__(self, data_dim, compress_dims, embedding_dim): + super(Encoder, self).__init__() + dim = data_dim + seq = [] + for item in list(compress_dims): + seq += [ + Linear(dim, item), + ReLU() + ] + dim = item + + self.seq = Sequential(*seq) + self.fc1 = Linear(dim, embedding_dim) + self.fc2 = Linear(dim, embedding_dim) + + def forward(self, input_): + """Encode the passed `input_`.""" + feature = self.seq(input_) + mu = self.fc1(feature) + logvar = self.fc2(feature) + std = torch.exp(0.5 * logvar) + return mu, std, logvar + + +class Decoder(Module): + """Decoder for the TVAESynthesizer. + + Args: + embedding_dim (int): + Size of the input vector. + decompress_dims (tuple or list of ints): + Size of each hidden layer. + data_dim (int): + Dimensions of the data. + """ + + def __init__(self, embedding_dim, decompress_dims, data_dim): + super(Decoder, self).__init__() + dim = embedding_dim + seq = [] + for item in list(decompress_dims): + seq += [Linear(dim, item), ReLU()] + dim = item + + seq.append(Linear(dim, data_dim)) + self.seq = Sequential(*seq) + self.sigma = Parameter(torch.ones(data_dim) * 0.1) + + def forward(self, input_): + """Decode the passed `input_`.""" + return self.seq(input_), self.sigma + + +def _loss_function(recon_x, x, sigmas, mu, logvar, output_info, factor): + st = 0 + loss = [] + for column_info in output_info: + for span_info in column_info: + if span_info.activation_fn != 'softmax': + ed = st + span_info.dim + std = sigmas[st] + eq = x[:, st] - torch.tanh(recon_x[:, st]) + loss.append((eq ** 2 / 2 / (std ** 2)).sum()) + loss.append(torch.log(std) * x.size()[0]) + st = ed + + else: + ed = st + span_info.dim + loss.append(cross_entropy( + recon_x[:, st:ed], torch.argmax(x[:, st:ed], dim=-1), reduction='sum')) + st = ed + + assert st == recon_x.size()[1] + KLD = -0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp()) + return sum(loss) * factor / x.size()[0], KLD / x.size()[0] + + +class TVAESynthesizer(BaseSynthesizer): + """TVAESynthesizer.""" + + def __init__( + self, + embedding_dim=128, + compress_dims=(128, 128), + decompress_dims=(128, 128), + l2scale=1e-5, + batch_size=500, + epochs=300, + lr=1e-3, + loss_factor=2, + device="cuda:0" + ): + self.embedding_dim = embedding_dim + self.compress_dims = compress_dims + self.decompress_dims = decompress_dims + + self.lr = lr + self.l2scale = l2scale + self.batch_size = batch_size + self.loss_factor = loss_factor + self.epochs = epochs + + + self._device = torch.device(device) + + @random_state + def fit(self, train_data, discrete_columns=()): + """Fit the TVAE Synthesizer models to the training data. + + Args: + train_data (numpy.ndarray or pandas.DataFrame): + Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame. + discrete_columns (list-like): + List of discrete columns to be used to generate the Conditional + Vector. If ``train_data`` is a Numpy array, this list should + contain the integer indices of the columns. Otherwise, if it is + a ``pandas.DataFrame``, this list should contain the column names. + """ + self.transformer = DataTransformer() + self.transformer.fit(train_data, discrete_columns) + train_data = self.transformer.transform(train_data) + dataset = TensorDataset(torch.from_numpy(train_data.astype('float32'))) + loader = DataLoader(dataset, batch_size=self.batch_size, shuffle=True, drop_last=False) + + data_dim = self.transformer.output_dimensions + encoder = Encoder(data_dim, self.compress_dims, self.embedding_dim).to(self._device) + self.decoder = Decoder(self.embedding_dim, self.decompress_dims, data_dim).to(self._device) + optimizerAE = Adam( + list(encoder.parameters()) + list(self.decoder.parameters()), + lr=self.lr, + weight_decay=self.l2scale) + data_iter = iter(loader) + print('Training:') + for i in range(self.epochs): + try: + data = next(data_iter) + except: + data_iter = iter(loader) + data = next(data_iter) + + optimizerAE.zero_grad() + real = data[0].to(self._device) + mu, std, logvar = encoder(real) + eps = torch.randn_like(std) + emb = eps * std + mu + rec, sigmas = self.decoder(emb) + loss_1, loss_2 = _loss_function( + rec, real, sigmas, mu, logvar, + self.transformer.output_info_list, self.loss_factor + ) + loss = loss_1 + loss_2 + loss.backward() + optimizerAE.step() + self.decoder.sigma.data.clamp_(0.01, 1.0) + if (i + 1) % 1000 == 0: + print(f"{i + 1}/{self.epochs} {loss}", flush=True) + + @random_state + def sample(self, samples, seed=0): + """Sample data similar to the training data. + + Args: + samples (int): + Number of rows to sample. + + Returns: + numpy.ndarray or pandas.DataFrame + """ + + torch.cuda.manual_seed(seed) + torch.manual_seed(seed) + + self.decoder.eval() + + sample_batch_size = 8092 + steps = samples // sample_batch_size + 1 + data = [] + for _ in range(steps): + mean = torch.zeros(sample_batch_size, self.embedding_dim) + std = mean + 1 + noise = torch.normal(mean=mean, std=std).to(self._device) + fake, sigmas = self.decoder(noise) + fake = torch.tanh(fake) + data.append(fake.detach().cpu().numpy()) + + data = np.concatenate(data, axis=0) + data = data[:samples] + return self.transformer.inverse_transform(data, sigmas.detach().cpu().numpy()) + + def set_device(self, device): + """Set the `device` to be used ('GPU' or 'CPU).""" + self._device = device + self.decoder.to(self._device) diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.cfg b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..8398eee0de75e378fa157456b8594f9ec383c45c --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.cfg @@ -0,0 +1,59 @@ +[bumpversion] +current_version = 0.5.2.dev0 +commit = True +tag = True +parse = (?P\d+)\.(?P\d+)\.(?P\d+)(\.(?P[a-z]+)(?P\d+))? +serialize = + {major}.{minor}.{patch}.{release}{candidate} + {major}.{minor}.{patch} + +[bumpversion:part:release] +optional_value = release +first_value = dev +values = + dev + release + +[bumpversion:part:candidate] + +[bumpversion:file:setup.py] +search = version='{current_version}' +replace = version='{new_version}' + +[bumpversion:file:ctgan/__init__.py] +search = __version__ = '{current_version}' +replace = __version__ = '{new_version}' + +[bumpversion:file:conda/meta.yaml] +search = version = '{current_version}' +replace = version = '{new_version}' + +[bdist_wheel] +universal = 1 + +[flake8] +convention = google +max-line-length = 99 +exclude = docs, .tox, .git, __pycache__, .ipynb_checkpoints +extend-ignore = D107, # Missing docstring in __init__ + D407, # Missing dashed underline after section + D417, # Missing argument descriptions in the docstring + SFS3, # String literal formatting using f-string. + VNE001 # Single letter variable names are not allowed +per-file-ignores = + ctgan/data.py:T001 + +[isort] +include_trailing_comment = True +line_length = 99 +lines_between_types = 0 +multi_line_output = 4 +not_skip = __init__.py +use_parentheses = True + +[aliases] +test = pytest + +[tool:pytest] +collect_ignore = ['setup.py'] + diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..83d973eb603ce5a4f4dc31f3bac459eeabdd1ec5 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""The setup script.""" + +from setuptools import find_packages, setup + +with open('README.md', encoding='utf-8') as readme_file: + readme = readme_file.read() + +with open('HISTORY.md', encoding='utf-8') as history_file: + history = history_file.read() + +install_requires = [ + 'packaging>=20,<22', + "numpy>=1.18.0,<1.20.0;python_version<'3.7'", + "numpy>=1.20.0,<2;python_version>='3.7'", + 'pandas>=1.1.3,<2', + 'scikit-learn>=0.24,<2', + 'torch>=1.8.0,<2', + 'torchvision>=0.9.0,<1', + 'rdt>=0.6.2,<0.7', +] + +setup_requires = [ + 'pytest-runner>=2.11.1', +] + +tests_require = [ + 'pytest>=3.4.2', + 'pytest-rerunfailures>=9.1.1,<10', + 'pytest-cov>=2.6.0', +] + +development_requires = [ + # general + 'pip>=9.0.1', + 'bumpversion>=0.5.3,<0.6', + 'watchdog>=0.8.3,<0.11', + + # style check + 'flake8>=3.7.7,<4', + 'isort>=4.3.4,<5', + 'dlint>=0.11.0,<0.12', # code security addon for flake8 + 'flake8-debugger>=4.0.0,<4.1', + 'flake8-mock>=0.3,<0.4', + 'flake8-mutable>=1.2.0,<1.3', + 'flake8-absolute-import>=1.0,<2', + 'flake8-multiline-containers>=0.0.18,<0.1', + 'flake8-print>=4.0.0,<4.1', + 'flake8-quotes>=3.3.0,<4', + 'flake8-fixme>=1.1.1,<1.2', + 'flake8-expression-complexity>=0.0.9,<0.1', + 'flake8-eradicate>=1.1.0,<1.2', + 'flake8-builtins>=1.5.3,<1.6', + 'flake8-variables-names>=0.0.4,<0.1', + 'pandas-vet>=0.2.2,<0.3', + 'flake8-comprehensions>=3.6.1,<3.7', + 'dlint>=0.11.0,<0.12', + 'flake8-docstrings>=1.5.0,<2', + 'flake8-sfs>=0.0.3,<0.1', + 'flake8-pytest-style>=1.5.0,<2', + + # fix style issues + 'autoflake>=1.1,<2', + 'autopep8>=1.4.3,<1.6', + + # distribute on PyPI + 'twine>=1.10.0,<4', + 'wheel>=0.30.0', + + # Advanced testing + 'coverage>=4.5.1,<6', + 'tox>=2.9.1,<4', + + 'invoke', +] + +setup( + author='MIT Data To AI Lab', + author_email='dailabmit@gmail.com', + classifiers=[ + 'Development Status :: 2 - Pre-Alpha', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: MIT License', + 'Natural Language :: English', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.6', + 'Programming Language :: Python :: 3.7', + 'Programming Language :: Python :: 3.8', + 'Programming Language :: Python :: 3.9', + ], + description='Conditional GAN for Tabular Data', + entry_points={ + 'console_scripts': [ + 'ctgan=ctgan.__main__:main' + ], + }, + extras_require={ + 'test': tests_require, + 'dev': development_requires + tests_require, + }, + install_package_data=True, + install_requires=install_requires, + license='MIT license', + long_description=readme + '\n\n' + history, + long_description_content_type='text/markdown', + include_package_data=True, + keywords='ctgan CTGAN', + name='ctgan', + packages=find_packages(include=['ctgan', 'ctgan.*']), + python_requires='>=3.6,<3.10', + setup_requires=setup_requires, + test_suite='tests', + tests_require=tests_require, + url='https://github.com/sdv-dev/CTGAN', + version='0.5.2.dev0', + zip_safe=False, +) diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tasks.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tasks.py new file mode 100644 index 0000000000000000000000000000000000000000..78730cea28cec928ff175364db655f10abe6143e --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tasks.py @@ -0,0 +1,121 @@ +import glob +import operator +import os +import re +import platform +import shutil +import stat +from pathlib import Path + +from invoke import task + +COMPARISONS = { + '>=': operator.ge, + '>': operator.gt, + '<': operator.lt, + '<=': operator.le +} + + +@task +def check_dependencies(c): + c.run('python -m pip check') + + +@task +def unit(c): + c.run('python -m pytest ./tests/unit --cov=ctgan --cov-report=xml') + + +@task +def integration(c): + c.run('python -m pytest ./tests/integration --reruns 3') + + +@task +def readme(c): + test_path = Path('tests/readme_test') + if test_path.exists() and test_path.is_dir(): + shutil.rmtree(test_path) + + cwd = os.getcwd() + os.makedirs(test_path, exist_ok=True) + shutil.copy('README.md', test_path / 'README.md') + os.chdir(test_path) + c.run('rundoc run --single-session python3 -t python3 README.md') + os.chdir(cwd) + shutil.rmtree(test_path) + + +def _validate_python_version(line): + python_version_match = re.search(r"python_version(<=?|>=?)\'(\d\.?)+\'", line) + if python_version_match: + python_version = python_version_match.group(0) + comparison = re.search(r'(>=?|<=?)', python_version).group(0) + version_number = python_version.split(comparison)[-1].replace("'", "") + comparison_function = COMPARISONS[comparison] + return comparison_function(platform.python_version(), version_number) + + return True + + +@task +def install_minimum(c): + with open('setup.py', 'r') as setup_py: + lines = setup_py.read().splitlines() + + versions = [] + started = False + for line in lines: + if started: + if line == ']': + started = False + continue + + line = line.strip() + if _validate_python_version(line): + requirement = re.match(r'[^>]*', line).group(0) + requirement = re.sub(r"""['",]""", '', requirement) + version = re.search(r'>=?[^(,|#)]*', line).group(0) + if version: + version = re.sub(r'>=?', '==', version) + version = re.sub(r"""['",]""", '', version) + requirement += version + + versions.append(requirement) + + elif (line.startswith('install_requires = [') or + line.startswith('pomegranate_requires = [')): + started = True + + c.run(f'python -m pip install {" ".join(versions)}') + + +@task +def minimum(c): + install_minimum(c) + check_dependencies(c) + unit(c) + integration(c) + + +@task +def lint(c): + check_dependencies(c) + c.run('flake8 ctgan') + c.run('flake8 tests --ignore=D101') + c.run('isort -c --recursive ctgan tests') + + +def remove_readonly(func, path, _): + "Clear the readonly bit and reattempt the removal" + os.chmod(path, stat.S_IWRITE) + func(path) + + +@task +def rmdir(c, path): + try: + shutil.rmtree(path, onerror=remove_readonly) + except PermissionError: + pass diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_ctgan.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_ctgan.py new file mode 100644 index 0000000000000000000000000000000000000000..a750d3dabc716a49fb722dbbb87e7a2120fc5fd4 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_ctgan.py @@ -0,0 +1,275 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""Integration tests for ctgan. + +These tests only ensure that the software does not crash and that +the API works as expected in terms of input and output data formats, +but correctness of the data values and the internal behavior of the +model are not checked. +""" + +import tempfile as tf + +import numpy as np +import pandas as pd +import pytest + +from ctgan.synthesizers.ctgan import CTGANSynthesizer + + +def test_ctgan_no_categoricals(): + """Test the CTGANSynthesizer with no categorical values.""" + data = pd.DataFrame({ + 'continuous': np.random.random(1000) + }) + + ctgan = CTGANSynthesizer(epochs=1) + ctgan.fit(data, []) + + sampled = ctgan.sample(100) + + assert sampled.shape == (100, 1) + assert isinstance(sampled, pd.DataFrame) + assert set(sampled.columns) == {'continuous'} + + +def test_ctgan_dataframe(): + """Test the CTGANSynthesizer when passed a dataframe.""" + data = pd.DataFrame({ + 'continuous': np.random.random(100), + 'discrete': np.random.choice(['a', 'b', 'c'], 100) + }) + discrete_columns = ['discrete'] + + ctgan = CTGANSynthesizer(epochs=1) + ctgan.fit(data, discrete_columns) + + sampled = ctgan.sample(100) + + assert sampled.shape == (100, 2) + assert isinstance(sampled, pd.DataFrame) + assert set(sampled.columns) == {'continuous', 'discrete'} + assert set(sampled['discrete'].unique()) == {'a', 'b', 'c'} + + +def test_ctgan_numpy(): + """Test the CTGANSynthesizer when passed a numpy array.""" + data = pd.DataFrame({ + 'continuous': np.random.random(100), + 'discrete': np.random.choice(['a', 'b', 'c'], 100) + }) + discrete_columns = [1] + + ctgan = CTGANSynthesizer(epochs=1) + ctgan.fit(data.to_numpy(), discrete_columns) + + sampled = ctgan.sample(100) + + assert sampled.shape == (100, 2) + assert isinstance(sampled, np.ndarray) + assert set(np.unique(sampled[:, 1])) == {'a', 'b', 'c'} + + +def test_log_frequency(): + """Test the CTGANSynthesizer with no `log_frequency` set to False.""" + data = pd.DataFrame({ + 'continuous': np.random.random(1000), + 'discrete': np.repeat(['a', 'b', 'c'], [950, 25, 25]) + }) + + discrete_columns = ['discrete'] + + ctgan = CTGANSynthesizer(epochs=100) + ctgan.fit(data, discrete_columns) + + sampled = ctgan.sample(10000) + counts = sampled['discrete'].value_counts() + assert counts['a'] < 6500 + + ctgan = CTGANSynthesizer(log_frequency=False, epochs=100) + ctgan.fit(data, discrete_columns) + + sampled = ctgan.sample(10000) + counts = sampled['discrete'].value_counts() + assert counts['a'] > 9000 + + +def test_categorical_nan(): + """Test the CTGANSynthesizer with no categorical values.""" + data = pd.DataFrame({ + 'continuous': np.random.random(30), + # This must be a list (not a np.array) or NaN will be cast to a string. + 'discrete': [np.nan, 'b', 'c'] * 10 + }) + discrete_columns = ['discrete'] + + ctgan = CTGANSynthesizer(epochs=1) + ctgan.fit(data, discrete_columns) + + sampled = ctgan.sample(100) + + assert sampled.shape == (100, 2) + assert isinstance(sampled, pd.DataFrame) + assert set(sampled.columns) == {'continuous', 'discrete'} + + # since np.nan != np.nan, we need to be careful here + values = set(sampled['discrete'].unique()) + assert len(values) == 3 + assert any(pd.isna(x) for x in values) + assert {'b', 'c'}.issubset(values) + + +def test_synthesizer_sample(): + """Test the CTGANSynthesizer samples the correct datatype.""" + data = pd.DataFrame({ + 'discrete': np.random.choice(['a', 'b', 'c'], 100) + }) + discrete_columns = ['discrete'] + + ctgan = CTGANSynthesizer(epochs=1) + ctgan.fit(data, discrete_columns) + + samples = ctgan.sample(1000, 'discrete', 'a') + assert isinstance(samples, pd.DataFrame) + + +def test_save_load(): + """Test the CTGANSynthesizer load/save methods.""" + data = pd.DataFrame({ + 'continuous': np.random.random(100), + 'discrete': np.random.choice(['a', 'b', 'c'], 100) + }) + discrete_columns = ['discrete'] + + ctgan = CTGANSynthesizer(epochs=1) + ctgan.fit(data, discrete_columns) + + with tf.TemporaryDirectory() as temporary_directory: + ctgan.save(temporary_directory + 'test_tvae.pkl') + ctgan = CTGANSynthesizer.load(temporary_directory + 'test_tvae.pkl') + + sampled = ctgan.sample(1000) + assert set(sampled.columns) == {'continuous', 'discrete'} + assert set(sampled['discrete'].unique()) == {'a', 'b', 'c'} + + +def test_wrong_discrete_columns_dataframe(): + """Test the CTGANSynthesizer correctly crashes when passed non-existing discrete columns.""" + data = pd.DataFrame({ + 'discrete': ['a', 'b'] + }) + discrete_columns = ['b', 'c'] + + ctgan = CTGANSynthesizer(epochs=1) + with pytest.raises(ValueError, match="Invalid columns found: {'.*', '.*'}"): + ctgan.fit(data, discrete_columns) + + +def test_wrong_discrete_columns_numpy(): + """Test the CTGANSynthesizer correctly crashes when passed non-existing discrete columns.""" + data = pd.DataFrame({ + 'discrete': ['a', 'b'] + }) + discrete_columns = [0, 1] + + ctgan = CTGANSynthesizer(epochs=1) + with pytest.raises(ValueError, match=r'Invalid columns found: \[1\]'): + ctgan.fit(data.to_numpy(), discrete_columns) + + +def test_wrong_sampling_conditions(): + """Test the CTGANSynthesizer correctly crashes when passed incorrect sampling conditions.""" + data = pd.DataFrame({ + 'continuous': np.random.random(100), + 'discrete': np.random.choice(['a', 'b', 'c'], 100) + }) + discrete_columns = ['discrete'] + + ctgan = CTGANSynthesizer(epochs=1) + ctgan.fit(data, discrete_columns) + + with pytest.raises(ValueError, match="The column_name `cardinal` doesn't exist in the data."): + ctgan.sample(1, 'cardinal', "doesn't matter") + + with pytest.raises(ValueError): # noqa: RDT currently incorrectly raises a tuple instead of a string + ctgan.sample(1, 'discrete', 'd') + + +def test_fixed_random_seed(): + """Test the CTGANSynthesizer with a fixed seed. + + Expect that when the random seed is reset with the same seed, the same sequence + of data will be produced. Expect that the data generated with the seed is + different than randomly sampled data. + """ + # Setup + data = pd.DataFrame({ + 'continuous': np.random.random(100), + 'discrete': np.random.choice(['a', 'b', 'c'], 100) + }) + discrete_columns = ['discrete'] + + ctgan = CTGANSynthesizer(epochs=1) + + # Run + ctgan.fit(data, discrete_columns) + sampled_random = ctgan.sample(10) + + ctgan.set_random_state(0) + sampled_0_0 = ctgan.sample(10) + sampled_0_1 = ctgan.sample(10) + + ctgan.set_random_state(0) + sampled_1_0 = ctgan.sample(10) + sampled_1_1 = ctgan.sample(10) + + # Assert + assert not np.array_equal(sampled_random, sampled_0_0) + assert not np.array_equal(sampled_random, sampled_0_1) + np.testing.assert_array_equal(sampled_0_0, sampled_1_0) + np.testing.assert_array_equal(sampled_0_1, sampled_1_1) + + +# Below are CTGAN tests that should be implemented in the future +def test_continuous(): + """Test training the CTGAN synthesizer on a continuous dataset.""" + # assert the distribution of the samples is close to the distribution of the data + # using kstest: + # - uniform (assert p-value > 0.05) + # - gaussian (assert p-value > 0.05) + # - inversely correlated (assert correlation < 0) + + +def test_categorical(): + """Test training the CTGAN synthesizer on a categorical dataset.""" + # assert the distribution of the samples is close to the distribution of the data + # using cstest: + # - uniform (assert p-value > 0.05) + # - very skewed / biased? (assert p-value > 0.05) + # - inversely correlated (assert correlation < 0) + + +def test_categorical_log_frequency(): + """Test training the CTGAN synthesizer on a small categorical dataset.""" + # assert the distribution of the samples is close to the distribution of the data + # using cstest: + # - uniform (assert p-value > 0.05) + # - very skewed / biased? (assert p-value > 0.05) + # - inversely correlated (assert correlation < 0) + + +def test_mixed(): + """Test training the CTGAN synthesizer on a small mixed-type dataset.""" + # assert the distribution of the samples is close to the distribution of the data + # using a kstest for continuous + a cstest for categorical. + + +def test_conditional(): + """Test training the CTGAN synthesizer and sampling conditioned on a categorical.""" + # verify that conditioning increases the likelihood of getting a sample with the specified + # categorical value + + +def test_batch_size_pack_size(): + """Test that if batch size is not a multiple of pack size, it raises a sane error.""" diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_tvae.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_tvae.py new file mode 100644 index 0000000000000000000000000000000000000000..ab8c583e0dd11fee3e1ce3d5cd4ac8f0a847a192 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_tvae.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +"""Integration tests for tvae. + +These tests only ensure that the software does not crash and that +the API works as expected in terms of input and output data formats, +but correctness of the data values and the internal behavior of the +model are not checked. +""" + +import numpy as np +import pandas as pd +from sklearn import datasets + +from ctgan.synthesizers.tvae import TVAESynthesizer + + +def test_tvae(tmpdir): + """Test the TVAESynthesizer load/save methods.""" + iris = datasets.load_iris() + data = pd.DataFrame(iris.data, columns=iris.feature_names) + data['class'] = pd.Series(iris.target).map(iris.target_names.__getitem__) + + tvae = TVAESynthesizer(epochs=10) + tvae.fit(data, ['class']) + + path = str(tmpdir / 'test_tvae.pkl') + tvae.save(path) + tvae = TVAESynthesizer.load(path) + + sampled = tvae.sample(100) + + assert sampled.shape == (100, 5) + assert isinstance(sampled, pd.DataFrame) + assert set(sampled.columns) == set(data.columns) + assert set(sampled.dtypes) == set(data.dtypes) + + +def test_drop_last_false(): + """Test the TVAESynthesizer predicts the correct values.""" + data = pd.DataFrame({ + '1': ['a', 'b', 'c'] * 150, + '2': ['a', 'b', 'c'] * 150 + }) + + tvae = TVAESynthesizer(epochs=300) + tvae.fit(data, ['1', '2']) + + sampled = tvae.sample(100) + correct = 0 + for _, row in sampled.iterrows(): + if row['1'] == row['2']: + correct += 1 + + assert correct >= 95 + + +# TVAE tests that should be implemented in the future. +def test_continuous(): + """Test training the TVAE synthesizer on a small continuous dataset.""" + # verify that the distribution of the samples is close to the distribution of the data + # using a kstest. + + +def test_categorical(): + """Test training the TVAE synthesizer on a small categorical dataset.""" + # verify that the distribution of the samples is close to the distribution of the data + # using a cstest. + + +def test_mixed(): + """Test training the TVAE synthesizer on a small mixed-type dataset.""" + # verify that the distribution of the samples is close to the distribution of the data + # using a kstest for continuous + a cstest for categorical. + + +def test__loss_function(): + """Test the TVAESynthesizer produces average values similar to the training data.""" + data = pd.DataFrame({ + '1': [float(i) for i in range(1000)], + '2': [float(2 * i) for i in range(1000)] + }) + + tvae = TVAESynthesizer(epochs=300) + tvae.fit(data) + + num_samples = 1000 + sampled = tvae.sample(num_samples) + error = 0 + for _, row in sampled.iterrows(): + error += abs(2 * row['1'] - row['2']) + + avg_error = error / num_samples + + assert avg_error < 400 + + +def test_fixed_random_seed(): + """Test the TVAESynthesizer with a fixed seed. + + Expect that when the random seed is reset with the same seed, the same sequence + of data will be produced. Expect that the data generated with the seed is + different than randomly sampled data. + """ + # Setup + data = pd.DataFrame({ + 'continuous': np.random.random(100), + 'discrete': np.random.choice(['a', 'b', 'c'], 100) + }) + discrete_columns = ['discrete'] + + tvae = TVAESynthesizer(epochs=1) + + # Run + tvae.fit(data, discrete_columns) + sampled_random = tvae.sample(10) + + tvae.set_random_state(0) + sampled_0_0 = tvae.sample(10) + sampled_0_1 = tvae.sample(10) + + tvae.set_random_state(0) + sampled_1_0 = tvae.sample(10) + sampled_1_1 = tvae.sample(10) + + # Assert + assert not np.array_equal(sampled_random, sampled_0_0) + assert not np.array_equal(sampled_random, sampled_0_1) + np.testing.assert_array_equal(sampled_0_0, sampled_1_0) + np.testing.assert_array_equal(sampled_0_1, sampled_1_1) diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/test_data_transformer.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/test_data_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..2f0314ca08a4cbd05d2dba7560edeeab57780306 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/test_data_transformer.py @@ -0,0 +1,42 @@ +"""Data transformer intergration testing module.""" + + +# Data Transformer tests that should be implemented in the future. +def test_constant(): + """Test transforming a dataframe containing constant values.""" + + +def test_df_continuous(): + """Test transforming a dataframe containing only continuous values.""" + # validate output ranges [0, 1] + # validate output shape (# samples, # output dims) + # validate that forward transform is **not** deterministic + # make sure it can be inverted + + +def test_df_categorical(): + """Test transforming a dataframe containing only categorical values.""" + # validate output ranges [0, 1] + # validate output shape (# samples, # output dims) + # validate that forward transform is deterministic + # make sure it can be inverted + + +def test_df_mixed(): + """Test transforming a dataframe containing mixed data types.""" + + +def test_df_mixed_nan(): + """Test transforming a dataframe containing mixed data types + NaN for categoricals.""" + + +def test_np_continuous(): + """Test transforming a np.array containing only continuous values.""" + + +def test_np_categorical(): + """Test transforming a np.array containing only categorical values.""" + + +def test_np_mixed(): + """Test transforming a np.array containing mixed data types.""" diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/__init__.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..60ff4d04eff14032ccb698a80a37aa16cb4ff1ce --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/__init__.py @@ -0,0 +1 @@ +"""Unit testing module.""" diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/__init__.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..80d7afbb190ef7d1204849cae14f6a89312c39f7 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/__init__.py @@ -0,0 +1 @@ +"""CTGANSynthesizer testing module.""" diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_base.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_base.py new file mode 100644 index 0000000000000000000000000000000000000000..5859d93deb2bebe6f07faf0a7c3b08c841e66546 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_base.py @@ -0,0 +1,111 @@ + +"""BaseSynthesizer unit testing module.""" + +from unittest.mock import MagicMock, call, patch + +import numpy as np +import torch + +from ctgan.synthesizers.base import BaseSynthesizer, random_state + + +@patch('ctgan.synthesizers.base.torch') +@patch('ctgan.synthesizers.base.np.random') +def test_valid_random_state(random_mock, torch_mock): + """Test the ``random_state`` attribute with a valid random state. + + Expect that the decorated function uses the random_state attribute. + """ + # Setup + my_function = MagicMock() + instance = MagicMock() + + random_state_mock = MagicMock() + random_state_mock.get_state.return_value = 'desired numpy state' + torch_generator_mock = MagicMock() + torch_generator_mock.get_state.return_value = 'desired torch state' + instance.random_states = (random_state_mock, torch_generator_mock) + + args = {'some', 'args'} + kwargs = {'keyword': 'value'} + + random_mock.RandomState.return_value = random_state_mock + random_mock.get_state.return_value = 'random state' + torch_mock.Generator.return_value = torch_generator_mock + torch_mock.get_rng_state.return_value = 'torch random state' + + # Run + decorated_function = random_state(my_function) + decorated_function(instance, *args, **kwargs) + + # Assert + my_function.assert_called_once_with(instance, *args, **kwargs) + + instance.assert_not_called + assert random_mock.get_state.call_count == 2 + assert torch_mock.get_rng_state.call_count == 2 + random_mock.RandomState.assert_has_calls( + [call().get_state(), call(), call().set_state('random state')]) + random_mock.set_state.assert_has_calls([call('desired numpy state'), call('random state')]) + torch_mock.set_rng_state.assert_has_calls( + [call('desired torch state'), call('torch random state')]) + + +@patch('ctgan.synthesizers.base.torch') +@patch('ctgan.synthesizers.base.np.random') +def test_no_random_seed(random_mock, torch_mock): + """Test the ``random_state`` attribute with no random state. + + Expect that the decorated function calls the original function + when there is no random state. + """ + # Setup + my_function = MagicMock() + instance = MagicMock() + instance.random_states = None + + args = {'some', 'args'} + kwargs = {'keyword': 'value'} + + # Run + decorated_function = random_state(my_function) + decorated_function(instance, *args, **kwargs) + + # Assert + my_function.assert_called_once_with(instance, *args, **kwargs) + + instance.assert_not_called + random_mock.get_state.assert_not_called() + random_mock.RandomState.assert_not_called() + random_mock.set_state.assert_not_called() + torch_mock.get_rng_state.assert_not_called() + torch_mock.Generator.assert_not_called() + torch_mock.set_rng_state.assert_not_called() + + +class TestBaseSynthesizer: + + def test_set_random_state(self): + """Test ``set_random_state`` works as expected.""" + # Setup + instance = BaseSynthesizer() + + # Run + instance.set_random_state(3) + + # Assert + assert isinstance(instance.random_states, tuple) + assert isinstance(instance.random_states[0], np.random.RandomState) + assert isinstance(instance.random_states[1], torch.Generator) + + def test_set_random_state_with_none(self): + """Test ``set_random_state`` with None.""" + # Setup + instance = BaseSynthesizer() + + # Run and assert + instance.set_random_state(3) + assert instance.random_states is not None + + instance.set_random_state(None) + assert instance.random_states is None diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_ctgan.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_ctgan.py new file mode 100644 index 0000000000000000000000000000000000000000..7a724d30779cea4e9512fc480e8417c17a21da7a --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_ctgan.py @@ -0,0 +1,343 @@ +"""CTGANSynthesizer unit testing module.""" + +from unittest import TestCase +from unittest.mock import Mock + +import pandas as pd +import pytest +import torch + +from ctgan.data_transformer import SpanInfo +from ctgan.synthesizers.ctgan import CTGANSynthesizer, Discriminator, Generator, Residual + + +class TestDiscriminator(TestCase): + + def test___init__(self): + """Test `__init__` for a generic case. + + Make sure 'self.seq' has same length as 3*`discriminator_dim` + 1. + + Setup: + - Create Discriminator + + Input: + - input_dim = positive integer + - discriminator_dim = list of integers + - pack = positive integer + + Output: + - None + + Side Effects: + - Set `self.seq`, `self.pack` and `self.packdim` + """ + discriminator_dim = [1, 2, 3] + discriminator = Discriminator(input_dim=50, discriminator_dim=discriminator_dim, pac=7) + + assert discriminator.pac == 7 + assert discriminator.pacdim == 350 + assert len(discriminator.seq) == 3 * len(discriminator_dim) + 1 + + def test_forward(self): + """Test `test_forward` for a generic case. + + Check that the output shapes are correct. + We can also test that all parameters have a gradient attached to them + by running `encoder.parameters()`. To do that, we just need to use `loss.backward()` + for some loss, like `loss = torch.mean(output)`. Notice that the input_dim = input_size. + + Setup: + - initialize with input_size, discriminator_dim, pac + - Create random tensor as input + + Input: + - input = random tensor of shape (N, input_size) + + Output: + - tensor of shape (N/pac, 1) + """ + discriminator = Discriminator(input_dim=50, discriminator_dim=[100, 200, 300], pac=7) + output = discriminator(torch.randn(70, 50)) + assert output.shape == (10, 1) + + # Check to make sure no gradients attached + for parameter in discriminator.parameters(): + assert parameter.grad is None + + # Backpropagate + output.mean().backward() + + # Check to make sure all parameters have gradients + for parameter in discriminator.parameters(): + assert parameter.grad is not None + + +class TestResidual(TestCase): + + def test_forward(self): + """Test `test_forward` for a generic case. + + Check that the output shapes are correct. + We can also test that all parameters have a gradient attached to them + by running `encoder.parameters()`. To do that, we just need to use `loss.backward()` + for some loss, like `loss = torch.mean(output)`. + + Setup: + - initialize with input_size, output_size + - Create random tensor as input + + Input: + - input = random tensor of shape (N, input_size) + + Output: + - tensor of shape (N, input_size + output_size) + """ + residual = Residual(10, 2) + output = residual(torch.randn(100, 10)) + assert output.shape == (100, 12) + + # Check to make sure no gradients attached + for parameter in residual.parameters(): + assert parameter.grad is None + + # Backpropagate + output.mean().backward() + + # Check to make sure all parameters have gradients + for parameter in residual.parameters(): + assert parameter.grad is not None + + +class TestGenerator(TestCase): + + def test___init__(self): + """Test `__init__` for a generic case. + + Make sure `self.seq` has same length as `generator_dim` + 1. + + Setup: + - Create Generator + + Input: + - embedding_dim = positive integer + - generator_dim = list of integers + - data_dim = positive integer + + Output: + - None + + Side Effects: + - Set `self.seq` + """ + generator_dim = [1, 2, 3] + generator = Generator(embedding_dim=50, generator_dim=generator_dim, data_dim=7) + + assert len(generator.seq) == len(generator_dim) + 1 + + def test_forward(self): + """Test `test_forward` for a generic case. + + Check that the output shapes are correct. + We can also test that all parameters have a gradient attached to them + by running `encoder.parameters()`. To do that, we just need to use `loss.backward()` + for some loss, like `loss = torch.mean(output)`. + + Setup: + - initialize with embedding_dim, generator_dim, data_dim + - Create random tensor as input + + Input: + - input = random tensor of shape (N, input_size) + + Output: + - tensor of shape (N, data_dim) + """ + generator = Generator(embedding_dim=60, generator_dim=[100, 200, 300], data_dim=500) + output = generator(torch.randn(70, 60)) + assert output.shape == (70, 500) + + # Check to make sure no gradients attached + for parameter in generator.parameters(): + assert parameter.grad is None + + # Backpropagate + output.mean().backward() + + # Check to make sure all parameters have gradients + for parameter in generator.parameters(): + assert parameter.grad is not None + + +def _assert_is_between(data, lower, upper): + """Assert all values of the tensor 'data' are within range.""" + assert all((data >= lower).numpy().tolist()) + assert all((data <= upper).numpy().tolist()) + + +class TestCTGANSynthesizer(TestCase): + + def test__apply_activate_(self): + """Test `_apply_activate` for tables with both continuous and categoricals. + + Check every continuous column has all values between -1 and 1 + (since they are normalized), and check every categorical column adds up to 1. + + Setup: + - Mock `self._transformer.output_info_list` + + Input: + - data = tensor of shape (N, data_dims) + + Output: + - tensor = tensor of shape (N, data_dims) + """ + model = CTGANSynthesizer() + model._transformer = Mock() + model._transformer.output_info_list = [ + [SpanInfo(3, 'softmax')], + [SpanInfo(1, 'tanh'), SpanInfo(2, 'softmax')] + ] + + data = torch.randn(100, 6) + result = model._apply_activate(data) + + assert result.shape == (100, 6) + _assert_is_between(result[:, 0:3], 0.0, 1.0) + _assert_is_between(result[: 3], -1.0, 1.0) + _assert_is_between(result[:, 4:6], 0.0, 1.0) + + def test__cond_loss(self): + """Test `_cond_loss`. + + Test that the loss is purely a function of the target categorical. + + Setup: + - mock transformer.output_info_list + - create two categoricals, one continuous + - compute the conditional loss, conditioned on the 1st categorical + - compare the loss to the cross-entropy of the 1st categorical, manually computed + + Input: + data - the synthetic data generated by the model + c - a tensor with the same shape as the data but with only a specific one-hot vector + corresponding to the target column filled in + m - binary mask used to select the categorical column to condition on + + Output: + loss scalar; this should only be affected by the target column + + Note: + - even though the implementation of this is probably right, I'm not sure if the idea + behind it is correct + """ + model = CTGANSynthesizer() + model._transformer = Mock() + model._transformer.output_info_list = [ + [SpanInfo(1, 'tanh'), SpanInfo(2, 'softmax')], + [SpanInfo(3, 'softmax')], # this is the categorical column we are conditioning on + [SpanInfo(2, 'softmax')], # this is the categorical column we are bry jrbec on + ] + + data = torch.tensor([ + # first 3 dims ignored, next 3 dims are the prediction, last 2 dims are ignored + [0.0, -1.0, 0.0, 0.05, 0.05, 0.9, 0.1, 0.4], + ]) + + c = torch.tensor([ + # first 3 dims are a one-hot for the categorical, + # next 2 are for a different categorical that we are not conditioning on + # (continuous values are not stored in this tensor) + [0.0, 0.0, 1.0, 0.0, 0.0], + ]) + + # this indicates that we are conditioning on the first categorical + m = torch.tensor([[1, 0]]) + + result = model._cond_loss(data, c, m) + expected = torch.nn.functional.cross_entropy( + torch.tensor([ + [0.05, 0.05, 0.9], # 3 categories, one hot + ]), + torch.tensor([2]) + ) + + assert (result - expected).abs() < 1e-3 + + def test__validate_discrete_columns(self): + """Test `_validate_discrete_columns` if the discrete column doesn't exist. + + Check the appropriate error is raised if `discrete_columns` is invalid, both + for numpy arrays and dataframes. + + Setup: + - Create dataframe with a discrete column + - Define `discrete_columns` as something not in the dataframe + + Input: + - train_data = 2-dimensional numpy array or a pandas.DataFrame + - discrete_columns = list of strings or integers + + Output: + None + + Side Effects: + - Raises error if the discrete column is invalid. + + Note: + - could create another function for numpy array + """ + data = pd.DataFrame({ + 'discrete': ['a', 'b'] + }) + discrete_columns = ['doesnt exist'] + + ctgan = CTGANSynthesizer(epochs=1) + with pytest.raises(ValueError, match=r'Invalid columns found: {\'doesnt exist\'}'): + ctgan.fit(data, discrete_columns) + + def test_sample(self): + """Test `sample` correctly sets `condition_info` and `global_condition_vec`. + + Tests the first 7 lines of sample by mocking the DataTransformer and DataSampler + and checking that they are being correctly used. + + Setup: + - Create and fit the synthesizer + - Mock DataTransformer, DataSampler + + Input: + - n = integer + - condition_column = string (not None) + - condition_value = string (not None) + + Output: + Not relevant + + Note: + - I'm not sure we need this test + """ + + def test_set_device(self): + """Test 'set_device' if a GPU is available. + + Check that decoder/encoder can successfully be moved to the device. + If the machine doesn't have a GPU, this test shouldn't run. + + Setup: + - Move decoder/encoder to device + + Input: + - device = string + + Output: + None + + Side Effects: + - Set `self._device` to `device` + - Moves `self.decoder` to `self._device` + + Note: + - Need to be careful when checking whether the encoder is actually set + to the right device, since it's not saved (it's only used in fit). + """ diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_tvae.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_tvae.py new file mode 100644 index 0000000000000000000000000000000000000000..cff981a86078d1689bec7bb5a37856aa903b68e7 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_tvae.py @@ -0,0 +1,123 @@ +"""TVAESynthesizer unit testing module.""" + +from unittest import TestCase + + +class TestEncoder(TestCase): + + def test___init__(self): + """Test `__init__` for a generic case. + + Make sure 'self.seq' has same length as 2*`compress_dims`. + + Setup: + - Create Encoder + + Input: + - data_dim = positive integer + - compress_dims = list of integers + - embedding_dim = positive integer + + Output: + - None + + Side Effects: + - Set `self.seq`, `self.fc1` and `self.fc2` + """ + + def test_forward(self): + """Test `test_forward` for a generic case. + + Check that the output shapes are correct and that std is positive. + We can also test that all parameters have a gradient attached to them + by running `encoder.parameters()`. To do that, we just need to use `loss.backward()` + for some loss, like `loss = torch.mean(mu) + torch.mean(std) + torch.mean(logvar)`. + + Setup: + - Create random tensor + + Input: + - input = random tensor of shape (N, data_dim) + + Output: + - Tuple of (mu, std, logvar): + mu - tensor of shape (N, embedding_dim) + std - tensor of shape (N, embedding_dim), non-negative values + logvar - tensor of shape (N, embedding_dim) + """ + + +class TestDecoder(TestCase): + + def test___init__(self): + """Test `__init__` for a generic case. + + Make sure 'self.seq' has same length as 2*`decompress_dims` + 1. + + Setup: + - Create Decoder + + Input: + - data_dim = positive integer + - decompress_dims = list of integers + - embedding_dim = positive integer + + Output: + - None + + Side Effects: + - Set `self.seq`, `self.sigma` + """ + + +class TestLossFunction(TestCase): + + def test__loss_function(self): + """Test `_loss_function`. + + Check loss values = to specific numbers. + + Setup: + Build all the tensors, lists, etc. + + Input: + recon_x = tensor of shape (N, data_dims) + x = tensor of shape (N, data_dims) + sigmas = tensor of shape (N,) + mu = tensor of shape (N,) + logvar = tensor of shape (N,) + output_info = list of SpanInfo objects from the data transformer, + including at least 1 continuous and 1 discrete + factor = scalar + + Output: + reconstruction loss = scalar = f(recon_x, x, sigmas, output_info, factor) + kld loss = scalar = f(logvar, mu) + """ + + +class TestTVAESynthesizer(TestCase): + + def test_set_device(self): + """Test 'set_device' if a GPU is available. + + Check that decoder/encoder can successfully be moved to the device. + If the machine doesn't have a GPU, this test shouldn't run. + + Setup: + - Move decoder/encoder to device + + Input: + - device = string + + Output: + None + + Side Effects: + - Set `self._device` to `device` + - Moves `self.decoder` to `self._device` + + Note: + - Need to be careful when checking whether the encoder is actually set + to the right device, since it's not saved (it's only used in fit). + """ diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/test_data_transformer.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/test_data_transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..305f84ee5e57d156348b54400a5c6138d3466b40 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/test_data_transformer.py @@ -0,0 +1,473 @@ +"""Data transformer unit testing module.""" + +from unittest import TestCase +from unittest.mock import Mock, patch + +import numpy as np +import pandas as pd + +from ctgan.data_transformer import ColumnTransformInfo, DataTransformer, SpanInfo + + +class TestDataTransformer(TestCase): + + @patch('ctgan.data_transformer.BayesGMMTransformer') + def test___fit_continuous(self, MockBGM): + """Test ``_fit_continuous`` on a simple continuous column. + + A ``BayesGMMTransformer`` will be created and fit with some ``data``. + + Setup: + - Mock the ``BayesGMMTransformer`` with ``valid_component_indicator`` as + ``[True, False, True]``. + - Initialize a ``DataTransformer``. + + Input: + - A dataframe with only one column containing random float values. + + Output: + - A ``ColumnTransformInfo`` object where: + - ``column_name`` matches the column of the data. + - ``transform`` is the ``BayesGMMTransformer`` instance. + - ``output_dimensions`` is 3 (matches size of ``valid_component_indicator``). + - ``output_info`` assigns the correct activation functions. + + Side Effects: + - ``fit`` should be called with the data. + """ + # Setup + bgm_instance = MockBGM.return_value + bgm_instance.valid_component_indicator = [True, False, True] + transformer = DataTransformer() + data = pd.DataFrame(np.random.normal((100, 1)), columns=['column']) + + # Run + info = transformer._fit_continuous(data) + + # Assert + assert info.column_name == 'column' + assert info.transform == bgm_instance + assert info.output_dimensions == 3 + assert info.output_info[0].dim == 1 + assert info.output_info[0].activation_fn == 'tanh' + assert info.output_info[1].dim == 2 + assert info.output_info[1].activation_fn == 'softmax' + + @patch('ctgan.data_transformer.BayesGMMTransformer') + def test__fit_continuous_max_clusters(self, MockBGM): + """Test ``_fit_continuous`` with data that has less than 10 rows. + + Expect that a ``BayesGMMTransformer`` is created with the max number of clusters + set to the length of the data. + + Input: + - Data with less than 10 rows. + + Side Effects: + - A ``BayesGMMTransformer`` is created with the max number of clusters set to the + length of the data. + """ + # Setup + data = pd.DataFrame(np.random.normal((7, 1)), columns=['column']) + transformer = DataTransformer() + + # Run + transformer._fit_continuous(data) + + # Assert + MockBGM.assert_called_once_with(max_clusters=len(data)) + + @patch('ctgan.data_transformer.OneHotEncodingTransformer') + def test___fit_discrete(self, MockOHE): + """Test ``_fit_discrete_`` on a simple discrete column. + + A ``OneHotEncodingTransformer`` will be created and fit with the ``data``. + + Setup: + - Mock the ``OneHotEncodingTransformer``. + - Create ``DataTransformer``. + + Input: + - A dataframe with only one column containing ``['a', 'b']`` values. + + Output: + - A ``ColumnTransformInfo`` object where: + - ``column_name`` matches the column of the data. + - ``transform`` is the ``OneHotEncodingTransformer`` instance. + - ``output_dimensions`` is 2. + - ``output_info`` assigns the correct activation function. + + Side Effects: + - ``fit`` should be called with the data. + """ + # Setup + ohe_instance = MockOHE.return_value + ohe_instance.dummies = ['a', 'b'] + transformer = DataTransformer() + data = pd.DataFrame(np.array(['a', 'b'] * 100), columns=['column']) + + # Run + info = transformer._fit_discrete(data) + + # Assert + assert info.column_name == 'column' + assert info.transform == ohe_instance + assert info.output_dimensions == 2 + assert info.output_info[0].dim == 2 + assert info.output_info[0].activation_fn == 'softmax' + + def test_fit(self): + """Test ``fit`` on a np.ndarray with one continuous and one discrete columns. + + The ``fit`` method should: + - Set ``self.dataframe`` to ``False``. + - Set ``self._column_raw_dtypes`` to the appropirate dtypes. + - Use the appropriate ``_fit`` type for each column. + - Update ``self.output_info_list``, ``self.output_dimensions`` and + ``self._column_transform_info_list`` appropriately. + + Setup: + - Create ``DataTransformer``. + - Mock ``_fit_discrete``. + - Mock ``_fit_continuous``. + + Input: + - A table with one continuous and one discrete columns. + - A list with the name of the discrete column. + + Side Effects: + - ``_fit_discrete`` and ``_fit_continuous`` should each be called once. + - Assigns ``self._column_raw_dtypes`` the appropriate dtypes. + - Assigns ``self.output_info_list`` the appropriate ``output_info``. + - Assigns ``self.output_dimensions`` the appropriate ``output_dimensions``. + - Assigns ``self._column_transform_info_list`` the appropriate + ``column_transform_info``. + """ + # Setup + transformer = DataTransformer() + transformer._fit_continuous = Mock() + transformer._fit_continuous.return_value = ColumnTransformInfo( + column_name='x', column_type='continuous', transform=None, + output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')], + output_dimensions=1 + 3 + ) + + transformer._fit_discrete = Mock() + transformer._fit_discrete.return_value = ColumnTransformInfo( + column_name='y', column_type='discrete', transform=None, + output_info=[SpanInfo(2, 'softmax')], + output_dimensions=2 + ) + + data = pd.DataFrame({ + 'x': np.random.random(size=100), + 'y': np.random.choice(['yes', 'no'], size=100) + }) + + # Run + transformer.fit(data, discrete_columns=['y']) + + # Assert + transformer._fit_discrete.assert_called_once() + transformer._fit_continuous.assert_called_once() + assert transformer.output_dimensions == 6 + + @patch('ctgan.data_transformer.BayesGMMTransformer') + def test__transform_continuous(self, MockBGM): + """Test ``_transform_continuous``. + + Setup: + - Mock the ``BayesGMMTransformer`` with the transform method returning + some dataframe. + - Create ``DataTransformer``. + + Input: + - ``ColumnTransformInfo`` object. + - A dataframe containing a continuous column. + + Output: + - A np.array where the first column contains the normalized part + of the mocked transform, and the other columns are a one hot encoding + representation of the component part of the mocked transform. + """ + # Setup + bgm_instance = MockBGM.return_value + bgm_instance.transform.return_value = pd.DataFrame({ + 'x.normalized': [0.1, 0.2, 0.3], + 'x.component': [0.0, 1.0, 1.0] + }) + + transformer = DataTransformer() + data = pd.DataFrame({'x': np.array([0.1, 0.3, 0.5])}) + column_transform_info = ColumnTransformInfo( + column_name='x', column_type='continuous', transform=bgm_instance, + output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')], + output_dimensions=1 + 3 + ) + + # Run + result = transformer._transform_continuous(column_transform_info, data) + + # Assert + expected = np.array([ + [0.1, 1, 0, 0], + [0.2, 0, 1, 0], + [0.3, 0, 1, 0], + ]) + np.testing.assert_array_equal(result, expected) + + def test_transform(self): + """Test ``transform`` on a dataframe with one continuous and one discrete columns. + + It should use the appropriate ``_transform`` type for each column and should return + them concanenated appropriately. + + Setup: + - Initialize a ``DataTransformer`` with a ``column_transform_info`` detailing + a continuous and a discrete columns. + - Mock the ``_transform_discrete`` and ``_transform_continuous`` methods. + + Input: + - A table with one continuous and one discrete columns. + + Output: + - np.array containing the transformed columns. + + Side Effects: + - ``_transform_discrete`` and ``_transform_continuous`` should each be called once. + """ + # Setup + data = pd.DataFrame({ + 'x': np.array([0.1, 0.3, 0.5]), + 'y': np.array(['yes', 'yes', 'no']) + }) + + transformer = DataTransformer() + transformer._column_transform_info_list = [ + ColumnTransformInfo( + column_name='x', column_type='continuous', transform=None, + output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')], + output_dimensions=1 + 3 + ), + ColumnTransformInfo( + column_name='y', column_type='discrete', transform=None, + output_info=[SpanInfo(2, 'softmax')], + output_dimensions=2 + ) + ] + + transformer._transform_continuous = Mock() + selected_normalized_value = np.array([[0.1], [0.3], [0.5]]) + selected_component_onehot = np.array([ + [1, 0, 0], + [0, 1, 0], + [0, 1, 0], + ]) + return_value = np.concatenate( + (selected_normalized_value, selected_component_onehot), axis=1) + transformer._transform_continuous.return_value = return_value + + transformer._transform_discrete = Mock() + transformer._transform_discrete.return_value = np.array([ + [0, 1], + [0, 1], + [1, 0], + ]) + + # Run + result = transformer.transform(data) + + # Assert + transformer._transform_continuous.assert_called_once() + transformer._transform_discrete.assert_called_once() + + expected = np.array([ + [0.1, 1, 0, 0, 0, 1], + [0.3, 0, 1, 0, 0, 1], + [0.5, 0, 1, 0, 1, 0], + ]) + assert result.shape == (3, 6) + assert (result[:, 0] == expected[:, 0]).all(), 'continuous-cdf' + assert (result[:, 1:4] == expected[:, 1:4]).all(), 'continuous-softmax' + assert (result[:, 4:6] == expected[:, 4:6]).all(), 'discrete' + + @patch('ctgan.data_transformer.BayesGMMTransformer') + def test__inverse_transform_continuous(self, MockBGM): + """Test ``_inverse_transform_continuous``. + + Setup: + - Create ``DataTransformer``. + - Mock the ``BayesGMMTransformer`` where: + - ``get_output_types`` returns the appropriate dictionary. + - ``reverse_transform`` returns some dataframe. + + Input: + - A ``ColumnTransformInfo`` object. + - A np.ndarray where: + - The first column contains the normalized value + - The remaining columns correspond to the one-hot + - sigmas = np.ndarray of floats + - st = index of the sigmas ndarray + + Output: + - Dataframe where the first column are floats and the second is a lable encoding. + + Side Effects: + - The ``reverse_transform`` method should be called with a dataframe + where the first column are floats and the second is a lable encoding. + """ + # Setup + bgm_instance = MockBGM.return_value + bgm_instance.get_output_types.return_value = { + 'x.normalized': 'numerical', + 'x.component': 'numerical' + } + + bgm_instance.reverse_transform.return_value = pd.DataFrame({ + 'x.normalized': [0.1, 0.2, 0.3], + 'x.component': [0.0, 1.0, 1.0] + }) + + transformer = DataTransformer() + column_data = np.array([ + [0.1, 1, 0, 0], + [0.3, 0, 1, 0], + [0.5, 0, 1, 0], + ]) + + column_transform_info = ColumnTransformInfo( + column_name='x', column_type='continuous', transform=bgm_instance, + output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')], + output_dimensions=1 + 3 + ) + + # Run + result = transformer._inverse_transform_continuous( + column_transform_info, column_data, None, None) + + # Assert + expected = pd.DataFrame({ + 'x.normalized': [0.1, 0.2, 0.3], + 'x.component': [0.0, 1.0, 1.0] + }) + + np.testing.assert_array_equal(result, expected) + + expected_data = pd.DataFrame({ + 'x.normalized': [0.1, 0.3, 0.5], + 'x.component': [0, 1, 1] + }) + + pd.testing.assert_frame_equal( + bgm_instance.reverse_transform.call_args[0][0], + expected_data + ) + + def test_inverse_transform(self): + """Test ``inverse_transform`` on a np.ndarray with continuous and discrete columns. + + It should use the appropriate '_fit' type for each column and should return + the corresponding columns. Since we are using the same example as the 'test_transform', + and these two functions are inverse of each other, the returned value here should + match the input of that function. + + Setup: + - Mock _column_transform_info_list + - Mock _inverse_transform_discrete + - Mock _inverse_trarnsform_continuous + + Input: + - column_data = a concatenation of two np.ndarrays + - the first one refers to the continuous values + - the first column contains the normalized values + - the remaining columns correspond to the a one-hot + - the second one refers to the discrete values + - the columns correspond to a one-hot + Output: + - numpy array containing a discrete column and a continuous column + + Side Effects: + - _transform_discrete and _transform_continuous should each be called once. + """ + + def test_convert_column_name_value_to_id(self): + """Test ``convert_column_name_value_to_id`` on a simple ``_column_transform_info_list``. + + Tests that the appropriate indexes are returned when a table of three columns, + discrete, continuous, discrete, is passed as '_column_transform_info_list'. + + Setup: + - Mock ``_column_transform_info_list``. + + Input: + - column_name = the name of a discrete column + - value = the categorical value + + Output: + - dictionary containing: + - ``discrete_column_id`` = the index of the target column, + when considering only discrete columns + - ``column_id`` = the index of the target column + (e.g. 3 = the third column in the data) + - ``value_id`` = the index of the indicator value in the one-hot encoding + """ + # Setup + ohe = Mock() + ohe.transform.return_value = pd.DataFrame([ + [0, 1] # one hot encoding, second dimension + ]) + transformer = DataTransformer() + transformer._column_transform_info_list = [ + ColumnTransformInfo( + column_name='x', column_type='continuous', transform=None, + output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')], + output_dimensions=1 + 3 + ), + ColumnTransformInfo( + column_name='y', column_type='discrete', transform=ohe, + output_info=[SpanInfo(2, 'softmax')], + output_dimensions=2 + ) + ] + + # Run + result = transformer.convert_column_name_value_to_id('y', 'yes') + + # Assert + assert result['column_id'] == 1 # this is the 2nd column + assert result['discrete_column_id'] == 0 # this is the 1st discrete column + assert result['value_id'] == 1 # this is the 2nd dimension in the one hot encoding + + def test_convert_column_name_value_to_id_multiple(self): + """Test ``convert_column_name_value_to_id``.""" + # Setup + ohe = Mock() + ohe.transform.return_value = pd.DataFrame([ + [0, 1, 0] # one hot encoding, second dimension + ]) + transformer = DataTransformer() + transformer._column_transform_info_list = [ + ColumnTransformInfo( + column_name='x', column_type='continuous', transform=None, + output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')], + output_dimensions=1 + 3 + ), + ColumnTransformInfo( + column_name='y', column_type='discrete', transform=ohe, + output_info=[SpanInfo(2, 'softmax')], + output_dimensions=2 + ), + ColumnTransformInfo( + column_name='z', column_type='discrete', transform=ohe, + output_info=[SpanInfo(2, 'softmax')], + output_dimensions=2 + ) + ] + + # Run + result = transformer.convert_column_name_value_to_id('z', 'yes') + + # Assert + assert result['column_id'] == 2 # this is the 3rd column + assert result['discrete_column_id'] == 1 # this is the 2nd discrete column + assert result['value_id'] == 1 # this is the 1st dimension in the one hot encoding diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tox.ini b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..5fbffba409c0fee10719de58cf5a5bf4639b374e --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tox.ini @@ -0,0 +1,19 @@ +[tox] +envlist = py38-lint, py3{6,7,8,9}-{unit,integration,readme} + +[testenv] +skipsdist = false +skip_install = false +deps = + invoke + readme: rundoc +extras = + lint: dev + unit: test + integration: test +commands = + lint: invoke lint + unit: invoke unit + integration: invoke integration + readme: invoke readme + invoke rmdir --path {envdir} diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/__init__.cpython-311.pyc b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/__init__.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1604250c3d8e6c8c288bcc2d9d48fae4cd84030d Binary files /dev/null and b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/__init__.cpython-311.pyc differ diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/data.cpython-311.pyc b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/data.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2e249ac45b9f949833ee23b6b41550d798ba61d Binary files /dev/null and b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/data.cpython-311.pyc differ diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/deep.cpython-311.pyc b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/deep.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..768685a4a160085dacce8e40229d93ae06a136be Binary files /dev/null and b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/deep.cpython-311.pyc differ diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/env.cpython-311.pyc b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/env.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a95b6ed55bba434311c8309b671d2020d365c1eb Binary files /dev/null and b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/env.cpython-311.pyc differ diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/metrics.cpython-311.pyc b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/metrics.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fbb8460fc066e4f58e29954619dd7f7d07a4f4b4 Binary files /dev/null and b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/metrics.cpython-311.pyc differ diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/util.cpython-311.pyc b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/util.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..119e2870726ef75764ee4e7870748bb355dc9a8c Binary files /dev/null and b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/lib/__pycache__/util.cpython-311.pyc differ diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_ddpm.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_ddpm.py new file mode 100644 index 0000000000000000000000000000000000000000..5a95dc23cab775a9ca7b7eb496bcefef58691dce --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/tune_ddpm.py @@ -0,0 +1,127 @@ +import subprocess +import lib +import os +import optuna +from copy import deepcopy +import shutil +import argparse +from pathlib import Path + +parser = argparse.ArgumentParser() +parser.add_argument('ds_name', type=str) +parser.add_argument('train_size', type=int) +parser.add_argument('eval_type', type=str) +parser.add_argument('eval_model', type=str) +parser.add_argument('prefix', type=str) +parser.add_argument('--eval_seeds', action='store_true', default=False) + +args = parser.parse_args() +train_size = args.train_size +ds_name = args.ds_name +eval_type = args.eval_type +assert eval_type in ('merged', 'synthetic') +prefix = str(args.prefix) + +pipeline = f'scripts/pipeline.py' +base_config_path = f'exp/{ds_name}/config.toml' +parent_path = Path(f'exp/{ds_name}/') +exps_path = Path(f'exp/{ds_name}/many-exps/') # temporary dir. maybe will be replaced with tempdiвdr +eval_seeds = f'scripts/eval_seeds.py' + +os.makedirs(exps_path, exist_ok=True) + +def _suggest_mlp_layers(trial): + def suggest_dim(name): + t = trial.suggest_int(name, d_min, d_max) + return 2 ** t + min_n_layers, max_n_layers, d_min, d_max = 1, 4, 7, 10 + n_layers = 2 * 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 + return d_layers + +def objective(trial): + + lr = trial.suggest_loguniform('lr', 0.00001, 0.003) + d_layers = _suggest_mlp_layers(trial) + weight_decay = 0.0 + batch_size = trial.suggest_categorical('batch_size', [256, 4096]) + steps = trial.suggest_categorical('steps', [5000, 20000, 30000]) + # steps = trial.suggest_categorical('steps', [500]) # for debug + gaussian_loss_type = 'mse' + # scheduler = trial.suggest_categorical('scheduler', ['cosine', 'linear']) + num_timesteps = trial.suggest_categorical('num_timesteps', [100, 1000]) + num_samples = int(train_size * (2 ** trial.suggest_int('num_samples', -2, 1))) + + base_config = lib.load_config(base_config_path) + + base_config['train']['main']['lr'] = lr + base_config['train']['main']['steps'] = steps + base_config['train']['main']['batch_size'] = batch_size + base_config['train']['main']['weight_decay'] = weight_decay + base_config['model_params']['rtdl_params']['d_layers'] = d_layers + base_config['eval']['type']['eval_type'] = eval_type + base_config['sample']['num_samples'] = num_samples + base_config['diffusion_params']['gaussian_loss_type'] = gaussian_loss_type + base_config['diffusion_params']['num_timesteps'] = num_timesteps + # base_config['diffusion_params']['scheduler'] = scheduler + + base_config['parent_dir'] = str(exps_path / f"{trial.number}") + base_config['eval']['type']['eval_model'] = args.eval_model + if args.eval_model == "mlp": + base_config['eval']['T']['normalization'] = "quantile" + base_config['eval']['T']['cat_encoding'] = "one-hot" + + trial.set_user_attr("config", base_config) + + lib.dump_config(base_config, exps_path / 'config.toml') + + subprocess.run(['python3.9', f'{pipeline}', '--config', f'{exps_path / "config.toml"}', '--train', '--change_val'], check=True) + + n_datasets = 5 + score = 0.0 + + for sample_seed in range(n_datasets): + base_config['sample']['seed'] = sample_seed + lib.dump_config(base_config, exps_path / 'config.toml') + + subprocess.run(['python3.9', f'{pipeline}', '--config', f'{exps_path / "config.toml"}', '--sample', '--eval', '--change_val'], check=True) + + report_path = str(Path(base_config['parent_dir']) / f'results_{args.eval_model}.json') + report = lib.load_json(report_path) + + if 'r2' in report['metrics']['val']: + score += report['metrics']['val']['r2'] + else: + score += report['metrics']['val']['macro avg']['f1-score'] + + shutil.rmtree(exps_path / f"{trial.number}") + + return score / n_datasets + +study = optuna.create_study( + direction='maximize', + sampler=optuna.samplers.TPESampler(seed=0), +) + +study.optimize(objective, n_trials=50, show_progress_bar=True) + +best_config_path = parent_path / f'{prefix}_best/config.toml' +best_config = study.best_trial.user_attrs['config'] +best_config["parent_dir"] = str(parent_path / f'{prefix}_best/') + +os.makedirs(parent_path / f'{prefix}_best', exist_ok=True) +lib.dump_config(best_config, best_config_path) +lib.dump_json(optuna.importance.get_param_importances(study), parent_path / f'{prefix}_best/importance.json') + +subprocess.run(['python3.9', f'{pipeline}', '--config', f'{best_config_path}', '--train', '--sample'], check=True) + +if args.eval_seeds: + best_exp = str(parent_path / f'{prefix}_best/config.toml') + subprocess.run(['python3.9', f'{eval_seeds}', '--config', f'{best_exp}', '10', "ddpm", eval_type, args.eval_model, '5'], check=True) \ No newline at end of file diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/utils_train.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/utils_train.py new file mode 100644 index 0000000000000000000000000000000000000000..4132ca56fb8e063111f916f903ef4e99206486e3 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/scripts/utils_train.py @@ -0,0 +1,89 @@ +import numpy as np +import os +import lib +from tab_ddpm.modules import MLPDiffusion, ResNetDiffusion + +def get_model( + model_name, + model_params, + n_num_features, + category_sizes +): + print(model_name) + if model_name == 'mlp': + model = MLPDiffusion(**model_params) + elif model_name == 'resnet': + model = ResNetDiffusion(**model_params) + else: + raise "Unknown model!" + return model + +def update_ema(target_params, source_params, rate=0.999): + """ + Update target parameters to be closer to those of source parameters using + an exponential moving average. + :param target_params: the target parameter sequence. + :param source_params: the source parameter sequence. + :param rate: the EMA rate (closer to 1 means slower). + """ + for targ, src in zip(target_params, source_params): + targ.detach().mul_(rate).add_(src.detach(), alpha=1 - rate) + +def concat_y_to_X(X, y): + if X is None: + return y.reshape(-1, 1) + return np.concatenate([y.reshape(-1, 1), X], axis=1) + +def make_dataset( + data_path: str, + T: lib.Transformations, + num_classes: int, + is_y_cond: bool, + change_val: bool +): + # classification + if num_classes > 0: + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) or not is_y_cond else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) else None + y = {} + + for split in ['train']: + X_num_t, X_cat_t, y_t = lib.read_pure_data(data_path, split) + if X_num is not None: + X_num[split] = X_num_t + if not is_y_cond: + X_cat_t = concat_y_to_X(X_cat_t, y_t) + if X_cat is not None: + X_cat[split] = X_cat_t + y[split] = y_t + else: + # regression + X_cat = {} if os.path.exists(os.path.join(data_path, 'X_cat_train.npy')) else None + X_num = {} if os.path.exists(os.path.join(data_path, 'X_num_train.npy')) or not is_y_cond else None + y = {} + + for split in ['train']: + X_num_t, X_cat_t, y_t = lib.read_pure_data(data_path, split) + if not is_y_cond: + X_num_t = concat_y_to_X(X_num_t, y_t) + if X_num is not None: + X_num[split] = X_num_t + if X_cat is not None: + X_cat[split] = X_cat_t + y[split] = y_t + + info = lib.load_json(os.path.join(data_path, 'info.json')) + + D = lib.Dataset( + X_num, + X_cat, + y, + y_info={}, + task_type=lib.TaskType(info['task_type']), + n_classes=info.get('n_classes') + ) + + if change_val: + D = lib.change_val(D) + + return lib.transform_dataset(D, T, None) \ No newline at end of file diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/pipeline_smote.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/pipeline_smote.py new file mode 100644 index 0000000000000000000000000000000000000000..4a6775493e975104c268a2cd177f953ea9589d0a --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/pipeline_smote.py @@ -0,0 +1,68 @@ +import tomli +import shutil +import os +import argparse +from sample_smote import sample_smote +from scripts.eval_catboost import train_catboost +# from scripts.eval_mlp import train_mlp +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('--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) + if args.sample: + sample_smote( + parent_dir=raw_config['parent_dir'], + real_data_path=raw_config['real_data_path'], + **raw_config['smote_params'], + seed=raw_config['seed'], + change_val=args.change_val + ) + + 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/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/sample_smote.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/sample_smote.py new file mode 100644 index 0000000000000000000000000000000000000000..63674186c3f1524d57bb4882f0c3dd432147230f --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/sample_smote.py @@ -0,0 +1,210 @@ +import os +import lib +import argparse +import numpy as np +from pathlib import Path +from typing import Union, Any +from imblearn.over_sampling import SMOTE, SMOTENC +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import MinMaxScaler +from sklearn.utils import check_random_state + +class MySMOTE(SMOTE): + def __init__( + self, + lam1=0.0, + lam2=1.0, + *, + sampling_strategy="auto", + random_state=None, + k_neighbors=5, + n_jobs=None, + ): + super().__init__( + sampling_strategy=sampling_strategy, + random_state=random_state, + k_neighbors=k_neighbors, + n_jobs=n_jobs, + ) + + self.lam1=lam1 + self.lam2=lam2 + + def _make_samples( + self, X, y_dtype, y_type, nn_data, nn_num, n_samples, step_size=1.0 + ): + random_state = check_random_state(self.random_state) + samples_indices = random_state.randint(low=0, high=nn_num.size, size=n_samples) + + # np.newaxis for backwards compatability with random_state + steps = step_size * random_state.uniform(low=self.lam1, high=self.lam2, size=n_samples)[:, np.newaxis] + rows = np.floor_divide(samples_indices, nn_num.shape[1]) + cols = np.mod(samples_indices, nn_num.shape[1]) + + X_new = self._generate_samples(X, nn_data, nn_num, rows, cols, steps) + y_new = np.full(n_samples, fill_value=y_type, dtype=y_dtype) + return X_new, y_new + +class MySMOTENC(SMOTENC): + def __init__( + self, + lam1=0.0, + lam2=1.0, + *, + categorical_features, + sampling_strategy="auto", + random_state=None, + k_neighbors=5, + n_jobs=None + ): + super().__init__( + categorical_features=categorical_features, + sampling_strategy=sampling_strategy, + random_state=random_state, + k_neighbors=k_neighbors, + n_jobs=n_jobs, + ) + + self.lam1=0.0 + self.lam2=1.0 + + def _make_samples( + self, X, y_dtype, y_type, nn_data, nn_num, n_samples, step_size=1.0, lam1=0.0, lam2=1.0 + ): + random_state = check_random_state(self.random_state) + samples_indices = random_state.randint(low=0, high=nn_num.size, size=n_samples) + + # np.newaxis for backwards compatability with random_state + steps = step_size * random_state.uniform(low=self.lam1, high=self.lam2, size=n_samples)[:, np.newaxis] + rows = np.floor_divide(samples_indices, nn_num.shape[1]) + cols = np.mod(samples_indices, nn_num.shape[1]) + + X_new = self._generate_samples(X, nn_data, nn_num, rows, cols, steps) + y_new = np.full(n_samples, fill_value=y_type, dtype=y_dtype) + return X_new, y_new + +def save_data(X, y, path, n_cat_features=0): + if n_cat_features > 0: + X_num = X[:, :-n_cat_features] + X_cat = X[:, -n_cat_features:] + else: + X_num = X + X_cat = None + + + np.save(path / "X_num_train", X_num.astype(float), allow_pickle=True) + np.save(path / "y_train", y, allow_pickle=True) + if X_cat is not None: + np.save(path / "X_cat_train", X_cat, allow_pickle=True) + +def sample_smote( + parent_dir, + real_data_path, + eval_type = "synthetic", + k_neighbours = 5, + frac_samples = 1.0, + frac_lam_del = 0.0, + change_val = False, + save = True, + seed = 0 +): + lam1 = 0.0 + frac_lam_del / 2 + lam2 = 1.0 - frac_lam_del / 2 + + real_data_path = Path(real_data_path) + info = lib.load_json(real_data_path / 'info.json') + is_regression = info['task_type'] == 'regression' + + X_num = {} + X_cat = {} + y = {} + + if change_val: + X_num['train'], X_cat['train'], y['train'], X_num['val'], X_cat['val'], y['val'] = 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_num['val'], X_cat['val'], y['val'] = lib.read_pure_data(real_data_path, 'val') + X_num['test'], X_cat['test'], y['test'] = lib.read_pure_data(real_data_path, 'test') + + + X = {k: X_num[k] for k in X_num.keys()} + + if is_regression: + X['train'] = np.concatenate([X["train"], y["train"].reshape(-1, 1)], axis=1, dtype=object) + y['train'] = np.where(y["train"] > np.median(y["train"]), 1, 0) + + n_num_features = X['train'].shape[1] + n_cat_features = X_cat['train'].shape[1] if X_cat['train'] is not None else 0 + cat_features = list(range(n_num_features, n_num_features+n_cat_features)) + print(cat_features) + + scaler = MinMaxScaler().fit(X["train"]) + X["train"] = scaler.transform(X["train"]).astype(object) + + if X_cat['train'] is not None: + for k in X_num.keys(): + X[k] = np.concatenate([X[k], X_cat[k]], axis=1, dtype=object) + + print("Before:", X['train'].shape) + + if eval_type != 'real': + strat = {k: int((1 + frac_samples) * np.sum(y['train'] == k)) for k in np.unique(y['train'])} + print(strat) + if n_cat_features > 0: + sm = MySMOTENC( + lam1=lam1, + lam2=lam2, + random_state=seed, + k_neighbors=k_neighbours, + categorical_features=cat_features, + sampling_strategy=strat + ) + else: + sm = MySMOTE( + lam1=lam1, + lam2=lam2, + random_state=seed, + k_neighbors=k_neighbours, + sampling_strategy=strat + ) + + X_res, y_res = sm.fit_resample(X['train'], y['train']) + if is_regression: + X_res[:, :X_num["train"].shape[1]+1] = scaler.inverse_transform(X_res[:, :X_num["train"].shape[1]+1]) + y_res = X_res[:, X_num["train"].shape[1]] + X_res = np.delete(X_res, [X_num["train"].shape[1]], axis=1) + else: + X_res[:, :X_num["train"].shape[1]] = scaler.inverse_transform(X_res[:, :X_num["train"].shape[1]]) + y_res = y_res.astype(int) + + if eval_type == "synthetic": + X_res = X_res[X['train'].shape[0]:] + y_res = y_res[X['train'].shape[0]:] + + disc_cols = [] + for col in range(X_num["train"].shape[1]): + uniq_vals = np.unique(X_num["train"][:, col]) + if len(uniq_vals) <= 32 and ((uniq_vals - np.round(uniq_vals)) == 0).all(): + disc_cols.append(col) + if len(disc_cols): + X_res[:, :X_num["train"].shape[1]] = lib.round_columns(X_num["train"], X_res[:, :X_num["train"].shape[1]], disc_cols) + + if save: + save_data(X_res, y_res, Path(parent_dir), n_cat_features) + + X['train'] = X_res + y['train'] = y_res + + return X, y + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('data_path', type=str) + parser.add_argument('method', type=str) + + args = parser.parse_args() + + sample_smote(args.data_path, args.method, save=False) + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/tune_smote.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/tune_smote.py new file mode 100644 index 0000000000000000000000000000000000000000..9c98e205150bd02fee9ce399280714101bd427c3 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/smote/tune_smote.py @@ -0,0 +1,98 @@ +import optuna +import lib +from copy import deepcopy +import argparse +import tempfile +from pathlib import Path +import os +from scripts.eval_catboost import train_catboost +from sample_smote import sample_smote +import subprocess + +parser = argparse.ArgumentParser() +parser.add_argument('data_path', type=str) +parser.add_argument('eval_type', type=str) + +args = parser.parse_args() +real_data_path = args.data_path +eval_type = args.eval_type + +def objective(trial): + + k_neighbours = trial.suggest_int("k_neighbours", 5, 20) + frac_samples = 2 ** trial.suggest_int('frac_samples', -2, 3) + + # z = \lam*x + (1 - \lam)*y, \lam ~ U[frac_lam_del/2, 1-frac_lam_del/2] + frac_lam_del = trial.suggest_float("frac_lam_del", 0.0, 0.95, step=0.05) + + score = 0.0 + with tempfile.TemporaryDirectory() as dir_: + dir_ = Path(dir_) + for seed in range(5): + sample_smote( + parent_dir=dir_, + real_data_path=real_data_path, + eval_type=eval_type, + frac_samples=frac_samples, + frac_lam_del=frac_lam_del, + k_neighbours=k_neighbours, + change_val=True, + seed=seed + ) + 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=5, show_progress_bar=True) + +os.makedirs(f"exp/{Path(real_data_path).name}/smote/", exist_ok=True) +config = { + "parent_dir": f"exp/{Path(real_data_path).name}/smote/", + "real_data_path": real_data_path, + "seed": 0, + "smote_params": {}, + "sample": {"seed": 0}, + "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" + }, + } +} + +config["smote_params"] = study.best_params +config["smote_params"]["frac_samples"] = 2 ** config["smote_params"]["frac_samples"] + +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', "smote", eval_type, "catboost", "5"], check=True) \ No newline at end of file diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/convert_synth_to_csv.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/convert_synth_to_csv.py new file mode 100644 index 0000000000000000000000000000000000000000..be1bb6180758714a938e9c5c73a51029523e20f0 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/convert_synth_to_csv.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +""" +Convert generated synthetic data from npy files to CSV format. +""" +import os +import sys +import numpy as np +import pandas as pd +import argparse + +def convert_to_csv(parent_dir, output_path=None): + """ + Convert generated synthetic data to CSV. + + Args: + parent_dir: Directory containing X_num_train.npy, X_cat_train.npy, y_train.npy + output_path: Output CSV file path (default: parent_dir/synth_train.csv) + """ + parent_dir = os.path.abspath(parent_dir) + + # Load npy files + x_num_path = os.path.join(parent_dir, 'X_num_train.npy') + x_cat_path = os.path.join(parent_dir, 'X_cat_train.npy') + y_path = os.path.join(parent_dir, 'y_train.npy') + + data_parts = [] + column_names = [] + + # Load numerical features + if os.path.exists(x_num_path): + X_num = np.load(x_num_path, allow_pickle=True) + print(f"Loaded X_num: shape {X_num.shape}") + data_parts.append(X_num) + # Create column names for numerical features + for i in range(X_num.shape[1]): + column_names.append(f'num_{i}') + + # Load categorical features + if os.path.exists(x_cat_path): + X_cat = np.load(x_cat_path, allow_pickle=True) + print(f"Loaded X_cat: shape {X_cat.shape}") + data_parts.append(X_cat) + # Create column names for categorical features + for i in range(X_cat.shape[1]): + column_names.append(f'cat_{i}') + + # Load target + if os.path.exists(y_path): + y = np.load(y_path, allow_pickle=True) + print(f"Loaded y: shape {y.shape}") + # Reshape if needed + if y.ndim == 1: + y = y.reshape(-1, 1) + data_parts.append(y) + column_names.append('y') + + if not data_parts: + raise ValueError(f"No data files found in {parent_dir}") + + # Concatenate all parts + data = np.hstack(data_parts) + print(f"Combined data shape: {data.shape}") + print(f"Number of columns: {len(column_names)}") + + # Create DataFrame + df = pd.DataFrame(data, columns=column_names) + + # Determine output path + if output_path is None: + output_path = os.path.join(parent_dir, 'synth_train.csv') + + # Save to CSV + df.to_csv(output_path, index=False) + print(f"[OK] Saved synthetic data to: {output_path}") + print(f"[OK] Total samples: {len(df)}, Total columns: {len(df.columns)}") + + # Print summary statistics + print("\n=== Data Summary ===") + print(df.describe()) + + return output_path + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='Convert synthetic npy files to CSV') + parser.add_argument('parent_dir', type=str, help='Directory containing generated npy files') + parser.add_argument('--output', '-o', type=str, default=None, help='Output CSV file path (default: parent_dir/synth_train.csv)') + + args = parser.parse_args() + convert_to_csv(args.parent_dir, args.output) diff --git a/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/make_tabddpm_info.py b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/make_tabddpm_info.py new file mode 100644 index 0000000000000000000000000000000000000000..30acf64d04521bfa8fc1810c893395eed5bd57a4 --- /dev/null +++ b/syntheticSuccess/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/tools/make_tabddpm_info.py @@ -0,0 +1,97 @@ +import os, json +import numpy as np + +def load(path): + return np.load(path, allow_pickle=True) + +def main(data_dir: str): + # required files + req = [ + "X_num_train.npy","X_num_val.npy","X_num_test.npy", + "X_cat_train.npy","X_cat_val.npy","X_cat_test.npy", + "y_train.npy","y_val.npy","y_test.npy" + ] + for f in req: + p = os.path.join(data_dir, f) + if not os.path.exists(p): + raise FileNotFoundError(p) + + Xn_tr = load(os.path.join(data_dir,"X_num_train.npy")) + Xc_tr = load(os.path.join(data_dir,"X_cat_train.npy")) + y_tr = load(os.path.join(data_dir,"y_train.npy")) + + # basic dims + n_num = 0 if Xn_tr.ndim < 2 else int(Xn_tr.shape[1]) + n_cat = 0 if Xc_tr.ndim < 2 else int(Xc_tr.shape[1]) + + # infer task / y info + y_flat = y_tr.reshape(-1) + uniq = np.unique(y_flat) + # if y is integer and has few unique values, could be classification + is_int = np.issubdtype(y_flat.dtype, np.integer) + num_classes = int(len(uniq)) if is_int else 0 + + # determine task_type + if is_int and num_classes == 2: + task_type = "binclass" + elif is_int and num_classes > 2 and num_classes <= 100: + task_type = "multiclass" + else: + task_type = "regression" + + # cat sizes (per categorical column) + cat_sizes = [] + if n_cat > 0: + # compute max+1 per column (assume categories encoded 0..K-1) + for j in range(n_cat): + col = Xc_tr[:, j].reshape(-1) + if col.size == 0: + cat_sizes.append(0) + else: + mx = int(np.max(col)) + cat_sizes.append(mx + 1) + + # numeric stats (optional but useful) + num_stats = {} + if n_num > 0: + # mean/std/min/max over train numeric + num_stats = { + "mean": np.mean(Xn_tr, axis=0).tolist(), + "std": (np.std(Xn_tr, axis=0) + 1e-12).tolist(), + "min": np.min(Xn_tr, axis=0).tolist(), + "max": np.max(Xn_tr, axis=0).tolist(), + } + + # This repo expects info.json. Keep fields simple & robust. + info = { + "task_type": task_type, + "n_num_features": n_num, + "n_cat_features": n_cat, + "cat_sizes": cat_sizes, + "y_dtype": str(y_flat.dtype), + "y_unique_count": int(len(uniq)), + "y_unique_head": uniq[:20].tolist(), + # heuristics: user can override in config.toml + "is_classification_like": bool(is_int and len(uniq) <= 100), + "num_classes_like": num_classes, + } + + # write files + with open(os.path.join(data_dir, "info.json"), "w", encoding="utf-8") as f: + json.dump(info, f, ensure_ascii=False, indent=2) + + # some codepaths may look for these (harmless if unused) + with open(os.path.join(data_dir, "cat_sizes.json"), "w", encoding="utf-8") as f: + json.dump({"cat_sizes": cat_sizes}, f, ensure_ascii=False, indent=2) + + with open(os.path.join(data_dir, "num_stats.json"), "w", encoding="utf-8") as f: + json.dump(num_stats, f, ensure_ascii=False, indent=2) + + print("[OK] wrote:", os.path.join(data_dir,"info.json")) + print("[OK] n_num =", n_num, "n_cat =", n_cat, "cat_sizes =", cat_sizes) + print("[OK] y unique count =", len(uniq), "head =", uniq[:20]) + +if __name__ == "__main__": + data_dir = "data/Tab-Cate-1" + main(data_dir) +