Resume SynthData0523 main/c6 batch 6
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+24
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_transformer.pyAdded+217
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/demo.pyAdded+10
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/__init__.pyAdded+16
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/base.pyAdded+105
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/ctgan.pyAdded+482
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/tvae.pyAdded+218
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.cfgAdded+59
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.pyAdded+119
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tasks.pyAdded+121
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_ctgan.pyAdded+275
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_tvae.pyAdded+131
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/test_data_transformer.pyAdded+42
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/__init__.pyAdded+1
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/__init__.pyAdded+1
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_base.pyAdded+111
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_ctgan.pyAdded+343
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_tvae.pyAdded+123
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/test_data_transformer.pyAdded+473
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tox.iniAdded+19
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/pipeline_tvae.pyAdded+80
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/train_sample_tvae.pyAdded+117
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/tune_tvae.pyAdded+153
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/LICENSE.mdAdded+21
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/README.mdAdded+99
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/_compat_run.pyAdded+6
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/agg_results.ipynbAdded+315
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/data.tarAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_train.npyAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_unnorm.npyAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_train.npyAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_unnorm.npyAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/config.tomlAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/info.jsonAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/loss.csvAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model.ptAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model_ema.ptAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/synth_train.csvAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/y_train.npyAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/config.tomlAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/config.tomlAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_catboost.jsonAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_simple.jsonAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/info.jsonAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/config.tomlAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_catboost.jsonAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_mlp.jsonAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple.jsonAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_ada.jsonAdded+3
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_lr.jsonAdded+3
4774 unmodified lines4775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014774 unmodified linesSynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/train_20260420_063042.log filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/columns.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/data.tar filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_train.npy filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_unnorm.npy filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_train.npy filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_unnorm.npy filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/config.toml filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/info.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/loss.csv filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model.pt filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model_ema.pt filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/synth_train.csv filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/y_train.npy filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/config.toml filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/config.toml filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_catboost.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_simple.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/info.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/config.toml filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_catboost.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_mlp.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_ada.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_lr.json filter=lfs diff=lfs merge=lfs -textSynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/importance.json filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217"""DataTransformer module."""
from collections import namedtuple
import numpy as npimport pandas as pdfrom 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) }12345678910"""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')12345678910111213141516"""Synthesizers module."""
from .ctgan import CTGANSynthesizerfrom .tvae import TVAESynthesizer
__all__ = ( 'CTGANSynthesizer', 'TVAESynthesizer')
def get_all_synthesizers(): return { name: globals()[name] for name in __all__ }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105"""BaseSynthesizer module."""
import contextlib
import numpy as npimport torch
@contextlib.contextmanagerdef 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`)')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482"""CTGANSynthesizer module."""
import warnings
import numpy as npimport pandas as pdimport torchfrom packaging import versionfrom torch import optimfrom torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, functional
from ..data_sampler import DataSamplerfrom ..data_transformer import DataTransformerfrom .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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218"""TVAESynthesizer module."""
import numpy as npimport torchfrom torch.nn import Linear, Module, Parameter, ReLU, Sequentialfrom torch.nn.functional import cross_entropyfrom torch.optim import Adamfrom torch.utils.data import DataLoader, TensorDataset
from ..data_transformer import DataTransformerfrom .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)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859[bumpversion]current_version = 0.5.2.dev0commit = Truetag = Trueparse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\.(?P<release>[a-z]+)(?P<candidate>\d+))?serialize = {major}.{minor}.{patch}.{release}{candidate} {major}.{minor}.{patch}
[bumpversion:part:release]optional_value = releasefirst_value = devvalues = 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 = googlemax-line-length = 99exclude = docs, .tox, .git, __pycache__, .ipynb_checkpointsextend-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 allowedper-file-ignores = ctgan/data.py:T001
[isort]include_trailing_comment = Trueline_length = 99lines_between_types = 0multi_line_output = 4not_skip = __init__.pyuse_parentheses = True
[aliases]test = pytest
[tool:pytest]collect_ignore = ['setup.py']
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119#!/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,)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import globimport operatorimport osimport reimport platformimport shutilimport statfrom pathlib import Path
from invoke import task
COMPARISONS = { '>=': operator.ge, '>': operator.gt, '<': operator.lt, '<=': operator.le}
@taskdef check_dependencies(c): c.run('python -m pip check')
@taskdef unit(c): c.run('python -m pytest ./tests/unit --cov=ctgan --cov-report=xml')
@taskdef integration(c): c.run('python -m pytest ./tests/integration --reruns 3')
@taskdef 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
@taskdef 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)}')
@taskdef minimum(c): install_minimum(c) check_dependencies(c) unit(c) integration(c)
@taskdef 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)
@taskdef rmdir(c, path): try: shutil.rmtree(path, onerror=remove_readonly) except PermissionError: pass123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275#!/usr/bin/env python# -*- coding: utf-8 -*-
"""Integration tests for ctgan.
These tests only ensure that the software does not crash and thatthe API works as expected in terms of input and output data formats,but correctness of the data values and the internal behavior of themodel are not checked."""
import tempfile as tf
import numpy as npimport pandas as pdimport 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 futuredef 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."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131#!/usr/bin/env python# -*- coding: utf-8 -*-
"""Integration tests for tvae.
These tests only ensure that the software does not crash and thatthe API works as expected in terms of input and output data formats,but correctness of the data values and the internal behavior of themodel are not checked."""
import numpy as npimport pandas as pdfrom 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)123456789101112131415161718192021222324252627282930313233343536373839404142"""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."""1"""Unit testing module."""1"""CTGANSynthesizer testing module."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
"""BaseSynthesizer unit testing module."""
from unittest.mock import MagicMock, call, patch
import numpy as npimport 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 None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343"""CTGANSynthesizer unit testing module."""
from unittest import TestCasefrom unittest.mock import Mock
import pandas as pdimport pytestimport torch
from ctgan.data_transformer import SpanInfofrom 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). """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123"""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). """123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473"""Data transformer unit testing module."""
from unittest import TestCasefrom unittest.mock import Mock, patch
import numpy as npimport 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 encoding12345678910111213141516171819[tox]envlist = py38-lint, py3{6,7,8,9}-{unit,integration,readme}
[testenv]skipsdist = falseskip_install = falsedeps = invoke readme: rundocextras = lint: dev unit: test integration: testcommands = lint: invoke lint unit: invoke unit integration: invoke integration readme: invoke readme invoke rmdir --path {envdir}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import tomliimport shutilimport osimport argparsefrom train_sample_tvae import train_tvae, sample_tvaefrom scripts.eval_catboost import train_catboostimport zeroimport lib
def load_config(path) : with open(path, 'rb') as f: return tomli.load(f) def save_file(parent_dir, config_path): try: dst = os.path.join(parent_dir) os.makedirs(os.path.dirname(dst), exist_ok=True) shutil.copyfile(os.path.abspath(config_path), dst) except shutil.SameFileError: pass
def main(): parser = argparse.ArgumentParser() parser.add_argument('--config', metavar='FILE') parser.add_argument('--train', action='store_true', default=False) parser.add_argument('--sample', action='store_true', default=False) parser.add_argument('--eval', action='store_true', default=False) parser.add_argument('--change_val', action='store_true', default=False)
args = parser.parse_args() raw_config = lib.load_config(args.config) timer = zero.Timer() timer.run() save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config) ctabgan = None if args.train: ctabgan = train_tvae( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], train_params=raw_config['train_params'], change_val=args.change_val, device=raw_config['device'] ) if args.sample: sample_tvae( synthesizer=ctabgan, parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], num_samples=raw_config['sample']['num_samples'], train_params=raw_config['train_params'], change_val=args.change_val, seed=raw_config['sample']['seed'], device=raw_config['device'] )
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json')) if args.eval: if raw_config['eval']['type']['eval_model'] == 'catboost': train_catboost( parent_dir=raw_config['parent_dir'], real_data_path=raw_config['real_data_path'], eval_type=raw_config['eval']['type']['eval_type'], T_dict=raw_config['eval']['T'], seed=raw_config['seed'], change_val=args.change_val ) # elif raw_config['eval']['type']['eval_model'] == 'mlp': # train_mlp( # parent_dir=raw_config['parent_dir'], # real_data_path=raw_config['real_data_path'], # eval_type=raw_config['eval']['type']['eval_type'], # T_dict=raw_config['eval']['T'], # seed=raw_config['seed'], # change_val=args.change_val # )
print(f'Elapsed time: {str(timer)}')
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import libimport osimport numpy as npimport argparsefrom CTGAN.ctgan import TVAESynthesizerfrom pathlib import Pathimport torchimport pickleimport warningsfrom sklearn.exceptions import ConvergenceWarning
warnings.filterwarnings("ignore", category=ConvergenceWarning)
def train_tvae( parent_dir, real_data_path, train_params = {"batch_size": 512}, change_val=False, device = "cpu"): real_data_path = Path(real_data_path) parent_dir = Path(parent_dir) device = torch.device(device)
if change_val: X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) else: X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
X.columns = [str(_) for _ in X.columns] cat_features = list(map(str, range(X_num_train.shape[1], X_num_train.shape[1]+X_cat_train.shape[1]))) if X_cat_train is not None else [] if lib.load_json(real_data_path / "info.json")["task_type"] != "regression": cat_features += ["y"]
train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
print(train_params) synthesizer = TVAESynthesizer( **train_params, device=device ) synthesizer.fit(X, cat_features)
# save_ctabgan(synthesizer, parent_dir) with open(parent_dir / "tvae.obj", "wb") as f: pickle.dump(synthesizer, f)
return synthesizer
def sample_tvae( synthesizer, parent_dir, real_data_path, num_samples, train_params = {"batch_size": 512}, change_val=False, device="cpu", seed=0): real_data_path = Path(real_data_path) parent_dir = Path(parent_dir) device = torch.device(device)
if change_val: X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path) else: X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train') X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
X.columns = [str(_) for _ in X.columns]
cat_features = list(map(str, range(X_num_train.shape[1], X_num_train.shape[1]+X_cat_train.shape[1]))) if X_cat_train is not None else [] if lib.load_json(real_data_path / "info.json")["task_type"] != "regression": cat_features += ["y"]
with open(parent_dir / "tvae.obj", 'rb') as f: synthesizer = pickle.load(f) synthesizer.decoder = synthesizer.decoder.to(device)
gen_data = synthesizer.sample(num_samples, seed)
y = gen_data['y'].values if len(np.unique(y)) == 1: y[0] = 0 y[1] = 1
X_cat = gen_data[cat_features].drop('y', axis=1, errors="ignore").values if len(cat_features) else None X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
if X_num_train is not None: np.save(parent_dir / 'X_num_train', X_num.astype(float)) if X_cat_train is not None: np.save(parent_dir / 'X_cat_train', X_cat.astype(str)) y = y.astype(float) if lib.load_json(real_data_path / "info.json")["task_type"] != "regression": y = y.astype(int) np.save(parent_dir / 'y_train', y) # only clf !!!
def main(): parser = argparse.ArgumentParser() parser.add_argument('real_data_path', type=str) parser.add_argument('parent_dir', type=str) parser.add_argument('train_size', type=int) args = parser.parse_args()
ctabgan = train_tvae(args.parent_dir, args.real_data_path, change_val=True) sample_tvae(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
if __name__ == '__main__': main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153from multiprocessing.sharedctypes import RawValueimport tempfileimport subprocessimport libimport osimport optunaimport argparsefrom pathlib import Pathfrom train_sample_tvae import train_tvae, sample_tvaefrom scripts.eval_catboost import train_catboost
parser = argparse.ArgumentParser()parser.add_argument('data_path', type=str)parser.add_argument('train_size', type=int)parser.add_argument('eval_type', type=str)parser.add_argument('device', type=str)
args = parser.parse_args()real_data_path = args.data_patheval_type = args.eval_typetrain_size = args.train_sizedevice = args.deviceassert eval_type in ('merged', 'synthetic')
def objective(trial): lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
def suggest_dim(name): t = trial.suggest_int(name, d_min, d_max) return 2 ** t # construct model min_n_layers, max_n_layers, d_min, d_max = 1, 3, 6, 9 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 ####
steps = trial.suggest_categorical('steps', [5000, 20000, 30000]) # steps = trial.suggest_categorical('steps', [1000]) batch_size = trial.suggest_categorical('batch_size', [256, 4096])
num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3))) embedding_dim = 2 ** trial.suggest_int('embedding_dim', 6, 10) loss_factor = trial.suggest_loguniform('loss_factor', 0.001, 10)
train_params = { "lr": lr, "epochs": steps, "embedding_dim": embedding_dim, "batch_size": batch_size, "loss_factor": loss_factor, "compress_dims": d_layers, "decompress_dims": d_layers }
trial.set_user_attr("train_params", train_params) trial.set_user_attr("num_samples", num_samples)
score = 0.0 with tempfile.TemporaryDirectory() as dir_: dir_ = Path(dir_) ctabgan = train_tvae( parent_dir=dir_, real_data_path=real_data_path, train_params=train_params, change_val=True, device=device )
for sample_seed in range(5): sample_tvae( ctabgan, parent_dir=dir_, real_data_path=real_data_path, num_samples=num_samples, train_params=train_params, change_val=True, seed=sample_seed, device=device )
T_dict = { "seed": 0, "normalization": None, "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": None, "y_policy": "default" } metrics = train_catboost( parent_dir=dir_, real_data_path=real_data_path, eval_type=eval_type, T_dict=T_dict, change_val=True, seed = 0 )
score += metrics.get_val_score() return score / 5
study = optuna.create_study( direction='maximize', sampler=optuna.samplers.TPESampler(seed=0),)
study.optimize(objective, n_trials=50, show_progress_bar=True)
os.makedirs(f"exp/{Path(real_data_path).name}/tvae/", exist_ok=True)config = { "parent_dir": f"exp/{Path(real_data_path).name}/tvae/", "real_data_path": real_data_path, "seed": 0, "device": args.device, "train_params": study.best_trial.user_attrs["train_params"], "sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]}, "eval": { "type": {"eval_model": "catboost", "eval_type": eval_type}, "T": { "seed": 0, "normalization": None, "num_nan_policy": None, "cat_nan_policy": None, "cat_min_frequency": None, "cat_encoding": None, "y_policy": "default" }, }}
train_tvae( parent_dir=f"exp/{Path(real_data_path).name}/tvae/", real_data_path=real_data_path, train_params=study.best_trial.user_attrs["train_params"], change_val=False, device=device)
lib.dump_config(config, config["parent_dir"]+"config.toml")
subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}', '10', "tvae", eval_type, "catboost", "5"], check=True)123456789101112131415161718192021MIT License
Copyright (c) 2022 Akim Kotelnikov
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899# TabDDPM: Modelling Tabular Data with Diffusion ModelsThis is the official code for our paper "TabDDPM: Modelling Tabular Data with Diffusion Models" ([paper](https://arxiv.org/abs/2209.15421))
<!-- ## ResultsYou can view all the results and build your own tables with this [notebook](notebooks/Reports.ipynb). -->
## Setup the environment1. Install [conda](https://docs.conda.io/en/latest/miniconda.html) (just to manage the env).2. Run the following commands ```bash export REPO_DIR=/path/to/the/code cd $REPO_DIR
conda create -n tddpm python=3.9.7 conda activate tddpm
pip install torch==1.10.1+cu111 -f https://download.pytorch.org/whl/torch_stable.html pip install -r requirements.txt
# if the following commands do not succeed, update conda conda env config vars set PYTHONPATH=${PYTHONPATH}:${REPO_DIR} conda env config vars set PROJECT_DIR=${REPO_DIR}
conda deactivate conda activate tddpm ```
## Running the experiments
Here we describe the neccesary info for reproducing the experimental results. Use `agg_results.ipynb` to print results for all dataset and all methods.
### Datasets
We upload the datasets used in the paper with our train/val/test splits (link below). We do not impose additional restrictions to the original dataset licenses, the sources of the data are listed in the paper appendix.
You could load the datasets with the following commands:
``` bashconda activate tddpmcd $PROJECT_DIRwget "https://www.dropbox.com/s/rpckvcs3vx7j605/data.tar?dl=0" -O data.tartar -xvf data.tar```
### File structure`tab-ddpm/` -- implementation of the proposed method `tuned_models/` -- tuned hyperparameters of evaluation model (CatBoost or MLP)
All main scripts are in `scripts/` folder:
- `scripts/pipeline.py` are used to train, sample and eval TabDDPM using a given config - `scripts/tune_ddpm.py` -- tune hyperparameters of TabDDPM- `scripts/eval_[catboost|mlp|simple].py` -- evaluate synthetic data using a tuned evaluation model or simple models- `scripts/eval_seeds.py` -- eval using multiple sampling and multuple eval seeds- `scripts/eval_seeds_simple.py` -- eval using multiple sampling and multuple eval seeds (for simple models)- `scripts/tune_evaluation_model.py` -- tune hyperparameters of eval model (CatBoost or MLP)- `scripts/resample_privacy.py` -- privacy calculation
Experiments folder (`exp/`):- All results and synthetic data are stored in `exp/[ds_name]/[exp_name]/` folder- `exp/[ds_name]/config.toml` is a base config for tuning TabDDPM- `exp/[ds_name]/eval_[catboost|mlp].json` stores results of evaluation (`scripts/eval_seeds.py`)
To understand the structure of `config.toml` file, read `CONFIG_DESCRIPTION.md`.
Baselines:- `smote/`- `CTGAN/` -- TVAE [official repo](https://github.com/sdv-dev/CTGAN)- `CTAB-GAN/` -- [official repo](https://github.com/Team-TUD/CTAB-GAN)- `CTAB-GAN-Plus/` -- [official repo](https://github.com/Team-TUD/CTAB-GAN-Plus)
### Examples
<ins>Run TabDDPM tuning.</ins>
Template and example (`--eval_seeds` is optional): ```bashpython scripts/tune_ddpm.py [ds_name] [train_size] synthetic [catboost|mlp] [exp_name] --eval_seedspython scripts/tune_ddpm.py churn2 6500 synthetic catboost ddpm_tune --eval_seeds```
<ins>Run TabDDPM pipeline.</ins>
Template and example (`--train`, `--sample`, `--eval` are optional): ```bashpython scripts/pipeline.py --config [path_to_your_config] --train --sample --evalpython scripts/pipeline.py --config exp/churn2/ddpm_cb_best/config.toml --train --sample```It takes approximately 7min to run the script above (NVIDIA GeForce RTX 2080 Ti).
<ins>Run evaluation over seeds</ins> Before running evaluation, you have to train the model with the given hyperparameters (the example above).
Template and example: ```bashpython scripts/eval_seeds.py --config [path_to_your_config] [n_eval_seeds] [ddpm|smote|ctabgan|ctabgan-plus|tvae] synthetic [catboost|mlp] [n_sample_seeds]python scripts/eval_seeds.py --config exp/churn2/ddpm_cb_best/config.toml 10 ddpm synthetic catboost 5```123456import collections, collections.abcfor _a in ('Sequence','MutableSequence','MutableMapping','Mapping','MutableSet','Set','Callable','Iterable','Iterator'): if not hasattr(collections, _a): setattr(collections, _a, getattr(collections.abc, _a, None))import sys, runpysys.argv = sys.argv[1:]runpy.run_path(sys.argv[0], run_name='__main__')123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Aggregating results to DataFrame" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import os\n", "import lib\n", "import numpy as np\n", "import pandas as pd\n", "\n", "DATASETS = [\n", " \"abalone\",\n", " \"adult\",\n", " \"buddy\",\n", " \"california\",\n", " \"cardio\",\n", " \"churn2\",\n", " \"default\",\n", " \"diabetes\",\n", " \"fb-comments\",\n", " \"gesture\",\n", " \"higgs-small\",\n", " \"house\",\n", " \"insurance\",\n", " \"king\",\n", " \"miniboone\",\n", " \"wilt\"\n", "]\n", "\n", "_REGRESSION = [\n", " \"abalone\",\n", " \"california\",\n", " \"fb-comments\",\n", " \"house\",\n", " \"insurance\",\n", " \"king\",\n", "]\n", "\n", "\n", "method2exp = {\n", " \"real\": \"exp/{}/ddpm_cb_best/\",\n", " \"tab-ddpm\": \"exp/{}/ddpm_cb_best/\",\n", " \"smote\": \"exp/{}/smote/\",\n", " \"ctabgan+\": \"exp/{}/ctabgan-plus/\",\n", " \"ctabgan\": \"exp/{}/ctabgan/\",\n", " \"tvae\": \"exp/{}/tvae/\"\n", "}\n", "\n", "eval_file = \"eval_catboost.json\"\n", "show_std = False\n", "df = pd.DataFrame(columns=[\"method\"] + [_[:3].upper() for _ in DATASETS])\n", "\n", "for algo in method2exp: \n", " algo_res = []\n", " for ds in DATASETS:\n", " if not os.path.exists(os.path.join(method2exp[algo].format(ds), eval_file)):\n", " algo_res.append(\"--\")\n", " continue\n", " metric = \"r2\" if ds in _REGRESSION else \"f1\"\n", " res_dict = lib.load_json(os.path.join(method2exp[algo].format(ds), eval_file))\n", "\n", " if algo == \"real\":\n", " res = f'{res_dict[\"real\"][\"test\"][metric + \"-mean\"]:.4f}' \n", " if show_std: res += f'+-{res_dict[\"real\"][\"test\"][metric + \"-std\"]:.4f}'\n", " else:\n", " res = f'{res_dict[\"synthetic\"][\"test\"][metric + \"-mean\"]:.4f}'\n", " if show_std: res += f'+-{res_dict[\"synthetic\"][\"test\"][metric + \"-std\"]:.4f}'\n", "\n", " algo_res.append(res)\n", " df.loc[len(df)] = [algo] + algo_res" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "<div>\n", "<style scoped>\n", " .dataframe tbody tr th:only-of-type {\n", " vertical-align: middle;\n", " }\n", "\n", " .dataframe tbody tr th {\n", " vertical-align: top;\n", " }\n", "\n", " .dataframe thead th {\n", " text-align: right;\n", " }\n", "</style>\n", "<table border=\"1\" class=\"dataframe\">\n", " <thead>\n", " <tr style=\"text-align: right;\">\n", " <th></th>\n", " <th>method</th>\n", " <th>ABA</th>\n", " <th>ADU</th>\n", " <th>BUD</th>\n", " <th>CAL</th>\n", " <th>CAR</th>\n", " <th>CHU</th>\n", " <th>DEF</th>\n", " <th>DIA</th>\n", " <th>FB-</th>\n", " <th>GES</th>\n", " <th>HIG</th>\n", " <th>HOU</th>\n", " <th>INS</th>\n", " <th>KIN</th>\n", " <th>MIN</th>\n", " <th>WIL</th>\n", " </tr>\n", " </thead>\n", " <tbody>\n", " <tr>\n", " <th>0</th>\n", " <td>real</td>\n", " <td>0.5562</td>\n", " <td>0.8152</td>\n", " <td>0.9063</td>\n", " <td>0.8568</td>\n", " <td>0.7379</td>\n", " <td>0.7403</td>\n", " <td>0.6880</td>\n", " <td>0.7849</td>\n", " <td>0.8371</td>\n", " <td>0.6365</td>\n", " <td>0.7238</td>\n", " <td>0.6616</td>\n", " <td>0.8137</td>\n", " <td>0.9070</td>\n", " <td>0.9342</td>\n", " <td>0.8982</td>\n", " </tr>\n", " <tr>\n", " <th>1</th>\n", " <td>tab-ddpm</td>\n", " <td>0.5499</td>\n", " <td>0.7951</td>\n", " <td>0.9057</td>\n", " <td>0.8362</td>\n", " <td>0.7374</td>\n", " <td>0.7548</td>\n", " <td>0.6910</td>\n", " <td>0.7398</td>\n", " <td>0.7128</td>\n", " <td>0.5967</td>\n", " <td>0.7218</td>\n", " <td>0.6766</td>\n", " <td>0.8092</td>\n", " <td>0.8331</td>\n", " <td>0.9362</td>\n", " <td>0.9045</td>\n", " </tr>\n", " <tr>\n", " <th>2</th>\n", " <td>smote</td>\n", " <td>0.5486</td>\n", " <td>0.7912</td>\n", " <td>0.8906</td>\n", " <td>0.8397</td>\n", " <td>0.7323</td>\n", " <td>0.7432</td>\n", " <td>0.6930</td>\n", " <td>0.6835</td>\n", " <td>0.8035</td>\n", " <td>0.6579</td>\n", " <td>0.7219</td>\n", " <td>0.6625</td>\n", " <td>0.8119</td>\n", " <td>0.8416</td>\n", " <td>0.9323</td>\n", " <td>0.9127</td>\n", " </tr>\n", " <tr>\n", " <th>3</th>\n", " <td>ctabgan+</td>\n", " <td>0.4672</td>\n", " <td>0.7724</td>\n", " <td>0.8844</td>\n", " <td>0.5247</td>\n", " <td>0.7327</td>\n", " <td>0.7024</td>\n", " <td>0.6865</td>\n", " <td>0.7339</td>\n", " <td>0.5088</td>\n", " <td>0.4055</td>\n", " <td>0.6639</td>\n", " <td>0.5040</td>\n", " <td>0.7966</td>\n", " <td>0.4438</td>\n", " <td>0.8920</td>\n", " <td>0.7983</td>\n", " </tr>\n", " <tr>\n", " <th>4</th>\n", " <td>ctabgan</td>\n", " <td>--</td>\n", " <td>0.7831</td>\n", " <td>0.8552</td>\n", " <td>--</td>\n", " <td>0.7171</td>\n", " <td>0.6875</td>\n", " <td>0.6437</td>\n", " <td>0.7310</td>\n", " <td>--</td>\n", " <td>0.3922</td>\n", " <td>0.5748</td>\n", " <td>--</td>\n", " <td>--</td>\n", " <td>--</td>\n", " <td>0.8892</td>\n", " <td>0.9060</td>\n", " </tr>\n", " <tr>\n", " <th>5</th>\n", " <td>tvae</td>\n", " <td>0.4328</td>\n", " <td>0.7810</td>\n", " <td>0.8638</td>\n", " <td>0.7518</td>\n", " <td>0.7174</td>\n", " <td>0.7317</td>\n", " <td>0.6564</td>\n", " <td>0.7136</td>\n", " <td>0.6853</td>\n", " <td>0.4340</td>\n", " <td>0.6378</td>\n", " <td>0.4926</td>\n", " <td>0.7842</td>\n", " <td>0.8238</td>\n", " <td>0.9125</td>\n", " <td>0.5006</td>\n", " </tr>\n", " </tbody>\n", "</table>\n", "</div>" ], "text/plain": [ " method ABA ADU BUD CAL CAR CHU DEF DIA \\\n", "0 real 0.5562 0.8152 0.9063 0.8568 0.7379 0.7403 0.6880 0.7849 \n", "1 tab-ddpm 0.5499 0.7951 0.9057 0.8362 0.7374 0.7548 0.6910 0.7398 \n", "2 smote 0.5486 0.7912 0.8906 0.8397 0.7323 0.7432 0.6930 0.6835 \n", "3 ctabgan+ 0.4672 0.7724 0.8844 0.5247 0.7327 0.7024 0.6865 0.7339 \n", "4 ctabgan -- 0.7831 0.8552 -- 0.7171 0.6875 0.6437 0.7310 \n", "5 tvae 0.4328 0.7810 0.8638 0.7518 0.7174 0.7317 0.6564 0.7136 \n", "\n", " FB- GES HIG HOU INS KIN MIN WIL \n", "0 0.8371 0.6365 0.7238 0.6616 0.8137 0.9070 0.9342 0.8982 \n", "1 0.7128 0.5967 0.7218 0.6766 0.8092 0.8331 0.9362 0.9045 \n", "2 0.8035 0.6579 0.7219 0.6625 0.8119 0.8416 0.9323 0.9127 \n", "3 0.5088 0.4055 0.6639 0.5040 0.7966 0.4438 0.8920 0.7983 \n", "4 -- 0.3922 0.5748 -- -- -- 0.8892 0.9060 \n", "5 0.6853 0.4340 0.6378 0.4926 0.7842 0.8238 0.9125 0.5006 " ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "df" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3.9.7 ('base')", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.7" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "a06af253165e97d0c1e75e8bf6d3252013856f30b8177e11b02d3fa36c37333d" } } }, "nbformat": 4, "nbformat_minor": 2}123version https://git-lfs.github.com/spec/v1oid sha256:d9530d0aaff4791e7dfd44697594bfc45819ecb571a80d3bd4af60217fb61ee8size 544923648123version https://git-lfs.github.com/spec/v1oid sha256:8d2be5d993d10dfbfe8997fc73ada380331396c1265d4b66464e978b8a734e87size 166049123version https://git-lfs.github.com/spec/v1oid sha256:7ada8f67106f3f6e8dad2dc55d8857edf2a3256da2234278f04d4e5e478b1e77size 662528123version https://git-lfs.github.com/spec/v1oid sha256:9c6c7d846995e547e63c454379e094bc793da6b8a3fbdaa7e360236bcd992bc5size 2208128123version https://git-lfs.github.com/spec/v1oid sha256:2ccfb8b86bb13792e6150ef8dfe40a8a34f5f94e5fa7df9933cb3cd94773c05dsize 2428928123version https://git-lfs.github.com/spec/v1oid sha256:db1cf55340ae5364a05a1c840094ca47fff79dd584850c9ee751b2a097f7b075size 922123version https://git-lfs.github.com/spec/v1oid sha256:3dcb118d387bd15e6a79e571ad80c7a4fe900858c45ccea903e70a9550c86203size 256123version https://git-lfs.github.com/spec/v1oid sha256:426ab9f8eb46c9344fff5853a5e7543939beb14314f8f3f10e079a216dd108efsize 610123version https://git-lfs.github.com/spec/v1oid sha256:d879e391140052f56e8b1896df4fd47bfa25aee889ec81f7a47cfdc7beea8accsize 1521051123version https://git-lfs.github.com/spec/v1oid sha256:ab7a9a3f8e65e549445f0ce927ad6849568a2f42061d0c9350128354ccd27efbsize 1521827123version https://git-lfs.github.com/spec/v1oid sha256:6120646eb9dc9d83006b8ec2565f020c1b7aec589229211b8bf1d5432a3f4e07size 1380080123version https://git-lfs.github.com/spec/v1oid sha256:283e1a42f3e03025d2241c3c39135ca9c64ba4b7baf2d9586ee25004b68cc936size 220928123version https://git-lfs.github.com/spec/v1oid sha256:fe8c63e9f9a09cd9ca89affd4bb5e4d1545d59cdb31f9f73fb486257bbfd447fsize 920123version https://git-lfs.github.com/spec/v1oid sha256:a6bd872ae66f715fffcc92f2c7c4cc2246980b4df0e02b93738a8c9b4f697af0size 539123version https://git-lfs.github.com/spec/v1oid sha256:42a3a2e2f22ebc24b66aaa3403869283f6576ce04e5fafa81fec15735d66aee3size 459123version https://git-lfs.github.com/spec/v1oid sha256:4d6478bba03b9309a26ef6e1247d95ce86668437fa08a6c5f15776ec9848a5e2size 2424123version https://git-lfs.github.com/spec/v1oid sha256:4b49fbcbcb81f577c2c56d703b327294a63a52fce9afa7b5fb98b20b61556c8csize 199123version https://git-lfs.github.com/spec/v1oid sha256:cc6aa7d00bb5078f766e5d73ea4e04bbe8437bac44636cfd80a36b9262df0a01size 920123version https://git-lfs.github.com/spec/v1oid sha256:7ef5506437037908e0c0d5f0bd0c5eb3c61747d9de491d345dc0e8e8be3845b8size 909123version https://git-lfs.github.com/spec/v1oid sha256:fe4a3e4e117924a65d2da76254394ba8aae00555e30bebae916e154a925f0e3esize 910123version https://git-lfs.github.com/spec/v1oid sha256:aaf9df7911d5911b85f1a805c48a1c6d0e978e287c10f9ef78365b08a14da806size 4809123version https://git-lfs.github.com/spec/v1oid sha256:0684462d69e5c1c8db2b1fad1ae7760be1849abcc5a623b5eaf07255b04a17f8size 454123version https://git-lfs.github.com/spec/v1oid sha256:ce2cdfb51f7d37053edfa2250af17d1adef47d3e0eb141926a6a74a613c6cbb2size 442.gitattributes+24
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_transformer.pyAdded+217
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/demo.pyAdded+10
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/__init__.pyAdded+16
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/base.pyAdded+105
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/ctgan.pyAdded+482
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/tvae.pyAdded+218
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.cfgAdded+59
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.pyAdded+119
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tasks.pyAdded+121
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_ctgan.pyAdded+275
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_tvae.pyAdded+131
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/test_data_transformer.pyAdded+42
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/__init__.pyAdded+1
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/__init__.pyAdded+1
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_base.pyAdded+111
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_ctgan.pyAdded+343
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_tvae.pyAdded+123
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/test_data_transformer.pyAdded+473
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tox.iniAdded+19
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/pipeline_tvae.pyAdded+80
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/train_sample_tvae.pyAdded+117
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/tune_tvae.pyAdded+153
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/LICENSE.mdAdded+21
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/README.mdAdded+99
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/_compat_run.pyAdded+6
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/agg_results.ipynbAdded+315
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/data.tarAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_train.npyAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_unnorm.npyAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_train.npyAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_unnorm.npyAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/config.tomlAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/info.jsonAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/loss.csvAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model.ptAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model_ema.ptAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/synth_train.csvAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/y_train.npyAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/config.tomlAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/config.tomlAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_catboost.jsonAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_simple.jsonAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/info.jsonAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/config.tomlAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_catboost.jsonAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_mlp.jsonAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple.jsonAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_ada.jsonAdded+3
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_lr.jsonAdded+3