Resume SynthData0523 main/c6 batch 6
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +24 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_transformer.py +217 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/demo.py +10 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/__init__.py +16 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/base.py +105 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/ctgan.py +482 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/tvae.py +218 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.cfg +59 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.py +119 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tasks.py +121 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_ctgan.py +275 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_tvae.py +131 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/test_data_transformer.py +42 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/__init__.py +1 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/__init__.py +1 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_base.py +111 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_ctgan.py +343 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_tvae.py +123 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/test_data_transformer.py +473 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tox.ini +19 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/pipeline_tvae.py +80 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/train_sample_tvae.py +117 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/tune_tvae.py +153 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/LICENSE.md +21 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/README.md +99 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/_compat_run.py +6 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/agg_results.ipynb +315 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/data.tar +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_train.npy +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_unnorm.npy +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_train.npy +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_unnorm.npy +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/config.toml +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/info.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/loss.csv +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model.pt +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model_ema.pt +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/synth_train.csv +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/y_train.npy +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/config.toml +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/config.toml +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_catboost.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_simple.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/info.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/config.toml +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_catboost.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_mlp.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_ada.json +3 -0
- SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_lr.json +3 -0
.gitattributes
CHANGED
|
@@ -4775,3 +4775,27 @@ SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/tabular_bundle/pipe
|
|
| 4775 |
SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/train_20260420_063042.log filter=lfs diff=lfs merge=lfs -text
|
| 4776 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/columns.json filter=lfs diff=lfs merge=lfs -text
|
| 4777 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4775 |
SynthData0523/main/c6/tabbyflow/tabbyflow-c6-20260420_063042/train_20260420_063042.log filter=lfs diff=lfs merge=lfs -text
|
| 4776 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN-Plus/columns.json filter=lfs diff=lfs merge=lfs -text
|
| 4777 |
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTAB-GAN/columns.json filter=lfs diff=lfs merge=lfs -text
|
| 4778 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/data.tar filter=lfs diff=lfs merge=lfs -text
|
| 4779 |
+
SynthData0523/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 -text
|
| 4780 |
+
SynthData0523/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 -text
|
| 4781 |
+
SynthData0523/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 -text
|
| 4782 |
+
SynthData0523/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 -text
|
| 4783 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/config.toml filter=lfs diff=lfs merge=lfs -text
|
| 4784 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/info.json filter=lfs diff=lfs merge=lfs -text
|
| 4785 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/loss.csv filter=lfs diff=lfs merge=lfs -text
|
| 4786 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model.pt filter=lfs diff=lfs merge=lfs -text
|
| 4787 |
+
SynthData0523/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 -text
|
| 4788 |
+
SynthData0523/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 -text
|
| 4789 |
+
SynthData0523/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 -text
|
| 4790 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/config.toml filter=lfs diff=lfs merge=lfs -text
|
| 4791 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/config.toml filter=lfs diff=lfs merge=lfs -text
|
| 4792 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_catboost.json filter=lfs diff=lfs merge=lfs -text
|
| 4793 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_simple.json filter=lfs diff=lfs merge=lfs -text
|
| 4794 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/info.json filter=lfs diff=lfs merge=lfs -text
|
| 4795 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/config.toml filter=lfs diff=lfs merge=lfs -text
|
| 4796 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_catboost.json filter=lfs diff=lfs merge=lfs -text
|
| 4797 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_mlp.json filter=lfs diff=lfs merge=lfs -text
|
| 4798 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple.json filter=lfs diff=lfs merge=lfs -text
|
| 4799 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_ada.json filter=lfs diff=lfs merge=lfs -text
|
| 4800 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_lr.json filter=lfs diff=lfs merge=lfs -text
|
| 4801 |
+
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/importance.json filter=lfs diff=lfs merge=lfs -text
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/data_transformer.py
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DataTransformer module."""
|
| 2 |
+
|
| 3 |
+
from collections import namedtuple
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from rdt.transformers import BayesGMMTransformer, OneHotEncodingTransformer
|
| 8 |
+
|
| 9 |
+
SpanInfo = namedtuple('SpanInfo', ['dim', 'activation_fn'])
|
| 10 |
+
ColumnTransformInfo = namedtuple(
|
| 11 |
+
'ColumnTransformInfo', [
|
| 12 |
+
'column_name', 'column_type', 'transform', 'output_info', 'output_dimensions'
|
| 13 |
+
]
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class DataTransformer(object):
|
| 18 |
+
"""Data Transformer.
|
| 19 |
+
|
| 20 |
+
Model continuous columns with a BayesianGMM and normalized to a scalar [0, 1] and a vector.
|
| 21 |
+
Discrete columns are encoded using a scikit-learn OneHotEncoder.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
def __init__(self, max_clusters=10, weight_threshold=0.005):
|
| 25 |
+
"""Create a data transformer.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
max_clusters (int):
|
| 29 |
+
Maximum number of Gaussian distributions in Bayesian GMM.
|
| 30 |
+
weight_threshold (float):
|
| 31 |
+
Weight threshold for a Gaussian distribution to be kept.
|
| 32 |
+
"""
|
| 33 |
+
self._max_clusters = max_clusters
|
| 34 |
+
self._weight_threshold = weight_threshold
|
| 35 |
+
|
| 36 |
+
def _fit_continuous(self, data):
|
| 37 |
+
"""Train Bayesian GMM for continuous columns.
|
| 38 |
+
|
| 39 |
+
Args:
|
| 40 |
+
data (pd.DataFrame):
|
| 41 |
+
A dataframe containing a column.
|
| 42 |
+
|
| 43 |
+
Returns:
|
| 44 |
+
namedtuple:
|
| 45 |
+
A ``ColumnTransformInfo`` object.
|
| 46 |
+
"""
|
| 47 |
+
column_name = data.columns[0]
|
| 48 |
+
gm = BayesGMMTransformer(max_clusters=min(len(data), 10))
|
| 49 |
+
gm.fit(data, [column_name])
|
| 50 |
+
num_components = sum(gm.valid_component_indicator)
|
| 51 |
+
|
| 52 |
+
return ColumnTransformInfo(
|
| 53 |
+
column_name=column_name, column_type='continuous', transform=gm,
|
| 54 |
+
output_info=[SpanInfo(1, 'tanh'), SpanInfo(num_components, 'softmax')],
|
| 55 |
+
output_dimensions=1 + num_components)
|
| 56 |
+
|
| 57 |
+
def _fit_discrete(self, data):
|
| 58 |
+
"""Fit one hot encoder for discrete column.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
data (pd.DataFrame):
|
| 62 |
+
A dataframe containing a column.
|
| 63 |
+
|
| 64 |
+
Returns:
|
| 65 |
+
namedtuple:
|
| 66 |
+
A ``ColumnTransformInfo`` object.
|
| 67 |
+
"""
|
| 68 |
+
column_name = data.columns[0]
|
| 69 |
+
ohe = OneHotEncodingTransformer()
|
| 70 |
+
ohe.fit(data, [column_name])
|
| 71 |
+
num_categories = len(ohe.dummies)
|
| 72 |
+
|
| 73 |
+
return ColumnTransformInfo(
|
| 74 |
+
column_name=column_name, column_type='discrete', transform=ohe,
|
| 75 |
+
output_info=[SpanInfo(num_categories, 'softmax')],
|
| 76 |
+
output_dimensions=num_categories)
|
| 77 |
+
|
| 78 |
+
def fit(self, raw_data, discrete_columns=()):
|
| 79 |
+
"""Fit the ``DataTransformer``.
|
| 80 |
+
|
| 81 |
+
Fits a ``BayesGMMTransformer`` for continuous columns and a
|
| 82 |
+
``OneHotEncodingTransformer`` for discrete columns.
|
| 83 |
+
|
| 84 |
+
This step also counts the #columns in matrix data and span information.
|
| 85 |
+
"""
|
| 86 |
+
self.output_info_list = []
|
| 87 |
+
self.output_dimensions = 0
|
| 88 |
+
self.dataframe = True
|
| 89 |
+
|
| 90 |
+
if not isinstance(raw_data, pd.DataFrame):
|
| 91 |
+
self.dataframe = False
|
| 92 |
+
# work around for RDT issue #328 Fitting with numerical column names fails
|
| 93 |
+
discrete_columns = [str(column) for column in discrete_columns]
|
| 94 |
+
column_names = [str(num) for num in range(raw_data.shape[1])]
|
| 95 |
+
raw_data = pd.DataFrame(raw_data, columns=column_names)
|
| 96 |
+
|
| 97 |
+
self._column_raw_dtypes = raw_data.infer_objects().dtypes
|
| 98 |
+
self._column_transform_info_list = []
|
| 99 |
+
for column_name in raw_data.columns:
|
| 100 |
+
if column_name in discrete_columns:
|
| 101 |
+
column_transform_info = self._fit_discrete(raw_data[[column_name]])
|
| 102 |
+
else:
|
| 103 |
+
column_transform_info = self._fit_continuous(raw_data[[column_name]])
|
| 104 |
+
|
| 105 |
+
self.output_info_list.append(column_transform_info.output_info)
|
| 106 |
+
self.output_dimensions += column_transform_info.output_dimensions
|
| 107 |
+
self._column_transform_info_list.append(column_transform_info)
|
| 108 |
+
|
| 109 |
+
def _transform_continuous(self, column_transform_info, data):
|
| 110 |
+
column_name = data.columns[0]
|
| 111 |
+
data.loc[:, column_name] = data[column_name].to_numpy().flatten()
|
| 112 |
+
gm = column_transform_info.transform
|
| 113 |
+
transformed = gm.transform(data, [column_name])
|
| 114 |
+
|
| 115 |
+
# Converts the transformed data to the appropriate output format.
|
| 116 |
+
# The first column (ending in '.normalized') stays the same,
|
| 117 |
+
# but the lable encoded column (ending in '.component') is one hot encoded.
|
| 118 |
+
output = np.zeros((len(transformed), column_transform_info.output_dimensions))
|
| 119 |
+
output[:, 0] = transformed[f'{column_name}.normalized'].to_numpy()
|
| 120 |
+
index = transformed[f'{column_name}.component'].to_numpy().astype(int)
|
| 121 |
+
output[np.arange(index.size), index + 1] = 1.0
|
| 122 |
+
|
| 123 |
+
return output
|
| 124 |
+
|
| 125 |
+
def _transform_discrete(self, column_transform_info, data):
|
| 126 |
+
ohe = column_transform_info.transform
|
| 127 |
+
return ohe.transform(data).to_numpy()
|
| 128 |
+
|
| 129 |
+
def transform(self, raw_data):
|
| 130 |
+
"""Take raw data and output a matrix data."""
|
| 131 |
+
if not isinstance(raw_data, pd.DataFrame):
|
| 132 |
+
column_names = [str(num) for num in range(raw_data.shape[1])]
|
| 133 |
+
raw_data = pd.DataFrame(raw_data, columns=column_names)
|
| 134 |
+
|
| 135 |
+
column_data_list = []
|
| 136 |
+
for column_transform_info in self._column_transform_info_list:
|
| 137 |
+
column_name = column_transform_info.column_name
|
| 138 |
+
data = raw_data[[column_name]]
|
| 139 |
+
if column_transform_info.column_type == 'continuous':
|
| 140 |
+
column_data_list.append(self._transform_continuous(column_transform_info, data))
|
| 141 |
+
else:
|
| 142 |
+
column_data_list.append(self._transform_discrete(column_transform_info, data))
|
| 143 |
+
|
| 144 |
+
return np.concatenate(column_data_list, axis=1).astype(float)
|
| 145 |
+
|
| 146 |
+
def _inverse_transform_continuous(self, column_transform_info, column_data, sigmas, st):
|
| 147 |
+
gm = column_transform_info.transform
|
| 148 |
+
data = pd.DataFrame(column_data[:, :2], columns=list(gm.get_output_types()))
|
| 149 |
+
data.iloc[:, 1] = np.argmax(column_data[:, 1:], axis=1)
|
| 150 |
+
if sigmas is not None:
|
| 151 |
+
selected_normalized_value = np.random.normal(data.iloc[:, 0], sigmas[st])
|
| 152 |
+
data.iloc[:, 0] = selected_normalized_value
|
| 153 |
+
|
| 154 |
+
return gm.reverse_transform(data, [column_transform_info.column_name])
|
| 155 |
+
|
| 156 |
+
def _inverse_transform_discrete(self, column_transform_info, column_data):
|
| 157 |
+
ohe = column_transform_info.transform
|
| 158 |
+
data = pd.DataFrame(column_data, columns=list(ohe.get_output_types()))
|
| 159 |
+
return ohe.reverse_transform(data)[column_transform_info.column_name]
|
| 160 |
+
|
| 161 |
+
def inverse_transform(self, data, sigmas=None):
|
| 162 |
+
"""Take matrix data and output raw data.
|
| 163 |
+
|
| 164 |
+
Output uses the same type as input to the transform function.
|
| 165 |
+
Either np array or pd dataframe.
|
| 166 |
+
"""
|
| 167 |
+
st = 0
|
| 168 |
+
recovered_column_data_list = []
|
| 169 |
+
column_names = []
|
| 170 |
+
for column_transform_info in self._column_transform_info_list:
|
| 171 |
+
dim = column_transform_info.output_dimensions
|
| 172 |
+
column_data = data[:, st:st + dim]
|
| 173 |
+
if column_transform_info.column_type == 'continuous':
|
| 174 |
+
recovered_column_data = self._inverse_transform_continuous(
|
| 175 |
+
column_transform_info, column_data, sigmas, st)
|
| 176 |
+
else:
|
| 177 |
+
recovered_column_data = self._inverse_transform_discrete(
|
| 178 |
+
column_transform_info, column_data)
|
| 179 |
+
|
| 180 |
+
recovered_column_data_list.append(recovered_column_data)
|
| 181 |
+
column_names.append(column_transform_info.column_name)
|
| 182 |
+
st += dim
|
| 183 |
+
|
| 184 |
+
recovered_data = np.column_stack(recovered_column_data_list)
|
| 185 |
+
recovered_data = (pd.DataFrame(recovered_data, columns=column_names)
|
| 186 |
+
.astype(self._column_raw_dtypes))
|
| 187 |
+
if not self.dataframe:
|
| 188 |
+
recovered_data = recovered_data.to_numpy()
|
| 189 |
+
|
| 190 |
+
return recovered_data
|
| 191 |
+
|
| 192 |
+
def convert_column_name_value_to_id(self, column_name, value):
|
| 193 |
+
"""Get the ids of the given `column_name`."""
|
| 194 |
+
discrete_counter = 0
|
| 195 |
+
column_id = 0
|
| 196 |
+
for column_transform_info in self._column_transform_info_list:
|
| 197 |
+
if column_transform_info.column_name == column_name:
|
| 198 |
+
break
|
| 199 |
+
if column_transform_info.column_type == 'discrete':
|
| 200 |
+
discrete_counter += 1
|
| 201 |
+
|
| 202 |
+
column_id += 1
|
| 203 |
+
|
| 204 |
+
else:
|
| 205 |
+
raise ValueError(f"The column_name `{column_name}` doesn't exist in the data.")
|
| 206 |
+
|
| 207 |
+
ohe = column_transform_info.transform
|
| 208 |
+
data = pd.DataFrame([value], columns=[column_transform_info.column_name])
|
| 209 |
+
one_hot = ohe.transform(data).to_numpy()[0]
|
| 210 |
+
if sum(one_hot) == 0:
|
| 211 |
+
raise ValueError(f"The value `{value}` doesn't exist in the column `{column_name}`.")
|
| 212 |
+
|
| 213 |
+
return {
|
| 214 |
+
'discrete_column_id': discrete_counter,
|
| 215 |
+
'column_id': column_id,
|
| 216 |
+
'value_id': np.argmax(one_hot)
|
| 217 |
+
}
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/demo.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Demo module."""
|
| 2 |
+
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
DEMO_URL = 'http://ctgan-data.s3.amazonaws.com/census.csv.gz'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def load_demo():
|
| 9 |
+
"""Load the demo."""
|
| 10 |
+
return pd.read_csv(DEMO_URL, compression='gzip')
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Synthesizers module."""
|
| 2 |
+
|
| 3 |
+
from .ctgan import CTGANSynthesizer
|
| 4 |
+
from .tvae import TVAESynthesizer
|
| 5 |
+
|
| 6 |
+
__all__ = (
|
| 7 |
+
'CTGANSynthesizer',
|
| 8 |
+
'TVAESynthesizer'
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_all_synthesizers():
|
| 13 |
+
return {
|
| 14 |
+
name: globals()[name]
|
| 15 |
+
for name in __all__
|
| 16 |
+
}
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/base.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""BaseSynthesizer module."""
|
| 2 |
+
|
| 3 |
+
import contextlib
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@contextlib.contextmanager
|
| 10 |
+
def set_random_states(random_state, set_model_random_state):
|
| 11 |
+
"""Context manager for managing the random state.
|
| 12 |
+
|
| 13 |
+
Args:
|
| 14 |
+
random_state (int or tuple):
|
| 15 |
+
The random seed or a tuple of (numpy.random.RandomState, torch.Generator).
|
| 16 |
+
set_model_random_state (function):
|
| 17 |
+
Function to set the random state on the model.
|
| 18 |
+
"""
|
| 19 |
+
original_np_state = np.random.get_state()
|
| 20 |
+
original_torch_state = torch.get_rng_state()
|
| 21 |
+
|
| 22 |
+
random_np_state, random_torch_state = random_state
|
| 23 |
+
|
| 24 |
+
np.random.set_state(random_np_state.get_state())
|
| 25 |
+
torch.set_rng_state(random_torch_state.get_state())
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
yield
|
| 29 |
+
finally:
|
| 30 |
+
current_np_state = np.random.RandomState()
|
| 31 |
+
current_np_state.set_state(np.random.get_state())
|
| 32 |
+
current_torch_state = torch.Generator()
|
| 33 |
+
current_torch_state.set_state(torch.get_rng_state())
|
| 34 |
+
set_model_random_state((current_np_state, current_torch_state))
|
| 35 |
+
|
| 36 |
+
np.random.set_state(original_np_state)
|
| 37 |
+
torch.set_rng_state(original_torch_state)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def random_state(function):
|
| 41 |
+
"""Set the random state before calling the function.
|
| 42 |
+
|
| 43 |
+
Args:
|
| 44 |
+
function (Callable):
|
| 45 |
+
The function to wrap around.
|
| 46 |
+
"""
|
| 47 |
+
def wrapper(self, *args, **kwargs):
|
| 48 |
+
if self.random_states is None:
|
| 49 |
+
return function(self, *args, **kwargs)
|
| 50 |
+
|
| 51 |
+
else:
|
| 52 |
+
with set_random_states(self.random_states, self.set_random_state):
|
| 53 |
+
return function(self, *args, **kwargs)
|
| 54 |
+
|
| 55 |
+
return wrapper
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class BaseSynthesizer:
|
| 59 |
+
"""Base class for all default synthesizers of ``CTGAN``.
|
| 60 |
+
|
| 61 |
+
This should contain the save/load methods.
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
random_states = None
|
| 65 |
+
|
| 66 |
+
def save(self, path):
|
| 67 |
+
"""Save the model in the passed `path`."""
|
| 68 |
+
device_backup = self._device
|
| 69 |
+
self.set_device(torch.device('cpu'))
|
| 70 |
+
torch.save(self, path)
|
| 71 |
+
self.set_device(device_backup)
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def load(cls, path):
|
| 75 |
+
"""Load the model stored in the passed `path`."""
|
| 76 |
+
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
|
| 77 |
+
model = torch.load(path)
|
| 78 |
+
model.set_device(device)
|
| 79 |
+
return model
|
| 80 |
+
|
| 81 |
+
def set_random_state(self, random_state):
|
| 82 |
+
"""Set the random state.
|
| 83 |
+
|
| 84 |
+
Args:
|
| 85 |
+
random_state (int, tuple, or None):
|
| 86 |
+
Either a tuple containing the (numpy.random.RandomState, torch.Generator)
|
| 87 |
+
or an int representing the random seed to use for both random states.
|
| 88 |
+
"""
|
| 89 |
+
if random_state is None:
|
| 90 |
+
self.random_states = random_state
|
| 91 |
+
elif isinstance(random_state, int):
|
| 92 |
+
self.random_states = (
|
| 93 |
+
np.random.RandomState(seed=random_state),
|
| 94 |
+
torch.Generator().manual_seed(random_state),
|
| 95 |
+
)
|
| 96 |
+
elif (
|
| 97 |
+
isinstance(random_state, tuple) and
|
| 98 |
+
isinstance(random_state[0], np.random.RandomState) and
|
| 99 |
+
isinstance(random_state[1], torch.Generator)
|
| 100 |
+
):
|
| 101 |
+
self.random_states = random_state
|
| 102 |
+
else:
|
| 103 |
+
raise TypeError(
|
| 104 |
+
f'`random_state` {random_state} expected to be an int or a tuple of '
|
| 105 |
+
'(`np.random.RandomState`, `torch.Generator`)')
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/ctgan.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CTGANSynthesizer module."""
|
| 2 |
+
|
| 3 |
+
import warnings
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import torch
|
| 8 |
+
from packaging import version
|
| 9 |
+
from torch import optim
|
| 10 |
+
from torch.nn import BatchNorm1d, Dropout, LeakyReLU, Linear, Module, ReLU, Sequential, functional
|
| 11 |
+
|
| 12 |
+
from ..data_sampler import DataSampler
|
| 13 |
+
from ..data_transformer import DataTransformer
|
| 14 |
+
from .base import BaseSynthesizer, random_state
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class Discriminator(Module):
|
| 18 |
+
"""Discriminator for the CTGANSynthesizer."""
|
| 19 |
+
|
| 20 |
+
def __init__(self, input_dim, discriminator_dim, pac=10):
|
| 21 |
+
super(Discriminator, self).__init__()
|
| 22 |
+
dim = input_dim * pac
|
| 23 |
+
self.pac = pac
|
| 24 |
+
self.pacdim = dim
|
| 25 |
+
seq = []
|
| 26 |
+
for item in list(discriminator_dim):
|
| 27 |
+
seq += [Linear(dim, item), LeakyReLU(0.2), Dropout(0.5)]
|
| 28 |
+
dim = item
|
| 29 |
+
|
| 30 |
+
seq += [Linear(dim, 1)]
|
| 31 |
+
self.seq = Sequential(*seq)
|
| 32 |
+
|
| 33 |
+
def calc_gradient_penalty(self, real_data, fake_data, device='cpu', pac=10, lambda_=10):
|
| 34 |
+
"""Compute the gradient penalty."""
|
| 35 |
+
alpha = torch.rand(real_data.size(0) // pac, 1, 1, device=device)
|
| 36 |
+
alpha = alpha.repeat(1, pac, real_data.size(1))
|
| 37 |
+
alpha = alpha.view(-1, real_data.size(1))
|
| 38 |
+
|
| 39 |
+
interpolates = alpha * real_data + ((1 - alpha) * fake_data)
|
| 40 |
+
|
| 41 |
+
disc_interpolates = self(interpolates)
|
| 42 |
+
|
| 43 |
+
gradients = torch.autograd.grad(
|
| 44 |
+
outputs=disc_interpolates, inputs=interpolates,
|
| 45 |
+
grad_outputs=torch.ones(disc_interpolates.size(), device=device),
|
| 46 |
+
create_graph=True, retain_graph=True, only_inputs=True
|
| 47 |
+
)[0]
|
| 48 |
+
|
| 49 |
+
gradients_view = gradients.view(-1, pac * real_data.size(1)).norm(2, dim=1) - 1
|
| 50 |
+
gradient_penalty = ((gradients_view) ** 2).mean() * lambda_
|
| 51 |
+
|
| 52 |
+
return gradient_penalty
|
| 53 |
+
|
| 54 |
+
def forward(self, input_):
|
| 55 |
+
"""Apply the Discriminator to the `input_`."""
|
| 56 |
+
assert input_.size()[0] % self.pac == 0
|
| 57 |
+
return self.seq(input_.view(-1, self.pacdim))
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class Residual(Module):
|
| 61 |
+
"""Residual layer for the CTGANSynthesizer."""
|
| 62 |
+
|
| 63 |
+
def __init__(self, i, o):
|
| 64 |
+
super(Residual, self).__init__()
|
| 65 |
+
self.fc = Linear(i, o)
|
| 66 |
+
self.bn = BatchNorm1d(o)
|
| 67 |
+
self.relu = ReLU()
|
| 68 |
+
|
| 69 |
+
def forward(self, input_):
|
| 70 |
+
"""Apply the Residual layer to the `input_`."""
|
| 71 |
+
out = self.fc(input_)
|
| 72 |
+
out = self.bn(out)
|
| 73 |
+
out = self.relu(out)
|
| 74 |
+
return torch.cat([out, input_], dim=1)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class Generator(Module):
|
| 78 |
+
"""Generator for the CTGANSynthesizer."""
|
| 79 |
+
|
| 80 |
+
def __init__(self, embedding_dim, generator_dim, data_dim):
|
| 81 |
+
super(Generator, self).__init__()
|
| 82 |
+
dim = embedding_dim
|
| 83 |
+
seq = []
|
| 84 |
+
for item in list(generator_dim):
|
| 85 |
+
seq += [Residual(dim, item)]
|
| 86 |
+
dim += item
|
| 87 |
+
seq.append(Linear(dim, data_dim))
|
| 88 |
+
self.seq = Sequential(*seq)
|
| 89 |
+
|
| 90 |
+
def forward(self, input_):
|
| 91 |
+
"""Apply the Generator to the `input_`."""
|
| 92 |
+
data = self.seq(input_)
|
| 93 |
+
return data
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class CTGANSynthesizer(BaseSynthesizer):
|
| 97 |
+
"""Conditional Table GAN Synthesizer.
|
| 98 |
+
|
| 99 |
+
This is the core class of the CTGAN project, where the different components
|
| 100 |
+
are orchestrated together.
|
| 101 |
+
For more details about the process, please check the [Modeling Tabular data using
|
| 102 |
+
Conditional GAN](https://arxiv.org/abs/1907.00503) paper.
|
| 103 |
+
|
| 104 |
+
Args:
|
| 105 |
+
embedding_dim (int):
|
| 106 |
+
Size of the random sample passed to the Generator. Defaults to 128.
|
| 107 |
+
generator_dim (tuple or list of ints):
|
| 108 |
+
Size of the output samples for each one of the Residuals. A Residual Layer
|
| 109 |
+
will be created for each one of the values provided. Defaults to (256, 256).
|
| 110 |
+
discriminator_dim (tuple or list of ints):
|
| 111 |
+
Size of the output samples for each one of the Discriminator Layers. A Linear Layer
|
| 112 |
+
will be created for each one of the values provided. Defaults to (256, 256).
|
| 113 |
+
generator_lr (float):
|
| 114 |
+
Learning rate for the generator. Defaults to 2e-4.
|
| 115 |
+
generator_decay (float):
|
| 116 |
+
Generator weight decay for the Adam Optimizer. Defaults to 1e-6.
|
| 117 |
+
discriminator_lr (float):
|
| 118 |
+
Learning rate for the discriminator. Defaults to 2e-4.
|
| 119 |
+
discriminator_decay (float):
|
| 120 |
+
Discriminator weight decay for the Adam Optimizer. Defaults to 1e-6.
|
| 121 |
+
batch_size (int):
|
| 122 |
+
Number of data samples to process in each step.
|
| 123 |
+
discriminator_steps (int):
|
| 124 |
+
Number of discriminator updates to do for each generator update.
|
| 125 |
+
From the WGAN paper: https://arxiv.org/abs/1701.07875. WGAN paper
|
| 126 |
+
default is 5. Default used is 1 to match original CTGAN implementation.
|
| 127 |
+
log_frequency (boolean):
|
| 128 |
+
Whether to use log frequency of categorical levels in conditional
|
| 129 |
+
sampling. Defaults to ``True``.
|
| 130 |
+
verbose (boolean):
|
| 131 |
+
Whether to have print statements for progress results. Defaults to ``False``.
|
| 132 |
+
epochs (int):
|
| 133 |
+
Number of training epochs. Defaults to 300.
|
| 134 |
+
pac (int):
|
| 135 |
+
Number of samples to group together when applying the discriminator.
|
| 136 |
+
Defaults to 10.
|
| 137 |
+
cuda (bool):
|
| 138 |
+
Whether to attempt to use cuda for GPU computation.
|
| 139 |
+
If this is False or CUDA is not available, CPU will be used.
|
| 140 |
+
Defaults to ``True``.
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
def __init__(self, embedding_dim=128, generator_dim=(256, 256), discriminator_dim=(256, 256),
|
| 144 |
+
generator_lr=2e-4, generator_decay=1e-6, discriminator_lr=2e-4,
|
| 145 |
+
discriminator_decay=1e-6, batch_size=500, discriminator_steps=1,
|
| 146 |
+
log_frequency=True, verbose=False, epochs=300, pac=10, cuda=True):
|
| 147 |
+
|
| 148 |
+
assert batch_size % 2 == 0
|
| 149 |
+
|
| 150 |
+
self._embedding_dim = embedding_dim
|
| 151 |
+
self._generator_dim = generator_dim
|
| 152 |
+
self._discriminator_dim = discriminator_dim
|
| 153 |
+
|
| 154 |
+
self._generator_lr = generator_lr
|
| 155 |
+
self._generator_decay = generator_decay
|
| 156 |
+
self._discriminator_lr = discriminator_lr
|
| 157 |
+
self._discriminator_decay = discriminator_decay
|
| 158 |
+
|
| 159 |
+
self._batch_size = batch_size
|
| 160 |
+
self._discriminator_steps = discriminator_steps
|
| 161 |
+
self._log_frequency = log_frequency
|
| 162 |
+
self._verbose = verbose
|
| 163 |
+
self._epochs = epochs
|
| 164 |
+
self.pac = pac
|
| 165 |
+
|
| 166 |
+
if not cuda or not torch.cuda.is_available():
|
| 167 |
+
device = 'cpu'
|
| 168 |
+
elif isinstance(cuda, str):
|
| 169 |
+
device = cuda
|
| 170 |
+
else:
|
| 171 |
+
device = 'cuda'
|
| 172 |
+
|
| 173 |
+
self._device = torch.device(device)
|
| 174 |
+
|
| 175 |
+
self._transformer = None
|
| 176 |
+
self._data_sampler = None
|
| 177 |
+
self._generator = None
|
| 178 |
+
|
| 179 |
+
@staticmethod
|
| 180 |
+
def _gumbel_softmax(logits, tau=1, hard=False, eps=1e-10, dim=-1):
|
| 181 |
+
"""Deals with the instability of the gumbel_softmax for older versions of torch.
|
| 182 |
+
|
| 183 |
+
For more details about the issue:
|
| 184 |
+
https://drive.google.com/file/d/1AA5wPfZ1kquaRtVruCd6BiYZGcDeNxyP/view?usp=sharing
|
| 185 |
+
|
| 186 |
+
Args:
|
| 187 |
+
logits […, num_features]:
|
| 188 |
+
Unnormalized log probabilities
|
| 189 |
+
tau:
|
| 190 |
+
Non-negative scalar temperature
|
| 191 |
+
hard (bool):
|
| 192 |
+
If True, the returned samples will be discretized as one-hot vectors,
|
| 193 |
+
but will be differentiated as if it is the soft sample in autograd
|
| 194 |
+
dim (int):
|
| 195 |
+
A dimension along which softmax will be computed. Default: -1.
|
| 196 |
+
|
| 197 |
+
Returns:
|
| 198 |
+
Sampled tensor of same shape as logits from the Gumbel-Softmax distribution.
|
| 199 |
+
"""
|
| 200 |
+
if version.parse(torch.__version__) < version.parse('1.2.0'):
|
| 201 |
+
for i in range(10):
|
| 202 |
+
transformed = functional.gumbel_softmax(logits, tau=tau, hard=hard,
|
| 203 |
+
eps=eps, dim=dim)
|
| 204 |
+
if not torch.isnan(transformed).any():
|
| 205 |
+
return transformed
|
| 206 |
+
raise ValueError('gumbel_softmax returning NaN.')
|
| 207 |
+
|
| 208 |
+
return functional.gumbel_softmax(logits, tau=tau, hard=hard, eps=eps, dim=dim)
|
| 209 |
+
|
| 210 |
+
def _apply_activate(self, data):
|
| 211 |
+
"""Apply proper activation function to the output of the generator."""
|
| 212 |
+
data_t = []
|
| 213 |
+
st = 0
|
| 214 |
+
for column_info in self._transformer.output_info_list:
|
| 215 |
+
for span_info in column_info:
|
| 216 |
+
if span_info.activation_fn == 'tanh':
|
| 217 |
+
ed = st + span_info.dim
|
| 218 |
+
data_t.append(torch.tanh(data[:, st:ed]))
|
| 219 |
+
st = ed
|
| 220 |
+
elif span_info.activation_fn == 'softmax':
|
| 221 |
+
ed = st + span_info.dim
|
| 222 |
+
transformed = self._gumbel_softmax(data[:, st:ed], tau=0.2)
|
| 223 |
+
data_t.append(transformed)
|
| 224 |
+
st = ed
|
| 225 |
+
else:
|
| 226 |
+
raise ValueError(f'Unexpected activation function {span_info.activation_fn}.')
|
| 227 |
+
|
| 228 |
+
return torch.cat(data_t, dim=1)
|
| 229 |
+
|
| 230 |
+
def _cond_loss(self, data, c, m):
|
| 231 |
+
"""Compute the cross entropy loss on the fixed discrete column."""
|
| 232 |
+
loss = []
|
| 233 |
+
st = 0
|
| 234 |
+
st_c = 0
|
| 235 |
+
for column_info in self._transformer.output_info_list:
|
| 236 |
+
for span_info in column_info:
|
| 237 |
+
if len(column_info) != 1 or span_info.activation_fn != 'softmax':
|
| 238 |
+
# not discrete column
|
| 239 |
+
st += span_info.dim
|
| 240 |
+
else:
|
| 241 |
+
ed = st + span_info.dim
|
| 242 |
+
ed_c = st_c + span_info.dim
|
| 243 |
+
tmp = functional.cross_entropy(
|
| 244 |
+
data[:, st:ed],
|
| 245 |
+
torch.argmax(c[:, st_c:ed_c], dim=1),
|
| 246 |
+
reduction='none'
|
| 247 |
+
)
|
| 248 |
+
loss.append(tmp)
|
| 249 |
+
st = ed
|
| 250 |
+
st_c = ed_c
|
| 251 |
+
|
| 252 |
+
loss = torch.stack(loss, dim=1) # noqa: PD013
|
| 253 |
+
|
| 254 |
+
return (loss * m).sum() / data.size()[0]
|
| 255 |
+
|
| 256 |
+
def _validate_discrete_columns(self, train_data, discrete_columns):
|
| 257 |
+
"""Check whether ``discrete_columns`` exists in ``train_data``.
|
| 258 |
+
|
| 259 |
+
Args:
|
| 260 |
+
train_data (numpy.ndarray or pandas.DataFrame):
|
| 261 |
+
Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame.
|
| 262 |
+
discrete_columns (list-like):
|
| 263 |
+
List of discrete columns to be used to generate the Conditional
|
| 264 |
+
Vector. If ``train_data`` is a Numpy array, this list should
|
| 265 |
+
contain the integer indices of the columns. Otherwise, if it is
|
| 266 |
+
a ``pandas.DataFrame``, this list should contain the column names.
|
| 267 |
+
"""
|
| 268 |
+
if isinstance(train_data, pd.DataFrame):
|
| 269 |
+
invalid_columns = set(discrete_columns) - set(train_data.columns)
|
| 270 |
+
elif isinstance(train_data, np.ndarray):
|
| 271 |
+
invalid_columns = []
|
| 272 |
+
for column in discrete_columns:
|
| 273 |
+
if column < 0 or column >= train_data.shape[1]:
|
| 274 |
+
invalid_columns.append(column)
|
| 275 |
+
else:
|
| 276 |
+
raise TypeError('``train_data`` should be either pd.DataFrame or np.array.')
|
| 277 |
+
|
| 278 |
+
if invalid_columns:
|
| 279 |
+
raise ValueError(f'Invalid columns found: {invalid_columns}')
|
| 280 |
+
|
| 281 |
+
@random_state
|
| 282 |
+
def fit(self, train_data, discrete_columns=(), epochs=None):
|
| 283 |
+
"""Fit the CTGAN Synthesizer models to the training data.
|
| 284 |
+
|
| 285 |
+
Args:
|
| 286 |
+
train_data (numpy.ndarray or pandas.DataFrame):
|
| 287 |
+
Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame.
|
| 288 |
+
discrete_columns (list-like):
|
| 289 |
+
List of discrete columns to be used to generate the Conditional
|
| 290 |
+
Vector. If ``train_data`` is a Numpy array, this list should
|
| 291 |
+
contain the integer indices of the columns. Otherwise, if it is
|
| 292 |
+
a ``pandas.DataFrame``, this list should contain the column names.
|
| 293 |
+
"""
|
| 294 |
+
self._validate_discrete_columns(train_data, discrete_columns)
|
| 295 |
+
|
| 296 |
+
if epochs is None:
|
| 297 |
+
epochs = self._epochs
|
| 298 |
+
else:
|
| 299 |
+
warnings.warn(
|
| 300 |
+
('`epochs` argument in `fit` method has been deprecated and will be removed '
|
| 301 |
+
'in a future version. Please pass `epochs` to the constructor instead'),
|
| 302 |
+
DeprecationWarning
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
self._transformer = DataTransformer()
|
| 306 |
+
self._transformer.fit(train_data, discrete_columns)
|
| 307 |
+
|
| 308 |
+
train_data = self._transformer.transform(train_data)
|
| 309 |
+
|
| 310 |
+
self._data_sampler = DataSampler(
|
| 311 |
+
train_data,
|
| 312 |
+
self._transformer.output_info_list,
|
| 313 |
+
self._log_frequency)
|
| 314 |
+
|
| 315 |
+
data_dim = self._transformer.output_dimensions
|
| 316 |
+
|
| 317 |
+
self._generator = Generator(
|
| 318 |
+
self._embedding_dim + self._data_sampler.dim_cond_vec(),
|
| 319 |
+
self._generator_dim,
|
| 320 |
+
data_dim
|
| 321 |
+
).to(self._device)
|
| 322 |
+
|
| 323 |
+
discriminator = Discriminator(
|
| 324 |
+
data_dim + self._data_sampler.dim_cond_vec(),
|
| 325 |
+
self._discriminator_dim,
|
| 326 |
+
pac=self.pac
|
| 327 |
+
).to(self._device)
|
| 328 |
+
|
| 329 |
+
optimizerG = optim.Adam(
|
| 330 |
+
self._generator.parameters(), lr=self._generator_lr, betas=(0.5, 0.9),
|
| 331 |
+
weight_decay=self._generator_decay
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
optimizerD = optim.Adam(
|
| 335 |
+
discriminator.parameters(), lr=self._discriminator_lr,
|
| 336 |
+
betas=(0.5, 0.9), weight_decay=self._discriminator_decay
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
mean = torch.zeros(self._batch_size, self._embedding_dim, device=self._device)
|
| 340 |
+
std = mean + 1
|
| 341 |
+
|
| 342 |
+
print('CTGAN training')
|
| 343 |
+
steps_per_epoch = max(len(train_data) // self._batch_size, 1)
|
| 344 |
+
for i in range(epochs):
|
| 345 |
+
for n in range(self._discriminator_steps):
|
| 346 |
+
fakez = torch.normal(mean=mean, std=std)
|
| 347 |
+
|
| 348 |
+
condvec = self._data_sampler.sample_condvec(self._batch_size)
|
| 349 |
+
if condvec is None:
|
| 350 |
+
c1, m1, col, opt = None, None, None, None
|
| 351 |
+
real = self._data_sampler.sample_data(self._batch_size, col, opt)
|
| 352 |
+
else:
|
| 353 |
+
c1, m1, col, opt = condvec
|
| 354 |
+
c1 = torch.from_numpy(c1).to(self._device)
|
| 355 |
+
m1 = torch.from_numpy(m1).to(self._device)
|
| 356 |
+
fakez = torch.cat([fakez, c1], dim=1)
|
| 357 |
+
|
| 358 |
+
perm = np.arange(self._batch_size)
|
| 359 |
+
np.random.shuffle(perm)
|
| 360 |
+
real = self._data_sampler.sample_data(
|
| 361 |
+
self._batch_size, col[perm], opt[perm])
|
| 362 |
+
c2 = c1[perm]
|
| 363 |
+
|
| 364 |
+
fake = self._generator(fakez)
|
| 365 |
+
fakeact = self._apply_activate(fake)
|
| 366 |
+
|
| 367 |
+
real = torch.from_numpy(real.astype('float32')).to(self._device)
|
| 368 |
+
|
| 369 |
+
if c1 is not None:
|
| 370 |
+
fake_cat = torch.cat([fakeact, c1], dim=1)
|
| 371 |
+
real_cat = torch.cat([real, c2], dim=1)
|
| 372 |
+
else:
|
| 373 |
+
real_cat = real
|
| 374 |
+
fake_cat = fakeact
|
| 375 |
+
|
| 376 |
+
y_fake = discriminator(fake_cat)
|
| 377 |
+
y_real = discriminator(real_cat)
|
| 378 |
+
|
| 379 |
+
pen = discriminator.calc_gradient_penalty(
|
| 380 |
+
real_cat, fake_cat, self._device, self.pac)
|
| 381 |
+
loss_d = -(torch.mean(y_real) - torch.mean(y_fake))
|
| 382 |
+
|
| 383 |
+
optimizerD.zero_grad()
|
| 384 |
+
pen.backward(retain_graph=True)
|
| 385 |
+
loss_d.backward()
|
| 386 |
+
optimizerD.step()
|
| 387 |
+
|
| 388 |
+
fakez = torch.normal(mean=mean, std=std)
|
| 389 |
+
condvec = self._data_sampler.sample_condvec(self._batch_size)
|
| 390 |
+
|
| 391 |
+
if condvec is None:
|
| 392 |
+
c1, m1, col, opt = None, None, None, None
|
| 393 |
+
else:
|
| 394 |
+
c1, m1, col, opt = condvec
|
| 395 |
+
c1 = torch.from_numpy(c1).to(self._device)
|
| 396 |
+
m1 = torch.from_numpy(m1).to(self._device)
|
| 397 |
+
fakez = torch.cat([fakez, c1], dim=1)
|
| 398 |
+
|
| 399 |
+
fake = self._generator(fakez)
|
| 400 |
+
fakeact = self._apply_activate(fake)
|
| 401 |
+
|
| 402 |
+
if c1 is not None:
|
| 403 |
+
y_fake = discriminator(torch.cat([fakeact, c1], dim=1))
|
| 404 |
+
else:
|
| 405 |
+
y_fake = discriminator(fakeact)
|
| 406 |
+
|
| 407 |
+
if condvec is None:
|
| 408 |
+
cross_entropy = 0
|
| 409 |
+
else:
|
| 410 |
+
cross_entropy = self._cond_loss(fake, c1, m1)
|
| 411 |
+
|
| 412 |
+
loss_g = -torch.mean(y_fake) + cross_entropy
|
| 413 |
+
|
| 414 |
+
optimizerG.zero_grad()
|
| 415 |
+
loss_g.backward()
|
| 416 |
+
optimizerG.step()
|
| 417 |
+
|
| 418 |
+
if self._verbose and (i + 1) % 1000 == 0:
|
| 419 |
+
print(f'Epoch {i+1}, Loss G: {loss_g.detach().cpu(): .4f},' # noqa: T001
|
| 420 |
+
f'Loss D: {loss_d.detach().cpu(): .4f}',
|
| 421 |
+
flush=True)
|
| 422 |
+
|
| 423 |
+
@random_state
|
| 424 |
+
def sample(self, n, condition_column=None, condition_value=None):
|
| 425 |
+
"""Sample data similar to the training data.
|
| 426 |
+
|
| 427 |
+
Choosing a condition_column and condition_value will increase the probability of the
|
| 428 |
+
discrete condition_value happening in the condition_column.
|
| 429 |
+
|
| 430 |
+
Args:
|
| 431 |
+
n (int):
|
| 432 |
+
Number of rows to sample.
|
| 433 |
+
condition_column (string):
|
| 434 |
+
Name of a discrete column.
|
| 435 |
+
condition_value (string):
|
| 436 |
+
Name of the category in the condition_column which we wish to increase the
|
| 437 |
+
probability of happening.
|
| 438 |
+
|
| 439 |
+
Returns:
|
| 440 |
+
numpy.ndarray or pandas.DataFrame
|
| 441 |
+
"""
|
| 442 |
+
if condition_column is not None and condition_value is not None:
|
| 443 |
+
condition_info = self._transformer.convert_column_name_value_to_id(
|
| 444 |
+
condition_column, condition_value)
|
| 445 |
+
global_condition_vec = self._data_sampler.generate_cond_from_condition_column_info(
|
| 446 |
+
condition_info, self._batch_size)
|
| 447 |
+
else:
|
| 448 |
+
global_condition_vec = None
|
| 449 |
+
|
| 450 |
+
steps = n // self._batch_size + 1
|
| 451 |
+
data = []
|
| 452 |
+
for i in range(steps):
|
| 453 |
+
mean = torch.zeros(self._batch_size, self._embedding_dim)
|
| 454 |
+
std = mean + 1
|
| 455 |
+
fakez = torch.normal(mean=mean, std=std).to(self._device)
|
| 456 |
+
|
| 457 |
+
if global_condition_vec is not None:
|
| 458 |
+
condvec = global_condition_vec.copy()
|
| 459 |
+
else:
|
| 460 |
+
condvec = self._data_sampler.sample_original_condvec(self._batch_size)
|
| 461 |
+
|
| 462 |
+
if condvec is None:
|
| 463 |
+
pass
|
| 464 |
+
else:
|
| 465 |
+
c1 = condvec
|
| 466 |
+
c1 = torch.from_numpy(c1).to(self._device)
|
| 467 |
+
fakez = torch.cat([fakez, c1], dim=1)
|
| 468 |
+
|
| 469 |
+
fake = self._generator(fakez)
|
| 470 |
+
fakeact = self._apply_activate(fake)
|
| 471 |
+
data.append(fakeact.detach().cpu().numpy())
|
| 472 |
+
|
| 473 |
+
data = np.concatenate(data, axis=0)
|
| 474 |
+
data = data[:n]
|
| 475 |
+
|
| 476 |
+
return self._transformer.inverse_transform(data)
|
| 477 |
+
|
| 478 |
+
def set_device(self, device):
|
| 479 |
+
"""Set the `device` to be used ('GPU' or 'CPU)."""
|
| 480 |
+
self._device = device
|
| 481 |
+
if self._generator is not None:
|
| 482 |
+
self._generator.to(self._device)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/ctgan/synthesizers/tvae.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TVAESynthesizer module."""
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from torch.nn import Linear, Module, Parameter, ReLU, Sequential
|
| 6 |
+
from torch.nn.functional import cross_entropy
|
| 7 |
+
from torch.optim import Adam
|
| 8 |
+
from torch.utils.data import DataLoader, TensorDataset
|
| 9 |
+
|
| 10 |
+
from ..data_transformer import DataTransformer
|
| 11 |
+
from .base import BaseSynthesizer, random_state
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Encoder(Module):
|
| 15 |
+
"""Encoder for the TVAESynthesizer.
|
| 16 |
+
|
| 17 |
+
Args:
|
| 18 |
+
data_dim (int):
|
| 19 |
+
Dimensions of the data.
|
| 20 |
+
compress_dims (tuple or list of ints):
|
| 21 |
+
Size of each hidden layer.
|
| 22 |
+
embedding_dim (int):
|
| 23 |
+
Size of the output vector.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def __init__(self, data_dim, compress_dims, embedding_dim):
|
| 27 |
+
super(Encoder, self).__init__()
|
| 28 |
+
dim = data_dim
|
| 29 |
+
seq = []
|
| 30 |
+
for item in list(compress_dims):
|
| 31 |
+
seq += [
|
| 32 |
+
Linear(dim, item),
|
| 33 |
+
ReLU()
|
| 34 |
+
]
|
| 35 |
+
dim = item
|
| 36 |
+
|
| 37 |
+
self.seq = Sequential(*seq)
|
| 38 |
+
self.fc1 = Linear(dim, embedding_dim)
|
| 39 |
+
self.fc2 = Linear(dim, embedding_dim)
|
| 40 |
+
|
| 41 |
+
def forward(self, input_):
|
| 42 |
+
"""Encode the passed `input_`."""
|
| 43 |
+
feature = self.seq(input_)
|
| 44 |
+
mu = self.fc1(feature)
|
| 45 |
+
logvar = self.fc2(feature)
|
| 46 |
+
std = torch.exp(0.5 * logvar)
|
| 47 |
+
return mu, std, logvar
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Decoder(Module):
|
| 51 |
+
"""Decoder for the TVAESynthesizer.
|
| 52 |
+
|
| 53 |
+
Args:
|
| 54 |
+
embedding_dim (int):
|
| 55 |
+
Size of the input vector.
|
| 56 |
+
decompress_dims (tuple or list of ints):
|
| 57 |
+
Size of each hidden layer.
|
| 58 |
+
data_dim (int):
|
| 59 |
+
Dimensions of the data.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(self, embedding_dim, decompress_dims, data_dim):
|
| 63 |
+
super(Decoder, self).__init__()
|
| 64 |
+
dim = embedding_dim
|
| 65 |
+
seq = []
|
| 66 |
+
for item in list(decompress_dims):
|
| 67 |
+
seq += [Linear(dim, item), ReLU()]
|
| 68 |
+
dim = item
|
| 69 |
+
|
| 70 |
+
seq.append(Linear(dim, data_dim))
|
| 71 |
+
self.seq = Sequential(*seq)
|
| 72 |
+
self.sigma = Parameter(torch.ones(data_dim) * 0.1)
|
| 73 |
+
|
| 74 |
+
def forward(self, input_):
|
| 75 |
+
"""Decode the passed `input_`."""
|
| 76 |
+
return self.seq(input_), self.sigma
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _loss_function(recon_x, x, sigmas, mu, logvar, output_info, factor):
|
| 80 |
+
st = 0
|
| 81 |
+
loss = []
|
| 82 |
+
for column_info in output_info:
|
| 83 |
+
for span_info in column_info:
|
| 84 |
+
if span_info.activation_fn != 'softmax':
|
| 85 |
+
ed = st + span_info.dim
|
| 86 |
+
std = sigmas[st]
|
| 87 |
+
eq = x[:, st] - torch.tanh(recon_x[:, st])
|
| 88 |
+
loss.append((eq ** 2 / 2 / (std ** 2)).sum())
|
| 89 |
+
loss.append(torch.log(std) * x.size()[0])
|
| 90 |
+
st = ed
|
| 91 |
+
|
| 92 |
+
else:
|
| 93 |
+
ed = st + span_info.dim
|
| 94 |
+
loss.append(cross_entropy(
|
| 95 |
+
recon_x[:, st:ed], torch.argmax(x[:, st:ed], dim=-1), reduction='sum'))
|
| 96 |
+
st = ed
|
| 97 |
+
|
| 98 |
+
assert st == recon_x.size()[1]
|
| 99 |
+
KLD = -0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp())
|
| 100 |
+
return sum(loss) * factor / x.size()[0], KLD / x.size()[0]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class TVAESynthesizer(BaseSynthesizer):
|
| 104 |
+
"""TVAESynthesizer."""
|
| 105 |
+
|
| 106 |
+
def __init__(
|
| 107 |
+
self,
|
| 108 |
+
embedding_dim=128,
|
| 109 |
+
compress_dims=(128, 128),
|
| 110 |
+
decompress_dims=(128, 128),
|
| 111 |
+
l2scale=1e-5,
|
| 112 |
+
batch_size=500,
|
| 113 |
+
epochs=300,
|
| 114 |
+
lr=1e-3,
|
| 115 |
+
loss_factor=2,
|
| 116 |
+
device="cuda:0"
|
| 117 |
+
):
|
| 118 |
+
self.embedding_dim = embedding_dim
|
| 119 |
+
self.compress_dims = compress_dims
|
| 120 |
+
self.decompress_dims = decompress_dims
|
| 121 |
+
|
| 122 |
+
self.lr = lr
|
| 123 |
+
self.l2scale = l2scale
|
| 124 |
+
self.batch_size = batch_size
|
| 125 |
+
self.loss_factor = loss_factor
|
| 126 |
+
self.epochs = epochs
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
self._device = torch.device(device)
|
| 130 |
+
|
| 131 |
+
@random_state
|
| 132 |
+
def fit(self, train_data, discrete_columns=()):
|
| 133 |
+
"""Fit the TVAE Synthesizer models to the training data.
|
| 134 |
+
|
| 135 |
+
Args:
|
| 136 |
+
train_data (numpy.ndarray or pandas.DataFrame):
|
| 137 |
+
Training Data. It must be a 2-dimensional numpy array or a pandas.DataFrame.
|
| 138 |
+
discrete_columns (list-like):
|
| 139 |
+
List of discrete columns to be used to generate the Conditional
|
| 140 |
+
Vector. If ``train_data`` is a Numpy array, this list should
|
| 141 |
+
contain the integer indices of the columns. Otherwise, if it is
|
| 142 |
+
a ``pandas.DataFrame``, this list should contain the column names.
|
| 143 |
+
"""
|
| 144 |
+
self.transformer = DataTransformer()
|
| 145 |
+
self.transformer.fit(train_data, discrete_columns)
|
| 146 |
+
train_data = self.transformer.transform(train_data)
|
| 147 |
+
dataset = TensorDataset(torch.from_numpy(train_data.astype('float32')))
|
| 148 |
+
loader = DataLoader(dataset, batch_size=self.batch_size, shuffle=True, drop_last=False)
|
| 149 |
+
|
| 150 |
+
data_dim = self.transformer.output_dimensions
|
| 151 |
+
encoder = Encoder(data_dim, self.compress_dims, self.embedding_dim).to(self._device)
|
| 152 |
+
self.decoder = Decoder(self.embedding_dim, self.decompress_dims, data_dim).to(self._device)
|
| 153 |
+
optimizerAE = Adam(
|
| 154 |
+
list(encoder.parameters()) + list(self.decoder.parameters()),
|
| 155 |
+
lr=self.lr,
|
| 156 |
+
weight_decay=self.l2scale)
|
| 157 |
+
data_iter = iter(loader)
|
| 158 |
+
print('Training:')
|
| 159 |
+
for i in range(self.epochs):
|
| 160 |
+
try:
|
| 161 |
+
data = next(data_iter)
|
| 162 |
+
except:
|
| 163 |
+
data_iter = iter(loader)
|
| 164 |
+
data = next(data_iter)
|
| 165 |
+
|
| 166 |
+
optimizerAE.zero_grad()
|
| 167 |
+
real = data[0].to(self._device)
|
| 168 |
+
mu, std, logvar = encoder(real)
|
| 169 |
+
eps = torch.randn_like(std)
|
| 170 |
+
emb = eps * std + mu
|
| 171 |
+
rec, sigmas = self.decoder(emb)
|
| 172 |
+
loss_1, loss_2 = _loss_function(
|
| 173 |
+
rec, real, sigmas, mu, logvar,
|
| 174 |
+
self.transformer.output_info_list, self.loss_factor
|
| 175 |
+
)
|
| 176 |
+
loss = loss_1 + loss_2
|
| 177 |
+
loss.backward()
|
| 178 |
+
optimizerAE.step()
|
| 179 |
+
self.decoder.sigma.data.clamp_(0.01, 1.0)
|
| 180 |
+
if (i + 1) % 1000 == 0:
|
| 181 |
+
print(f"{i + 1}/{self.epochs} {loss}", flush=True)
|
| 182 |
+
|
| 183 |
+
@random_state
|
| 184 |
+
def sample(self, samples, seed=0):
|
| 185 |
+
"""Sample data similar to the training data.
|
| 186 |
+
|
| 187 |
+
Args:
|
| 188 |
+
samples (int):
|
| 189 |
+
Number of rows to sample.
|
| 190 |
+
|
| 191 |
+
Returns:
|
| 192 |
+
numpy.ndarray or pandas.DataFrame
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
torch.cuda.manual_seed(seed)
|
| 196 |
+
torch.manual_seed(seed)
|
| 197 |
+
|
| 198 |
+
self.decoder.eval()
|
| 199 |
+
|
| 200 |
+
sample_batch_size = 8092
|
| 201 |
+
steps = samples // sample_batch_size + 1
|
| 202 |
+
data = []
|
| 203 |
+
for _ in range(steps):
|
| 204 |
+
mean = torch.zeros(sample_batch_size, self.embedding_dim)
|
| 205 |
+
std = mean + 1
|
| 206 |
+
noise = torch.normal(mean=mean, std=std).to(self._device)
|
| 207 |
+
fake, sigmas = self.decoder(noise)
|
| 208 |
+
fake = torch.tanh(fake)
|
| 209 |
+
data.append(fake.detach().cpu().numpy())
|
| 210 |
+
|
| 211 |
+
data = np.concatenate(data, axis=0)
|
| 212 |
+
data = data[:samples]
|
| 213 |
+
return self.transformer.inverse_transform(data, sigmas.detach().cpu().numpy())
|
| 214 |
+
|
| 215 |
+
def set_device(self, device):
|
| 216 |
+
"""Set the `device` to be used ('GPU' or 'CPU)."""
|
| 217 |
+
self._device = device
|
| 218 |
+
self.decoder.to(self._device)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.cfg
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[bumpversion]
|
| 2 |
+
current_version = 0.5.2.dev0
|
| 3 |
+
commit = True
|
| 4 |
+
tag = True
|
| 5 |
+
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\.(?P<release>[a-z]+)(?P<candidate>\d+))?
|
| 6 |
+
serialize =
|
| 7 |
+
{major}.{minor}.{patch}.{release}{candidate}
|
| 8 |
+
{major}.{minor}.{patch}
|
| 9 |
+
|
| 10 |
+
[bumpversion:part:release]
|
| 11 |
+
optional_value = release
|
| 12 |
+
first_value = dev
|
| 13 |
+
values =
|
| 14 |
+
dev
|
| 15 |
+
release
|
| 16 |
+
|
| 17 |
+
[bumpversion:part:candidate]
|
| 18 |
+
|
| 19 |
+
[bumpversion:file:setup.py]
|
| 20 |
+
search = version='{current_version}'
|
| 21 |
+
replace = version='{new_version}'
|
| 22 |
+
|
| 23 |
+
[bumpversion:file:ctgan/__init__.py]
|
| 24 |
+
search = __version__ = '{current_version}'
|
| 25 |
+
replace = __version__ = '{new_version}'
|
| 26 |
+
|
| 27 |
+
[bumpversion:file:conda/meta.yaml]
|
| 28 |
+
search = version = '{current_version}'
|
| 29 |
+
replace = version = '{new_version}'
|
| 30 |
+
|
| 31 |
+
[bdist_wheel]
|
| 32 |
+
universal = 1
|
| 33 |
+
|
| 34 |
+
[flake8]
|
| 35 |
+
convention = google
|
| 36 |
+
max-line-length = 99
|
| 37 |
+
exclude = docs, .tox, .git, __pycache__, .ipynb_checkpoints
|
| 38 |
+
extend-ignore = D107, # Missing docstring in __init__
|
| 39 |
+
D407, # Missing dashed underline after section
|
| 40 |
+
D417, # Missing argument descriptions in the docstring
|
| 41 |
+
SFS3, # String literal formatting using f-string.
|
| 42 |
+
VNE001 # Single letter variable names are not allowed
|
| 43 |
+
per-file-ignores =
|
| 44 |
+
ctgan/data.py:T001
|
| 45 |
+
|
| 46 |
+
[isort]
|
| 47 |
+
include_trailing_comment = True
|
| 48 |
+
line_length = 99
|
| 49 |
+
lines_between_types = 0
|
| 50 |
+
multi_line_output = 4
|
| 51 |
+
not_skip = __init__.py
|
| 52 |
+
use_parentheses = True
|
| 53 |
+
|
| 54 |
+
[aliases]
|
| 55 |
+
test = pytest
|
| 56 |
+
|
| 57 |
+
[tool:pytest]
|
| 58 |
+
collect_ignore = ['setup.py']
|
| 59 |
+
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/setup.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""The setup script."""
|
| 5 |
+
|
| 6 |
+
from setuptools import find_packages, setup
|
| 7 |
+
|
| 8 |
+
with open('README.md', encoding='utf-8') as readme_file:
|
| 9 |
+
readme = readme_file.read()
|
| 10 |
+
|
| 11 |
+
with open('HISTORY.md', encoding='utf-8') as history_file:
|
| 12 |
+
history = history_file.read()
|
| 13 |
+
|
| 14 |
+
install_requires = [
|
| 15 |
+
'packaging>=20,<22',
|
| 16 |
+
"numpy>=1.18.0,<1.20.0;python_version<'3.7'",
|
| 17 |
+
"numpy>=1.20.0,<2;python_version>='3.7'",
|
| 18 |
+
'pandas>=1.1.3,<2',
|
| 19 |
+
'scikit-learn>=0.24,<2',
|
| 20 |
+
'torch>=1.8.0,<2',
|
| 21 |
+
'torchvision>=0.9.0,<1',
|
| 22 |
+
'rdt>=0.6.2,<0.7',
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
setup_requires = [
|
| 26 |
+
'pytest-runner>=2.11.1',
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
tests_require = [
|
| 30 |
+
'pytest>=3.4.2',
|
| 31 |
+
'pytest-rerunfailures>=9.1.1,<10',
|
| 32 |
+
'pytest-cov>=2.6.0',
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
development_requires = [
|
| 36 |
+
# general
|
| 37 |
+
'pip>=9.0.1',
|
| 38 |
+
'bumpversion>=0.5.3,<0.6',
|
| 39 |
+
'watchdog>=0.8.3,<0.11',
|
| 40 |
+
|
| 41 |
+
# style check
|
| 42 |
+
'flake8>=3.7.7,<4',
|
| 43 |
+
'isort>=4.3.4,<5',
|
| 44 |
+
'dlint>=0.11.0,<0.12', # code security addon for flake8
|
| 45 |
+
'flake8-debugger>=4.0.0,<4.1',
|
| 46 |
+
'flake8-mock>=0.3,<0.4',
|
| 47 |
+
'flake8-mutable>=1.2.0,<1.3',
|
| 48 |
+
'flake8-absolute-import>=1.0,<2',
|
| 49 |
+
'flake8-multiline-containers>=0.0.18,<0.1',
|
| 50 |
+
'flake8-print>=4.0.0,<4.1',
|
| 51 |
+
'flake8-quotes>=3.3.0,<4',
|
| 52 |
+
'flake8-fixme>=1.1.1,<1.2',
|
| 53 |
+
'flake8-expression-complexity>=0.0.9,<0.1',
|
| 54 |
+
'flake8-eradicate>=1.1.0,<1.2',
|
| 55 |
+
'flake8-builtins>=1.5.3,<1.6',
|
| 56 |
+
'flake8-variables-names>=0.0.4,<0.1',
|
| 57 |
+
'pandas-vet>=0.2.2,<0.3',
|
| 58 |
+
'flake8-comprehensions>=3.6.1,<3.7',
|
| 59 |
+
'dlint>=0.11.0,<0.12',
|
| 60 |
+
'flake8-docstrings>=1.5.0,<2',
|
| 61 |
+
'flake8-sfs>=0.0.3,<0.1',
|
| 62 |
+
'flake8-pytest-style>=1.5.0,<2',
|
| 63 |
+
|
| 64 |
+
# fix style issues
|
| 65 |
+
'autoflake>=1.1,<2',
|
| 66 |
+
'autopep8>=1.4.3,<1.6',
|
| 67 |
+
|
| 68 |
+
# distribute on PyPI
|
| 69 |
+
'twine>=1.10.0,<4',
|
| 70 |
+
'wheel>=0.30.0',
|
| 71 |
+
|
| 72 |
+
# Advanced testing
|
| 73 |
+
'coverage>=4.5.1,<6',
|
| 74 |
+
'tox>=2.9.1,<4',
|
| 75 |
+
|
| 76 |
+
'invoke',
|
| 77 |
+
]
|
| 78 |
+
|
| 79 |
+
setup(
|
| 80 |
+
author='MIT Data To AI Lab',
|
| 81 |
+
author_email='dailabmit@gmail.com',
|
| 82 |
+
classifiers=[
|
| 83 |
+
'Development Status :: 2 - Pre-Alpha',
|
| 84 |
+
'Intended Audience :: Developers',
|
| 85 |
+
'License :: OSI Approved :: MIT License',
|
| 86 |
+
'Natural Language :: English',
|
| 87 |
+
'Programming Language :: Python :: 3',
|
| 88 |
+
'Programming Language :: Python :: 3.6',
|
| 89 |
+
'Programming Language :: Python :: 3.7',
|
| 90 |
+
'Programming Language :: Python :: 3.8',
|
| 91 |
+
'Programming Language :: Python :: 3.9',
|
| 92 |
+
],
|
| 93 |
+
description='Conditional GAN for Tabular Data',
|
| 94 |
+
entry_points={
|
| 95 |
+
'console_scripts': [
|
| 96 |
+
'ctgan=ctgan.__main__:main'
|
| 97 |
+
],
|
| 98 |
+
},
|
| 99 |
+
extras_require={
|
| 100 |
+
'test': tests_require,
|
| 101 |
+
'dev': development_requires + tests_require,
|
| 102 |
+
},
|
| 103 |
+
install_package_data=True,
|
| 104 |
+
install_requires=install_requires,
|
| 105 |
+
license='MIT license',
|
| 106 |
+
long_description=readme + '\n\n' + history,
|
| 107 |
+
long_description_content_type='text/markdown',
|
| 108 |
+
include_package_data=True,
|
| 109 |
+
keywords='ctgan CTGAN',
|
| 110 |
+
name='ctgan',
|
| 111 |
+
packages=find_packages(include=['ctgan', 'ctgan.*']),
|
| 112 |
+
python_requires='>=3.6,<3.10',
|
| 113 |
+
setup_requires=setup_requires,
|
| 114 |
+
test_suite='tests',
|
| 115 |
+
tests_require=tests_require,
|
| 116 |
+
url='https://github.com/sdv-dev/CTGAN',
|
| 117 |
+
version='0.5.2.dev0',
|
| 118 |
+
zip_safe=False,
|
| 119 |
+
)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tasks.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import glob
|
| 2 |
+
import operator
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import platform
|
| 6 |
+
import shutil
|
| 7 |
+
import stat
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
from invoke import task
|
| 11 |
+
|
| 12 |
+
COMPARISONS = {
|
| 13 |
+
'>=': operator.ge,
|
| 14 |
+
'>': operator.gt,
|
| 15 |
+
'<': operator.lt,
|
| 16 |
+
'<=': operator.le
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@task
|
| 21 |
+
def check_dependencies(c):
|
| 22 |
+
c.run('python -m pip check')
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@task
|
| 26 |
+
def unit(c):
|
| 27 |
+
c.run('python -m pytest ./tests/unit --cov=ctgan --cov-report=xml')
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@task
|
| 31 |
+
def integration(c):
|
| 32 |
+
c.run('python -m pytest ./tests/integration --reruns 3')
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@task
|
| 36 |
+
def readme(c):
|
| 37 |
+
test_path = Path('tests/readme_test')
|
| 38 |
+
if test_path.exists() and test_path.is_dir():
|
| 39 |
+
shutil.rmtree(test_path)
|
| 40 |
+
|
| 41 |
+
cwd = os.getcwd()
|
| 42 |
+
os.makedirs(test_path, exist_ok=True)
|
| 43 |
+
shutil.copy('README.md', test_path / 'README.md')
|
| 44 |
+
os.chdir(test_path)
|
| 45 |
+
c.run('rundoc run --single-session python3 -t python3 README.md')
|
| 46 |
+
os.chdir(cwd)
|
| 47 |
+
shutil.rmtree(test_path)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _validate_python_version(line):
|
| 51 |
+
python_version_match = re.search(r"python_version(<=?|>=?)\'(\d\.?)+\'", line)
|
| 52 |
+
if python_version_match:
|
| 53 |
+
python_version = python_version_match.group(0)
|
| 54 |
+
comparison = re.search(r'(>=?|<=?)', python_version).group(0)
|
| 55 |
+
version_number = python_version.split(comparison)[-1].replace("'", "")
|
| 56 |
+
comparison_function = COMPARISONS[comparison]
|
| 57 |
+
return comparison_function(platform.python_version(), version_number)
|
| 58 |
+
|
| 59 |
+
return True
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@task
|
| 63 |
+
def install_minimum(c):
|
| 64 |
+
with open('setup.py', 'r') as setup_py:
|
| 65 |
+
lines = setup_py.read().splitlines()
|
| 66 |
+
|
| 67 |
+
versions = []
|
| 68 |
+
started = False
|
| 69 |
+
for line in lines:
|
| 70 |
+
if started:
|
| 71 |
+
if line == ']':
|
| 72 |
+
started = False
|
| 73 |
+
continue
|
| 74 |
+
|
| 75 |
+
line = line.strip()
|
| 76 |
+
if _validate_python_version(line):
|
| 77 |
+
requirement = re.match(r'[^>]*', line).group(0)
|
| 78 |
+
requirement = re.sub(r"""['",]""", '', requirement)
|
| 79 |
+
version = re.search(r'>=?[^(,|#)]*', line).group(0)
|
| 80 |
+
if version:
|
| 81 |
+
version = re.sub(r'>=?', '==', version)
|
| 82 |
+
version = re.sub(r"""['",]""", '', version)
|
| 83 |
+
requirement += version
|
| 84 |
+
|
| 85 |
+
versions.append(requirement)
|
| 86 |
+
|
| 87 |
+
elif (line.startswith('install_requires = [') or
|
| 88 |
+
line.startswith('pomegranate_requires = [')):
|
| 89 |
+
started = True
|
| 90 |
+
|
| 91 |
+
c.run(f'python -m pip install {" ".join(versions)}')
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
@task
|
| 95 |
+
def minimum(c):
|
| 96 |
+
install_minimum(c)
|
| 97 |
+
check_dependencies(c)
|
| 98 |
+
unit(c)
|
| 99 |
+
integration(c)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@task
|
| 103 |
+
def lint(c):
|
| 104 |
+
check_dependencies(c)
|
| 105 |
+
c.run('flake8 ctgan')
|
| 106 |
+
c.run('flake8 tests --ignore=D101')
|
| 107 |
+
c.run('isort -c --recursive ctgan tests')
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def remove_readonly(func, path, _):
|
| 111 |
+
"Clear the readonly bit and reattempt the removal"
|
| 112 |
+
os.chmod(path, stat.S_IWRITE)
|
| 113 |
+
func(path)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@task
|
| 117 |
+
def rmdir(c, path):
|
| 118 |
+
try:
|
| 119 |
+
shutil.rmtree(path, onerror=remove_readonly)
|
| 120 |
+
except PermissionError:
|
| 121 |
+
pass
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_ctgan.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""Integration tests for ctgan.
|
| 5 |
+
|
| 6 |
+
These tests only ensure that the software does not crash and that
|
| 7 |
+
the API works as expected in terms of input and output data formats,
|
| 8 |
+
but correctness of the data values and the internal behavior of the
|
| 9 |
+
model are not checked.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import tempfile as tf
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pandas as pd
|
| 16 |
+
import pytest
|
| 17 |
+
|
| 18 |
+
from ctgan.synthesizers.ctgan import CTGANSynthesizer
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def test_ctgan_no_categoricals():
|
| 22 |
+
"""Test the CTGANSynthesizer with no categorical values."""
|
| 23 |
+
data = pd.DataFrame({
|
| 24 |
+
'continuous': np.random.random(1000)
|
| 25 |
+
})
|
| 26 |
+
|
| 27 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 28 |
+
ctgan.fit(data, [])
|
| 29 |
+
|
| 30 |
+
sampled = ctgan.sample(100)
|
| 31 |
+
|
| 32 |
+
assert sampled.shape == (100, 1)
|
| 33 |
+
assert isinstance(sampled, pd.DataFrame)
|
| 34 |
+
assert set(sampled.columns) == {'continuous'}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_ctgan_dataframe():
|
| 38 |
+
"""Test the CTGANSynthesizer when passed a dataframe."""
|
| 39 |
+
data = pd.DataFrame({
|
| 40 |
+
'continuous': np.random.random(100),
|
| 41 |
+
'discrete': np.random.choice(['a', 'b', 'c'], 100)
|
| 42 |
+
})
|
| 43 |
+
discrete_columns = ['discrete']
|
| 44 |
+
|
| 45 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 46 |
+
ctgan.fit(data, discrete_columns)
|
| 47 |
+
|
| 48 |
+
sampled = ctgan.sample(100)
|
| 49 |
+
|
| 50 |
+
assert sampled.shape == (100, 2)
|
| 51 |
+
assert isinstance(sampled, pd.DataFrame)
|
| 52 |
+
assert set(sampled.columns) == {'continuous', 'discrete'}
|
| 53 |
+
assert set(sampled['discrete'].unique()) == {'a', 'b', 'c'}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_ctgan_numpy():
|
| 57 |
+
"""Test the CTGANSynthesizer when passed a numpy array."""
|
| 58 |
+
data = pd.DataFrame({
|
| 59 |
+
'continuous': np.random.random(100),
|
| 60 |
+
'discrete': np.random.choice(['a', 'b', 'c'], 100)
|
| 61 |
+
})
|
| 62 |
+
discrete_columns = [1]
|
| 63 |
+
|
| 64 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 65 |
+
ctgan.fit(data.to_numpy(), discrete_columns)
|
| 66 |
+
|
| 67 |
+
sampled = ctgan.sample(100)
|
| 68 |
+
|
| 69 |
+
assert sampled.shape == (100, 2)
|
| 70 |
+
assert isinstance(sampled, np.ndarray)
|
| 71 |
+
assert set(np.unique(sampled[:, 1])) == {'a', 'b', 'c'}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_log_frequency():
|
| 75 |
+
"""Test the CTGANSynthesizer with no `log_frequency` set to False."""
|
| 76 |
+
data = pd.DataFrame({
|
| 77 |
+
'continuous': np.random.random(1000),
|
| 78 |
+
'discrete': np.repeat(['a', 'b', 'c'], [950, 25, 25])
|
| 79 |
+
})
|
| 80 |
+
|
| 81 |
+
discrete_columns = ['discrete']
|
| 82 |
+
|
| 83 |
+
ctgan = CTGANSynthesizer(epochs=100)
|
| 84 |
+
ctgan.fit(data, discrete_columns)
|
| 85 |
+
|
| 86 |
+
sampled = ctgan.sample(10000)
|
| 87 |
+
counts = sampled['discrete'].value_counts()
|
| 88 |
+
assert counts['a'] < 6500
|
| 89 |
+
|
| 90 |
+
ctgan = CTGANSynthesizer(log_frequency=False, epochs=100)
|
| 91 |
+
ctgan.fit(data, discrete_columns)
|
| 92 |
+
|
| 93 |
+
sampled = ctgan.sample(10000)
|
| 94 |
+
counts = sampled['discrete'].value_counts()
|
| 95 |
+
assert counts['a'] > 9000
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_categorical_nan():
|
| 99 |
+
"""Test the CTGANSynthesizer with no categorical values."""
|
| 100 |
+
data = pd.DataFrame({
|
| 101 |
+
'continuous': np.random.random(30),
|
| 102 |
+
# This must be a list (not a np.array) or NaN will be cast to a string.
|
| 103 |
+
'discrete': [np.nan, 'b', 'c'] * 10
|
| 104 |
+
})
|
| 105 |
+
discrete_columns = ['discrete']
|
| 106 |
+
|
| 107 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 108 |
+
ctgan.fit(data, discrete_columns)
|
| 109 |
+
|
| 110 |
+
sampled = ctgan.sample(100)
|
| 111 |
+
|
| 112 |
+
assert sampled.shape == (100, 2)
|
| 113 |
+
assert isinstance(sampled, pd.DataFrame)
|
| 114 |
+
assert set(sampled.columns) == {'continuous', 'discrete'}
|
| 115 |
+
|
| 116 |
+
# since np.nan != np.nan, we need to be careful here
|
| 117 |
+
values = set(sampled['discrete'].unique())
|
| 118 |
+
assert len(values) == 3
|
| 119 |
+
assert any(pd.isna(x) for x in values)
|
| 120 |
+
assert {'b', 'c'}.issubset(values)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def test_synthesizer_sample():
|
| 124 |
+
"""Test the CTGANSynthesizer samples the correct datatype."""
|
| 125 |
+
data = pd.DataFrame({
|
| 126 |
+
'discrete': np.random.choice(['a', 'b', 'c'], 100)
|
| 127 |
+
})
|
| 128 |
+
discrete_columns = ['discrete']
|
| 129 |
+
|
| 130 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 131 |
+
ctgan.fit(data, discrete_columns)
|
| 132 |
+
|
| 133 |
+
samples = ctgan.sample(1000, 'discrete', 'a')
|
| 134 |
+
assert isinstance(samples, pd.DataFrame)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_save_load():
|
| 138 |
+
"""Test the CTGANSynthesizer load/save methods."""
|
| 139 |
+
data = pd.DataFrame({
|
| 140 |
+
'continuous': np.random.random(100),
|
| 141 |
+
'discrete': np.random.choice(['a', 'b', 'c'], 100)
|
| 142 |
+
})
|
| 143 |
+
discrete_columns = ['discrete']
|
| 144 |
+
|
| 145 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 146 |
+
ctgan.fit(data, discrete_columns)
|
| 147 |
+
|
| 148 |
+
with tf.TemporaryDirectory() as temporary_directory:
|
| 149 |
+
ctgan.save(temporary_directory + 'test_tvae.pkl')
|
| 150 |
+
ctgan = CTGANSynthesizer.load(temporary_directory + 'test_tvae.pkl')
|
| 151 |
+
|
| 152 |
+
sampled = ctgan.sample(1000)
|
| 153 |
+
assert set(sampled.columns) == {'continuous', 'discrete'}
|
| 154 |
+
assert set(sampled['discrete'].unique()) == {'a', 'b', 'c'}
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_wrong_discrete_columns_dataframe():
|
| 158 |
+
"""Test the CTGANSynthesizer correctly crashes when passed non-existing discrete columns."""
|
| 159 |
+
data = pd.DataFrame({
|
| 160 |
+
'discrete': ['a', 'b']
|
| 161 |
+
})
|
| 162 |
+
discrete_columns = ['b', 'c']
|
| 163 |
+
|
| 164 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 165 |
+
with pytest.raises(ValueError, match="Invalid columns found: {'.*', '.*'}"):
|
| 166 |
+
ctgan.fit(data, discrete_columns)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def test_wrong_discrete_columns_numpy():
|
| 170 |
+
"""Test the CTGANSynthesizer correctly crashes when passed non-existing discrete columns."""
|
| 171 |
+
data = pd.DataFrame({
|
| 172 |
+
'discrete': ['a', 'b']
|
| 173 |
+
})
|
| 174 |
+
discrete_columns = [0, 1]
|
| 175 |
+
|
| 176 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 177 |
+
with pytest.raises(ValueError, match=r'Invalid columns found: \[1\]'):
|
| 178 |
+
ctgan.fit(data.to_numpy(), discrete_columns)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def test_wrong_sampling_conditions():
|
| 182 |
+
"""Test the CTGANSynthesizer correctly crashes when passed incorrect sampling conditions."""
|
| 183 |
+
data = pd.DataFrame({
|
| 184 |
+
'continuous': np.random.random(100),
|
| 185 |
+
'discrete': np.random.choice(['a', 'b', 'c'], 100)
|
| 186 |
+
})
|
| 187 |
+
discrete_columns = ['discrete']
|
| 188 |
+
|
| 189 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 190 |
+
ctgan.fit(data, discrete_columns)
|
| 191 |
+
|
| 192 |
+
with pytest.raises(ValueError, match="The column_name `cardinal` doesn't exist in the data."):
|
| 193 |
+
ctgan.sample(1, 'cardinal', "doesn't matter")
|
| 194 |
+
|
| 195 |
+
with pytest.raises(ValueError): # noqa: RDT currently incorrectly raises a tuple instead of a string
|
| 196 |
+
ctgan.sample(1, 'discrete', 'd')
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def test_fixed_random_seed():
|
| 200 |
+
"""Test the CTGANSynthesizer with a fixed seed.
|
| 201 |
+
|
| 202 |
+
Expect that when the random seed is reset with the same seed, the same sequence
|
| 203 |
+
of data will be produced. Expect that the data generated with the seed is
|
| 204 |
+
different than randomly sampled data.
|
| 205 |
+
"""
|
| 206 |
+
# Setup
|
| 207 |
+
data = pd.DataFrame({
|
| 208 |
+
'continuous': np.random.random(100),
|
| 209 |
+
'discrete': np.random.choice(['a', 'b', 'c'], 100)
|
| 210 |
+
})
|
| 211 |
+
discrete_columns = ['discrete']
|
| 212 |
+
|
| 213 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 214 |
+
|
| 215 |
+
# Run
|
| 216 |
+
ctgan.fit(data, discrete_columns)
|
| 217 |
+
sampled_random = ctgan.sample(10)
|
| 218 |
+
|
| 219 |
+
ctgan.set_random_state(0)
|
| 220 |
+
sampled_0_0 = ctgan.sample(10)
|
| 221 |
+
sampled_0_1 = ctgan.sample(10)
|
| 222 |
+
|
| 223 |
+
ctgan.set_random_state(0)
|
| 224 |
+
sampled_1_0 = ctgan.sample(10)
|
| 225 |
+
sampled_1_1 = ctgan.sample(10)
|
| 226 |
+
|
| 227 |
+
# Assert
|
| 228 |
+
assert not np.array_equal(sampled_random, sampled_0_0)
|
| 229 |
+
assert not np.array_equal(sampled_random, sampled_0_1)
|
| 230 |
+
np.testing.assert_array_equal(sampled_0_0, sampled_1_0)
|
| 231 |
+
np.testing.assert_array_equal(sampled_0_1, sampled_1_1)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# Below are CTGAN tests that should be implemented in the future
|
| 235 |
+
def test_continuous():
|
| 236 |
+
"""Test training the CTGAN synthesizer on a continuous dataset."""
|
| 237 |
+
# assert the distribution of the samples is close to the distribution of the data
|
| 238 |
+
# using kstest:
|
| 239 |
+
# - uniform (assert p-value > 0.05)
|
| 240 |
+
# - gaussian (assert p-value > 0.05)
|
| 241 |
+
# - inversely correlated (assert correlation < 0)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def test_categorical():
|
| 245 |
+
"""Test training the CTGAN synthesizer on a categorical dataset."""
|
| 246 |
+
# assert the distribution of the samples is close to the distribution of the data
|
| 247 |
+
# using cstest:
|
| 248 |
+
# - uniform (assert p-value > 0.05)
|
| 249 |
+
# - very skewed / biased? (assert p-value > 0.05)
|
| 250 |
+
# - inversely correlated (assert correlation < 0)
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def test_categorical_log_frequency():
|
| 254 |
+
"""Test training the CTGAN synthesizer on a small categorical dataset."""
|
| 255 |
+
# assert the distribution of the samples is close to the distribution of the data
|
| 256 |
+
# using cstest:
|
| 257 |
+
# - uniform (assert p-value > 0.05)
|
| 258 |
+
# - very skewed / biased? (assert p-value > 0.05)
|
| 259 |
+
# - inversely correlated (assert correlation < 0)
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def test_mixed():
|
| 263 |
+
"""Test training the CTGAN synthesizer on a small mixed-type dataset."""
|
| 264 |
+
# assert the distribution of the samples is close to the distribution of the data
|
| 265 |
+
# using a kstest for continuous + a cstest for categorical.
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def test_conditional():
|
| 269 |
+
"""Test training the CTGAN synthesizer and sampling conditioned on a categorical."""
|
| 270 |
+
# verify that conditioning increases the likelihood of getting a sample with the specified
|
| 271 |
+
# categorical value
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def test_batch_size_pack_size():
|
| 275 |
+
"""Test that if batch size is not a multiple of pack size, it raises a sane error."""
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/synthesizer/test_tvae.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""Integration tests for tvae.
|
| 5 |
+
|
| 6 |
+
These tests only ensure that the software does not crash and that
|
| 7 |
+
the API works as expected in terms of input and output data formats,
|
| 8 |
+
but correctness of the data values and the internal behavior of the
|
| 9 |
+
model are not checked.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import numpy as np
|
| 13 |
+
import pandas as pd
|
| 14 |
+
from sklearn import datasets
|
| 15 |
+
|
| 16 |
+
from ctgan.synthesizers.tvae import TVAESynthesizer
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_tvae(tmpdir):
|
| 20 |
+
"""Test the TVAESynthesizer load/save methods."""
|
| 21 |
+
iris = datasets.load_iris()
|
| 22 |
+
data = pd.DataFrame(iris.data, columns=iris.feature_names)
|
| 23 |
+
data['class'] = pd.Series(iris.target).map(iris.target_names.__getitem__)
|
| 24 |
+
|
| 25 |
+
tvae = TVAESynthesizer(epochs=10)
|
| 26 |
+
tvae.fit(data, ['class'])
|
| 27 |
+
|
| 28 |
+
path = str(tmpdir / 'test_tvae.pkl')
|
| 29 |
+
tvae.save(path)
|
| 30 |
+
tvae = TVAESynthesizer.load(path)
|
| 31 |
+
|
| 32 |
+
sampled = tvae.sample(100)
|
| 33 |
+
|
| 34 |
+
assert sampled.shape == (100, 5)
|
| 35 |
+
assert isinstance(sampled, pd.DataFrame)
|
| 36 |
+
assert set(sampled.columns) == set(data.columns)
|
| 37 |
+
assert set(sampled.dtypes) == set(data.dtypes)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def test_drop_last_false():
|
| 41 |
+
"""Test the TVAESynthesizer predicts the correct values."""
|
| 42 |
+
data = pd.DataFrame({
|
| 43 |
+
'1': ['a', 'b', 'c'] * 150,
|
| 44 |
+
'2': ['a', 'b', 'c'] * 150
|
| 45 |
+
})
|
| 46 |
+
|
| 47 |
+
tvae = TVAESynthesizer(epochs=300)
|
| 48 |
+
tvae.fit(data, ['1', '2'])
|
| 49 |
+
|
| 50 |
+
sampled = tvae.sample(100)
|
| 51 |
+
correct = 0
|
| 52 |
+
for _, row in sampled.iterrows():
|
| 53 |
+
if row['1'] == row['2']:
|
| 54 |
+
correct += 1
|
| 55 |
+
|
| 56 |
+
assert correct >= 95
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# TVAE tests that should be implemented in the future.
|
| 60 |
+
def test_continuous():
|
| 61 |
+
"""Test training the TVAE synthesizer on a small continuous dataset."""
|
| 62 |
+
# verify that the distribution of the samples is close to the distribution of the data
|
| 63 |
+
# using a kstest.
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def test_categorical():
|
| 67 |
+
"""Test training the TVAE synthesizer on a small categorical dataset."""
|
| 68 |
+
# verify that the distribution of the samples is close to the distribution of the data
|
| 69 |
+
# using a cstest.
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_mixed():
|
| 73 |
+
"""Test training the TVAE synthesizer on a small mixed-type dataset."""
|
| 74 |
+
# verify that the distribution of the samples is close to the distribution of the data
|
| 75 |
+
# using a kstest for continuous + a cstest for categorical.
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test__loss_function():
|
| 79 |
+
"""Test the TVAESynthesizer produces average values similar to the training data."""
|
| 80 |
+
data = pd.DataFrame({
|
| 81 |
+
'1': [float(i) for i in range(1000)],
|
| 82 |
+
'2': [float(2 * i) for i in range(1000)]
|
| 83 |
+
})
|
| 84 |
+
|
| 85 |
+
tvae = TVAESynthesizer(epochs=300)
|
| 86 |
+
tvae.fit(data)
|
| 87 |
+
|
| 88 |
+
num_samples = 1000
|
| 89 |
+
sampled = tvae.sample(num_samples)
|
| 90 |
+
error = 0
|
| 91 |
+
for _, row in sampled.iterrows():
|
| 92 |
+
error += abs(2 * row['1'] - row['2'])
|
| 93 |
+
|
| 94 |
+
avg_error = error / num_samples
|
| 95 |
+
|
| 96 |
+
assert avg_error < 400
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def test_fixed_random_seed():
|
| 100 |
+
"""Test the TVAESynthesizer with a fixed seed.
|
| 101 |
+
|
| 102 |
+
Expect that when the random seed is reset with the same seed, the same sequence
|
| 103 |
+
of data will be produced. Expect that the data generated with the seed is
|
| 104 |
+
different than randomly sampled data.
|
| 105 |
+
"""
|
| 106 |
+
# Setup
|
| 107 |
+
data = pd.DataFrame({
|
| 108 |
+
'continuous': np.random.random(100),
|
| 109 |
+
'discrete': np.random.choice(['a', 'b', 'c'], 100)
|
| 110 |
+
})
|
| 111 |
+
discrete_columns = ['discrete']
|
| 112 |
+
|
| 113 |
+
tvae = TVAESynthesizer(epochs=1)
|
| 114 |
+
|
| 115 |
+
# Run
|
| 116 |
+
tvae.fit(data, discrete_columns)
|
| 117 |
+
sampled_random = tvae.sample(10)
|
| 118 |
+
|
| 119 |
+
tvae.set_random_state(0)
|
| 120 |
+
sampled_0_0 = tvae.sample(10)
|
| 121 |
+
sampled_0_1 = tvae.sample(10)
|
| 122 |
+
|
| 123 |
+
tvae.set_random_state(0)
|
| 124 |
+
sampled_1_0 = tvae.sample(10)
|
| 125 |
+
sampled_1_1 = tvae.sample(10)
|
| 126 |
+
|
| 127 |
+
# Assert
|
| 128 |
+
assert not np.array_equal(sampled_random, sampled_0_0)
|
| 129 |
+
assert not np.array_equal(sampled_random, sampled_0_1)
|
| 130 |
+
np.testing.assert_array_equal(sampled_0_0, sampled_1_0)
|
| 131 |
+
np.testing.assert_array_equal(sampled_0_1, sampled_1_1)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/integration/test_data_transformer.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Data transformer intergration testing module."""
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
# Data Transformer tests that should be implemented in the future.
|
| 5 |
+
def test_constant():
|
| 6 |
+
"""Test transforming a dataframe containing constant values."""
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def test_df_continuous():
|
| 10 |
+
"""Test transforming a dataframe containing only continuous values."""
|
| 11 |
+
# validate output ranges [0, 1]
|
| 12 |
+
# validate output shape (# samples, # output dims)
|
| 13 |
+
# validate that forward transform is **not** deterministic
|
| 14 |
+
# make sure it can be inverted
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def test_df_categorical():
|
| 18 |
+
"""Test transforming a dataframe containing only categorical values."""
|
| 19 |
+
# validate output ranges [0, 1]
|
| 20 |
+
# validate output shape (# samples, # output dims)
|
| 21 |
+
# validate that forward transform is deterministic
|
| 22 |
+
# make sure it can be inverted
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_df_mixed():
|
| 26 |
+
"""Test transforming a dataframe containing mixed data types."""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_df_mixed_nan():
|
| 30 |
+
"""Test transforming a dataframe containing mixed data types + NaN for categoricals."""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_np_continuous():
|
| 34 |
+
"""Test transforming a np.array containing only continuous values."""
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_np_categorical():
|
| 38 |
+
"""Test transforming a np.array containing only categorical values."""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def test_np_mixed():
|
| 42 |
+
"""Test transforming a np.array containing mixed data types."""
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""Unit testing module."""
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
"""CTGANSynthesizer testing module."""
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_base.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
"""BaseSynthesizer unit testing module."""
|
| 3 |
+
|
| 4 |
+
from unittest.mock import MagicMock, call, patch
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import torch
|
| 8 |
+
|
| 9 |
+
from ctgan.synthesizers.base import BaseSynthesizer, random_state
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@patch('ctgan.synthesizers.base.torch')
|
| 13 |
+
@patch('ctgan.synthesizers.base.np.random')
|
| 14 |
+
def test_valid_random_state(random_mock, torch_mock):
|
| 15 |
+
"""Test the ``random_state`` attribute with a valid random state.
|
| 16 |
+
|
| 17 |
+
Expect that the decorated function uses the random_state attribute.
|
| 18 |
+
"""
|
| 19 |
+
# Setup
|
| 20 |
+
my_function = MagicMock()
|
| 21 |
+
instance = MagicMock()
|
| 22 |
+
|
| 23 |
+
random_state_mock = MagicMock()
|
| 24 |
+
random_state_mock.get_state.return_value = 'desired numpy state'
|
| 25 |
+
torch_generator_mock = MagicMock()
|
| 26 |
+
torch_generator_mock.get_state.return_value = 'desired torch state'
|
| 27 |
+
instance.random_states = (random_state_mock, torch_generator_mock)
|
| 28 |
+
|
| 29 |
+
args = {'some', 'args'}
|
| 30 |
+
kwargs = {'keyword': 'value'}
|
| 31 |
+
|
| 32 |
+
random_mock.RandomState.return_value = random_state_mock
|
| 33 |
+
random_mock.get_state.return_value = 'random state'
|
| 34 |
+
torch_mock.Generator.return_value = torch_generator_mock
|
| 35 |
+
torch_mock.get_rng_state.return_value = 'torch random state'
|
| 36 |
+
|
| 37 |
+
# Run
|
| 38 |
+
decorated_function = random_state(my_function)
|
| 39 |
+
decorated_function(instance, *args, **kwargs)
|
| 40 |
+
|
| 41 |
+
# Assert
|
| 42 |
+
my_function.assert_called_once_with(instance, *args, **kwargs)
|
| 43 |
+
|
| 44 |
+
instance.assert_not_called
|
| 45 |
+
assert random_mock.get_state.call_count == 2
|
| 46 |
+
assert torch_mock.get_rng_state.call_count == 2
|
| 47 |
+
random_mock.RandomState.assert_has_calls(
|
| 48 |
+
[call().get_state(), call(), call().set_state('random state')])
|
| 49 |
+
random_mock.set_state.assert_has_calls([call('desired numpy state'), call('random state')])
|
| 50 |
+
torch_mock.set_rng_state.assert_has_calls(
|
| 51 |
+
[call('desired torch state'), call('torch random state')])
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@patch('ctgan.synthesizers.base.torch')
|
| 55 |
+
@patch('ctgan.synthesizers.base.np.random')
|
| 56 |
+
def test_no_random_seed(random_mock, torch_mock):
|
| 57 |
+
"""Test the ``random_state`` attribute with no random state.
|
| 58 |
+
|
| 59 |
+
Expect that the decorated function calls the original function
|
| 60 |
+
when there is no random state.
|
| 61 |
+
"""
|
| 62 |
+
# Setup
|
| 63 |
+
my_function = MagicMock()
|
| 64 |
+
instance = MagicMock()
|
| 65 |
+
instance.random_states = None
|
| 66 |
+
|
| 67 |
+
args = {'some', 'args'}
|
| 68 |
+
kwargs = {'keyword': 'value'}
|
| 69 |
+
|
| 70 |
+
# Run
|
| 71 |
+
decorated_function = random_state(my_function)
|
| 72 |
+
decorated_function(instance, *args, **kwargs)
|
| 73 |
+
|
| 74 |
+
# Assert
|
| 75 |
+
my_function.assert_called_once_with(instance, *args, **kwargs)
|
| 76 |
+
|
| 77 |
+
instance.assert_not_called
|
| 78 |
+
random_mock.get_state.assert_not_called()
|
| 79 |
+
random_mock.RandomState.assert_not_called()
|
| 80 |
+
random_mock.set_state.assert_not_called()
|
| 81 |
+
torch_mock.get_rng_state.assert_not_called()
|
| 82 |
+
torch_mock.Generator.assert_not_called()
|
| 83 |
+
torch_mock.set_rng_state.assert_not_called()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class TestBaseSynthesizer:
|
| 87 |
+
|
| 88 |
+
def test_set_random_state(self):
|
| 89 |
+
"""Test ``set_random_state`` works as expected."""
|
| 90 |
+
# Setup
|
| 91 |
+
instance = BaseSynthesizer()
|
| 92 |
+
|
| 93 |
+
# Run
|
| 94 |
+
instance.set_random_state(3)
|
| 95 |
+
|
| 96 |
+
# Assert
|
| 97 |
+
assert isinstance(instance.random_states, tuple)
|
| 98 |
+
assert isinstance(instance.random_states[0], np.random.RandomState)
|
| 99 |
+
assert isinstance(instance.random_states[1], torch.Generator)
|
| 100 |
+
|
| 101 |
+
def test_set_random_state_with_none(self):
|
| 102 |
+
"""Test ``set_random_state`` with None."""
|
| 103 |
+
# Setup
|
| 104 |
+
instance = BaseSynthesizer()
|
| 105 |
+
|
| 106 |
+
# Run and assert
|
| 107 |
+
instance.set_random_state(3)
|
| 108 |
+
assert instance.random_states is not None
|
| 109 |
+
|
| 110 |
+
instance.set_random_state(None)
|
| 111 |
+
assert instance.random_states is None
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_ctgan.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CTGANSynthesizer unit testing module."""
|
| 2 |
+
|
| 3 |
+
from unittest import TestCase
|
| 4 |
+
from unittest.mock import Mock
|
| 5 |
+
|
| 6 |
+
import pandas as pd
|
| 7 |
+
import pytest
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from ctgan.data_transformer import SpanInfo
|
| 11 |
+
from ctgan.synthesizers.ctgan import CTGANSynthesizer, Discriminator, Generator, Residual
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class TestDiscriminator(TestCase):
|
| 15 |
+
|
| 16 |
+
def test___init__(self):
|
| 17 |
+
"""Test `__init__` for a generic case.
|
| 18 |
+
|
| 19 |
+
Make sure 'self.seq' has same length as 3*`discriminator_dim` + 1.
|
| 20 |
+
|
| 21 |
+
Setup:
|
| 22 |
+
- Create Discriminator
|
| 23 |
+
|
| 24 |
+
Input:
|
| 25 |
+
- input_dim = positive integer
|
| 26 |
+
- discriminator_dim = list of integers
|
| 27 |
+
- pack = positive integer
|
| 28 |
+
|
| 29 |
+
Output:
|
| 30 |
+
- None
|
| 31 |
+
|
| 32 |
+
Side Effects:
|
| 33 |
+
- Set `self.seq`, `self.pack` and `self.packdim`
|
| 34 |
+
"""
|
| 35 |
+
discriminator_dim = [1, 2, 3]
|
| 36 |
+
discriminator = Discriminator(input_dim=50, discriminator_dim=discriminator_dim, pac=7)
|
| 37 |
+
|
| 38 |
+
assert discriminator.pac == 7
|
| 39 |
+
assert discriminator.pacdim == 350
|
| 40 |
+
assert len(discriminator.seq) == 3 * len(discriminator_dim) + 1
|
| 41 |
+
|
| 42 |
+
def test_forward(self):
|
| 43 |
+
"""Test `test_forward` for a generic case.
|
| 44 |
+
|
| 45 |
+
Check that the output shapes are correct.
|
| 46 |
+
We can also test that all parameters have a gradient attached to them
|
| 47 |
+
by running `encoder.parameters()`. To do that, we just need to use `loss.backward()`
|
| 48 |
+
for some loss, like `loss = torch.mean(output)`. Notice that the input_dim = input_size.
|
| 49 |
+
|
| 50 |
+
Setup:
|
| 51 |
+
- initialize with input_size, discriminator_dim, pac
|
| 52 |
+
- Create random tensor as input
|
| 53 |
+
|
| 54 |
+
Input:
|
| 55 |
+
- input = random tensor of shape (N, input_size)
|
| 56 |
+
|
| 57 |
+
Output:
|
| 58 |
+
- tensor of shape (N/pac, 1)
|
| 59 |
+
"""
|
| 60 |
+
discriminator = Discriminator(input_dim=50, discriminator_dim=[100, 200, 300], pac=7)
|
| 61 |
+
output = discriminator(torch.randn(70, 50))
|
| 62 |
+
assert output.shape == (10, 1)
|
| 63 |
+
|
| 64 |
+
# Check to make sure no gradients attached
|
| 65 |
+
for parameter in discriminator.parameters():
|
| 66 |
+
assert parameter.grad is None
|
| 67 |
+
|
| 68 |
+
# Backpropagate
|
| 69 |
+
output.mean().backward()
|
| 70 |
+
|
| 71 |
+
# Check to make sure all parameters have gradients
|
| 72 |
+
for parameter in discriminator.parameters():
|
| 73 |
+
assert parameter.grad is not None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class TestResidual(TestCase):
|
| 77 |
+
|
| 78 |
+
def test_forward(self):
|
| 79 |
+
"""Test `test_forward` for a generic case.
|
| 80 |
+
|
| 81 |
+
Check that the output shapes are correct.
|
| 82 |
+
We can also test that all parameters have a gradient attached to them
|
| 83 |
+
by running `encoder.parameters()`. To do that, we just need to use `loss.backward()`
|
| 84 |
+
for some loss, like `loss = torch.mean(output)`.
|
| 85 |
+
|
| 86 |
+
Setup:
|
| 87 |
+
- initialize with input_size, output_size
|
| 88 |
+
- Create random tensor as input
|
| 89 |
+
|
| 90 |
+
Input:
|
| 91 |
+
- input = random tensor of shape (N, input_size)
|
| 92 |
+
|
| 93 |
+
Output:
|
| 94 |
+
- tensor of shape (N, input_size + output_size)
|
| 95 |
+
"""
|
| 96 |
+
residual = Residual(10, 2)
|
| 97 |
+
output = residual(torch.randn(100, 10))
|
| 98 |
+
assert output.shape == (100, 12)
|
| 99 |
+
|
| 100 |
+
# Check to make sure no gradients attached
|
| 101 |
+
for parameter in residual.parameters():
|
| 102 |
+
assert parameter.grad is None
|
| 103 |
+
|
| 104 |
+
# Backpropagate
|
| 105 |
+
output.mean().backward()
|
| 106 |
+
|
| 107 |
+
# Check to make sure all parameters have gradients
|
| 108 |
+
for parameter in residual.parameters():
|
| 109 |
+
assert parameter.grad is not None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class TestGenerator(TestCase):
|
| 113 |
+
|
| 114 |
+
def test___init__(self):
|
| 115 |
+
"""Test `__init__` for a generic case.
|
| 116 |
+
|
| 117 |
+
Make sure `self.seq` has same length as `generator_dim` + 1.
|
| 118 |
+
|
| 119 |
+
Setup:
|
| 120 |
+
- Create Generator
|
| 121 |
+
|
| 122 |
+
Input:
|
| 123 |
+
- embedding_dim = positive integer
|
| 124 |
+
- generator_dim = list of integers
|
| 125 |
+
- data_dim = positive integer
|
| 126 |
+
|
| 127 |
+
Output:
|
| 128 |
+
- None
|
| 129 |
+
|
| 130 |
+
Side Effects:
|
| 131 |
+
- Set `self.seq`
|
| 132 |
+
"""
|
| 133 |
+
generator_dim = [1, 2, 3]
|
| 134 |
+
generator = Generator(embedding_dim=50, generator_dim=generator_dim, data_dim=7)
|
| 135 |
+
|
| 136 |
+
assert len(generator.seq) == len(generator_dim) + 1
|
| 137 |
+
|
| 138 |
+
def test_forward(self):
|
| 139 |
+
"""Test `test_forward` for a generic case.
|
| 140 |
+
|
| 141 |
+
Check that the output shapes are correct.
|
| 142 |
+
We can also test that all parameters have a gradient attached to them
|
| 143 |
+
by running `encoder.parameters()`. To do that, we just need to use `loss.backward()`
|
| 144 |
+
for some loss, like `loss = torch.mean(output)`.
|
| 145 |
+
|
| 146 |
+
Setup:
|
| 147 |
+
- initialize with embedding_dim, generator_dim, data_dim
|
| 148 |
+
- Create random tensor as input
|
| 149 |
+
|
| 150 |
+
Input:
|
| 151 |
+
- input = random tensor of shape (N, input_size)
|
| 152 |
+
|
| 153 |
+
Output:
|
| 154 |
+
- tensor of shape (N, data_dim)
|
| 155 |
+
"""
|
| 156 |
+
generator = Generator(embedding_dim=60, generator_dim=[100, 200, 300], data_dim=500)
|
| 157 |
+
output = generator(torch.randn(70, 60))
|
| 158 |
+
assert output.shape == (70, 500)
|
| 159 |
+
|
| 160 |
+
# Check to make sure no gradients attached
|
| 161 |
+
for parameter in generator.parameters():
|
| 162 |
+
assert parameter.grad is None
|
| 163 |
+
|
| 164 |
+
# Backpropagate
|
| 165 |
+
output.mean().backward()
|
| 166 |
+
|
| 167 |
+
# Check to make sure all parameters have gradients
|
| 168 |
+
for parameter in generator.parameters():
|
| 169 |
+
assert parameter.grad is not None
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _assert_is_between(data, lower, upper):
|
| 173 |
+
"""Assert all values of the tensor 'data' are within range."""
|
| 174 |
+
assert all((data >= lower).numpy().tolist())
|
| 175 |
+
assert all((data <= upper).numpy().tolist())
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
class TestCTGANSynthesizer(TestCase):
|
| 179 |
+
|
| 180 |
+
def test__apply_activate_(self):
|
| 181 |
+
"""Test `_apply_activate` for tables with both continuous and categoricals.
|
| 182 |
+
|
| 183 |
+
Check every continuous column has all values between -1 and 1
|
| 184 |
+
(since they are normalized), and check every categorical column adds up to 1.
|
| 185 |
+
|
| 186 |
+
Setup:
|
| 187 |
+
- Mock `self._transformer.output_info_list`
|
| 188 |
+
|
| 189 |
+
Input:
|
| 190 |
+
- data = tensor of shape (N, data_dims)
|
| 191 |
+
|
| 192 |
+
Output:
|
| 193 |
+
- tensor = tensor of shape (N, data_dims)
|
| 194 |
+
"""
|
| 195 |
+
model = CTGANSynthesizer()
|
| 196 |
+
model._transformer = Mock()
|
| 197 |
+
model._transformer.output_info_list = [
|
| 198 |
+
[SpanInfo(3, 'softmax')],
|
| 199 |
+
[SpanInfo(1, 'tanh'), SpanInfo(2, 'softmax')]
|
| 200 |
+
]
|
| 201 |
+
|
| 202 |
+
data = torch.randn(100, 6)
|
| 203 |
+
result = model._apply_activate(data)
|
| 204 |
+
|
| 205 |
+
assert result.shape == (100, 6)
|
| 206 |
+
_assert_is_between(result[:, 0:3], 0.0, 1.0)
|
| 207 |
+
_assert_is_between(result[: 3], -1.0, 1.0)
|
| 208 |
+
_assert_is_between(result[:, 4:6], 0.0, 1.0)
|
| 209 |
+
|
| 210 |
+
def test__cond_loss(self):
|
| 211 |
+
"""Test `_cond_loss`.
|
| 212 |
+
|
| 213 |
+
Test that the loss is purely a function of the target categorical.
|
| 214 |
+
|
| 215 |
+
Setup:
|
| 216 |
+
- mock transformer.output_info_list
|
| 217 |
+
- create two categoricals, one continuous
|
| 218 |
+
- compute the conditional loss, conditioned on the 1st categorical
|
| 219 |
+
- compare the loss to the cross-entropy of the 1st categorical, manually computed
|
| 220 |
+
|
| 221 |
+
Input:
|
| 222 |
+
data - the synthetic data generated by the model
|
| 223 |
+
c - a tensor with the same shape as the data but with only a specific one-hot vector
|
| 224 |
+
corresponding to the target column filled in
|
| 225 |
+
m - binary mask used to select the categorical column to condition on
|
| 226 |
+
|
| 227 |
+
Output:
|
| 228 |
+
loss scalar; this should only be affected by the target column
|
| 229 |
+
|
| 230 |
+
Note:
|
| 231 |
+
- even though the implementation of this is probably right, I'm not sure if the idea
|
| 232 |
+
behind it is correct
|
| 233 |
+
"""
|
| 234 |
+
model = CTGANSynthesizer()
|
| 235 |
+
model._transformer = Mock()
|
| 236 |
+
model._transformer.output_info_list = [
|
| 237 |
+
[SpanInfo(1, 'tanh'), SpanInfo(2, 'softmax')],
|
| 238 |
+
[SpanInfo(3, 'softmax')], # this is the categorical column we are conditioning on
|
| 239 |
+
[SpanInfo(2, 'softmax')], # this is the categorical column we are bry jrbec on
|
| 240 |
+
]
|
| 241 |
+
|
| 242 |
+
data = torch.tensor([
|
| 243 |
+
# first 3 dims ignored, next 3 dims are the prediction, last 2 dims are ignored
|
| 244 |
+
[0.0, -1.0, 0.0, 0.05, 0.05, 0.9, 0.1, 0.4],
|
| 245 |
+
])
|
| 246 |
+
|
| 247 |
+
c = torch.tensor([
|
| 248 |
+
# first 3 dims are a one-hot for the categorical,
|
| 249 |
+
# next 2 are for a different categorical that we are not conditioning on
|
| 250 |
+
# (continuous values are not stored in this tensor)
|
| 251 |
+
[0.0, 0.0, 1.0, 0.0, 0.0],
|
| 252 |
+
])
|
| 253 |
+
|
| 254 |
+
# this indicates that we are conditioning on the first categorical
|
| 255 |
+
m = torch.tensor([[1, 0]])
|
| 256 |
+
|
| 257 |
+
result = model._cond_loss(data, c, m)
|
| 258 |
+
expected = torch.nn.functional.cross_entropy(
|
| 259 |
+
torch.tensor([
|
| 260 |
+
[0.05, 0.05, 0.9], # 3 categories, one hot
|
| 261 |
+
]),
|
| 262 |
+
torch.tensor([2])
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
assert (result - expected).abs() < 1e-3
|
| 266 |
+
|
| 267 |
+
def test__validate_discrete_columns(self):
|
| 268 |
+
"""Test `_validate_discrete_columns` if the discrete column doesn't exist.
|
| 269 |
+
|
| 270 |
+
Check the appropriate error is raised if `discrete_columns` is invalid, both
|
| 271 |
+
for numpy arrays and dataframes.
|
| 272 |
+
|
| 273 |
+
Setup:
|
| 274 |
+
- Create dataframe with a discrete column
|
| 275 |
+
- Define `discrete_columns` as something not in the dataframe
|
| 276 |
+
|
| 277 |
+
Input:
|
| 278 |
+
- train_data = 2-dimensional numpy array or a pandas.DataFrame
|
| 279 |
+
- discrete_columns = list of strings or integers
|
| 280 |
+
|
| 281 |
+
Output:
|
| 282 |
+
None
|
| 283 |
+
|
| 284 |
+
Side Effects:
|
| 285 |
+
- Raises error if the discrete column is invalid.
|
| 286 |
+
|
| 287 |
+
Note:
|
| 288 |
+
- could create another function for numpy array
|
| 289 |
+
"""
|
| 290 |
+
data = pd.DataFrame({
|
| 291 |
+
'discrete': ['a', 'b']
|
| 292 |
+
})
|
| 293 |
+
discrete_columns = ['doesnt exist']
|
| 294 |
+
|
| 295 |
+
ctgan = CTGANSynthesizer(epochs=1)
|
| 296 |
+
with pytest.raises(ValueError, match=r'Invalid columns found: {\'doesnt exist\'}'):
|
| 297 |
+
ctgan.fit(data, discrete_columns)
|
| 298 |
+
|
| 299 |
+
def test_sample(self):
|
| 300 |
+
"""Test `sample` correctly sets `condition_info` and `global_condition_vec`.
|
| 301 |
+
|
| 302 |
+
Tests the first 7 lines of sample by mocking the DataTransformer and DataSampler
|
| 303 |
+
and checking that they are being correctly used.
|
| 304 |
+
|
| 305 |
+
Setup:
|
| 306 |
+
- Create and fit the synthesizer
|
| 307 |
+
- Mock DataTransformer, DataSampler
|
| 308 |
+
|
| 309 |
+
Input:
|
| 310 |
+
- n = integer
|
| 311 |
+
- condition_column = string (not None)
|
| 312 |
+
- condition_value = string (not None)
|
| 313 |
+
|
| 314 |
+
Output:
|
| 315 |
+
Not relevant
|
| 316 |
+
|
| 317 |
+
Note:
|
| 318 |
+
- I'm not sure we need this test
|
| 319 |
+
"""
|
| 320 |
+
|
| 321 |
+
def test_set_device(self):
|
| 322 |
+
"""Test 'set_device' if a GPU is available.
|
| 323 |
+
|
| 324 |
+
Check that decoder/encoder can successfully be moved to the device.
|
| 325 |
+
If the machine doesn't have a GPU, this test shouldn't run.
|
| 326 |
+
|
| 327 |
+
Setup:
|
| 328 |
+
- Move decoder/encoder to device
|
| 329 |
+
|
| 330 |
+
Input:
|
| 331 |
+
- device = string
|
| 332 |
+
|
| 333 |
+
Output:
|
| 334 |
+
None
|
| 335 |
+
|
| 336 |
+
Side Effects:
|
| 337 |
+
- Set `self._device` to `device`
|
| 338 |
+
- Moves `self.decoder` to `self._device`
|
| 339 |
+
|
| 340 |
+
Note:
|
| 341 |
+
- Need to be careful when checking whether the encoder is actually set
|
| 342 |
+
to the right device, since it's not saved (it's only used in fit).
|
| 343 |
+
"""
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/synthesizer/test_tvae.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""TVAESynthesizer unit testing module."""
|
| 2 |
+
|
| 3 |
+
from unittest import TestCase
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class TestEncoder(TestCase):
|
| 7 |
+
|
| 8 |
+
def test___init__(self):
|
| 9 |
+
"""Test `__init__` for a generic case.
|
| 10 |
+
|
| 11 |
+
Make sure 'self.seq' has same length as 2*`compress_dims`.
|
| 12 |
+
|
| 13 |
+
Setup:
|
| 14 |
+
- Create Encoder
|
| 15 |
+
|
| 16 |
+
Input:
|
| 17 |
+
- data_dim = positive integer
|
| 18 |
+
- compress_dims = list of integers
|
| 19 |
+
- embedding_dim = positive integer
|
| 20 |
+
|
| 21 |
+
Output:
|
| 22 |
+
- None
|
| 23 |
+
|
| 24 |
+
Side Effects:
|
| 25 |
+
- Set `self.seq`, `self.fc1` and `self.fc2`
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def test_forward(self):
|
| 29 |
+
"""Test `test_forward` for a generic case.
|
| 30 |
+
|
| 31 |
+
Check that the output shapes are correct and that std is positive.
|
| 32 |
+
We can also test that all parameters have a gradient attached to them
|
| 33 |
+
by running `encoder.parameters()`. To do that, we just need to use `loss.backward()`
|
| 34 |
+
for some loss, like `loss = torch.mean(mu) + torch.mean(std) + torch.mean(logvar)`.
|
| 35 |
+
|
| 36 |
+
Setup:
|
| 37 |
+
- Create random tensor
|
| 38 |
+
|
| 39 |
+
Input:
|
| 40 |
+
- input = random tensor of shape (N, data_dim)
|
| 41 |
+
|
| 42 |
+
Output:
|
| 43 |
+
- Tuple of (mu, std, logvar):
|
| 44 |
+
mu - tensor of shape (N, embedding_dim)
|
| 45 |
+
std - tensor of shape (N, embedding_dim), non-negative values
|
| 46 |
+
logvar - tensor of shape (N, embedding_dim)
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TestDecoder(TestCase):
|
| 51 |
+
|
| 52 |
+
def test___init__(self):
|
| 53 |
+
"""Test `__init__` for a generic case.
|
| 54 |
+
|
| 55 |
+
Make sure 'self.seq' has same length as 2*`decompress_dims` + 1.
|
| 56 |
+
|
| 57 |
+
Setup:
|
| 58 |
+
- Create Decoder
|
| 59 |
+
|
| 60 |
+
Input:
|
| 61 |
+
- data_dim = positive integer
|
| 62 |
+
- decompress_dims = list of integers
|
| 63 |
+
- embedding_dim = positive integer
|
| 64 |
+
|
| 65 |
+
Output:
|
| 66 |
+
- None
|
| 67 |
+
|
| 68 |
+
Side Effects:
|
| 69 |
+
- Set `self.seq`, `self.sigma`
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class TestLossFunction(TestCase):
|
| 74 |
+
|
| 75 |
+
def test__loss_function(self):
|
| 76 |
+
"""Test `_loss_function`.
|
| 77 |
+
|
| 78 |
+
Check loss values = to specific numbers.
|
| 79 |
+
|
| 80 |
+
Setup:
|
| 81 |
+
Build all the tensors, lists, etc.
|
| 82 |
+
|
| 83 |
+
Input:
|
| 84 |
+
recon_x = tensor of shape (N, data_dims)
|
| 85 |
+
x = tensor of shape (N, data_dims)
|
| 86 |
+
sigmas = tensor of shape (N,)
|
| 87 |
+
mu = tensor of shape (N,)
|
| 88 |
+
logvar = tensor of shape (N,)
|
| 89 |
+
output_info = list of SpanInfo objects from the data transformer,
|
| 90 |
+
including at least 1 continuous and 1 discrete
|
| 91 |
+
factor = scalar
|
| 92 |
+
|
| 93 |
+
Output:
|
| 94 |
+
reconstruction loss = scalar = f(recon_x, x, sigmas, output_info, factor)
|
| 95 |
+
kld loss = scalar = f(logvar, mu)
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class TestTVAESynthesizer(TestCase):
|
| 100 |
+
|
| 101 |
+
def test_set_device(self):
|
| 102 |
+
"""Test 'set_device' if a GPU is available.
|
| 103 |
+
|
| 104 |
+
Check that decoder/encoder can successfully be moved to the device.
|
| 105 |
+
If the machine doesn't have a GPU, this test shouldn't run.
|
| 106 |
+
|
| 107 |
+
Setup:
|
| 108 |
+
- Move decoder/encoder to device
|
| 109 |
+
|
| 110 |
+
Input:
|
| 111 |
+
- device = string
|
| 112 |
+
|
| 113 |
+
Output:
|
| 114 |
+
None
|
| 115 |
+
|
| 116 |
+
Side Effects:
|
| 117 |
+
- Set `self._device` to `device`
|
| 118 |
+
- Moves `self.decoder` to `self._device`
|
| 119 |
+
|
| 120 |
+
Note:
|
| 121 |
+
- Need to be careful when checking whether the encoder is actually set
|
| 122 |
+
to the right device, since it's not saved (it's only used in fit).
|
| 123 |
+
"""
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tests/unit/test_data_transformer.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Data transformer unit testing module."""
|
| 2 |
+
|
| 3 |
+
from unittest import TestCase
|
| 4 |
+
from unittest.mock import Mock, patch
|
| 5 |
+
|
| 6 |
+
import numpy as np
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
from ctgan.data_transformer import ColumnTransformInfo, DataTransformer, SpanInfo
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class TestDataTransformer(TestCase):
|
| 13 |
+
|
| 14 |
+
@patch('ctgan.data_transformer.BayesGMMTransformer')
|
| 15 |
+
def test___fit_continuous(self, MockBGM):
|
| 16 |
+
"""Test ``_fit_continuous`` on a simple continuous column.
|
| 17 |
+
|
| 18 |
+
A ``BayesGMMTransformer`` will be created and fit with some ``data``.
|
| 19 |
+
|
| 20 |
+
Setup:
|
| 21 |
+
- Mock the ``BayesGMMTransformer`` with ``valid_component_indicator`` as
|
| 22 |
+
``[True, False, True]``.
|
| 23 |
+
- Initialize a ``DataTransformer``.
|
| 24 |
+
|
| 25 |
+
Input:
|
| 26 |
+
- A dataframe with only one column containing random float values.
|
| 27 |
+
|
| 28 |
+
Output:
|
| 29 |
+
- A ``ColumnTransformInfo`` object where:
|
| 30 |
+
- ``column_name`` matches the column of the data.
|
| 31 |
+
- ``transform`` is the ``BayesGMMTransformer`` instance.
|
| 32 |
+
- ``output_dimensions`` is 3 (matches size of ``valid_component_indicator``).
|
| 33 |
+
- ``output_info`` assigns the correct activation functions.
|
| 34 |
+
|
| 35 |
+
Side Effects:
|
| 36 |
+
- ``fit`` should be called with the data.
|
| 37 |
+
"""
|
| 38 |
+
# Setup
|
| 39 |
+
bgm_instance = MockBGM.return_value
|
| 40 |
+
bgm_instance.valid_component_indicator = [True, False, True]
|
| 41 |
+
transformer = DataTransformer()
|
| 42 |
+
data = pd.DataFrame(np.random.normal((100, 1)), columns=['column'])
|
| 43 |
+
|
| 44 |
+
# Run
|
| 45 |
+
info = transformer._fit_continuous(data)
|
| 46 |
+
|
| 47 |
+
# Assert
|
| 48 |
+
assert info.column_name == 'column'
|
| 49 |
+
assert info.transform == bgm_instance
|
| 50 |
+
assert info.output_dimensions == 3
|
| 51 |
+
assert info.output_info[0].dim == 1
|
| 52 |
+
assert info.output_info[0].activation_fn == 'tanh'
|
| 53 |
+
assert info.output_info[1].dim == 2
|
| 54 |
+
assert info.output_info[1].activation_fn == 'softmax'
|
| 55 |
+
|
| 56 |
+
@patch('ctgan.data_transformer.BayesGMMTransformer')
|
| 57 |
+
def test__fit_continuous_max_clusters(self, MockBGM):
|
| 58 |
+
"""Test ``_fit_continuous`` with data that has less than 10 rows.
|
| 59 |
+
|
| 60 |
+
Expect that a ``BayesGMMTransformer`` is created with the max number of clusters
|
| 61 |
+
set to the length of the data.
|
| 62 |
+
|
| 63 |
+
Input:
|
| 64 |
+
- Data with less than 10 rows.
|
| 65 |
+
|
| 66 |
+
Side Effects:
|
| 67 |
+
- A ``BayesGMMTransformer`` is created with the max number of clusters set to the
|
| 68 |
+
length of the data.
|
| 69 |
+
"""
|
| 70 |
+
# Setup
|
| 71 |
+
data = pd.DataFrame(np.random.normal((7, 1)), columns=['column'])
|
| 72 |
+
transformer = DataTransformer()
|
| 73 |
+
|
| 74 |
+
# Run
|
| 75 |
+
transformer._fit_continuous(data)
|
| 76 |
+
|
| 77 |
+
# Assert
|
| 78 |
+
MockBGM.assert_called_once_with(max_clusters=len(data))
|
| 79 |
+
|
| 80 |
+
@patch('ctgan.data_transformer.OneHotEncodingTransformer')
|
| 81 |
+
def test___fit_discrete(self, MockOHE):
|
| 82 |
+
"""Test ``_fit_discrete_`` on a simple discrete column.
|
| 83 |
+
|
| 84 |
+
A ``OneHotEncodingTransformer`` will be created and fit with the ``data``.
|
| 85 |
+
|
| 86 |
+
Setup:
|
| 87 |
+
- Mock the ``OneHotEncodingTransformer``.
|
| 88 |
+
- Create ``DataTransformer``.
|
| 89 |
+
|
| 90 |
+
Input:
|
| 91 |
+
- A dataframe with only one column containing ``['a', 'b']`` values.
|
| 92 |
+
|
| 93 |
+
Output:
|
| 94 |
+
- A ``ColumnTransformInfo`` object where:
|
| 95 |
+
- ``column_name`` matches the column of the data.
|
| 96 |
+
- ``transform`` is the ``OneHotEncodingTransformer`` instance.
|
| 97 |
+
- ``output_dimensions`` is 2.
|
| 98 |
+
- ``output_info`` assigns the correct activation function.
|
| 99 |
+
|
| 100 |
+
Side Effects:
|
| 101 |
+
- ``fit`` should be called with the data.
|
| 102 |
+
"""
|
| 103 |
+
# Setup
|
| 104 |
+
ohe_instance = MockOHE.return_value
|
| 105 |
+
ohe_instance.dummies = ['a', 'b']
|
| 106 |
+
transformer = DataTransformer()
|
| 107 |
+
data = pd.DataFrame(np.array(['a', 'b'] * 100), columns=['column'])
|
| 108 |
+
|
| 109 |
+
# Run
|
| 110 |
+
info = transformer._fit_discrete(data)
|
| 111 |
+
|
| 112 |
+
# Assert
|
| 113 |
+
assert info.column_name == 'column'
|
| 114 |
+
assert info.transform == ohe_instance
|
| 115 |
+
assert info.output_dimensions == 2
|
| 116 |
+
assert info.output_info[0].dim == 2
|
| 117 |
+
assert info.output_info[0].activation_fn == 'softmax'
|
| 118 |
+
|
| 119 |
+
def test_fit(self):
|
| 120 |
+
"""Test ``fit`` on a np.ndarray with one continuous and one discrete columns.
|
| 121 |
+
|
| 122 |
+
The ``fit`` method should:
|
| 123 |
+
- Set ``self.dataframe`` to ``False``.
|
| 124 |
+
- Set ``self._column_raw_dtypes`` to the appropirate dtypes.
|
| 125 |
+
- Use the appropriate ``_fit`` type for each column.
|
| 126 |
+
- Update ``self.output_info_list``, ``self.output_dimensions`` and
|
| 127 |
+
``self._column_transform_info_list`` appropriately.
|
| 128 |
+
|
| 129 |
+
Setup:
|
| 130 |
+
- Create ``DataTransformer``.
|
| 131 |
+
- Mock ``_fit_discrete``.
|
| 132 |
+
- Mock ``_fit_continuous``.
|
| 133 |
+
|
| 134 |
+
Input:
|
| 135 |
+
- A table with one continuous and one discrete columns.
|
| 136 |
+
- A list with the name of the discrete column.
|
| 137 |
+
|
| 138 |
+
Side Effects:
|
| 139 |
+
- ``_fit_discrete`` and ``_fit_continuous`` should each be called once.
|
| 140 |
+
- Assigns ``self._column_raw_dtypes`` the appropriate dtypes.
|
| 141 |
+
- Assigns ``self.output_info_list`` the appropriate ``output_info``.
|
| 142 |
+
- Assigns ``self.output_dimensions`` the appropriate ``output_dimensions``.
|
| 143 |
+
- Assigns ``self._column_transform_info_list`` the appropriate
|
| 144 |
+
``column_transform_info``.
|
| 145 |
+
"""
|
| 146 |
+
# Setup
|
| 147 |
+
transformer = DataTransformer()
|
| 148 |
+
transformer._fit_continuous = Mock()
|
| 149 |
+
transformer._fit_continuous.return_value = ColumnTransformInfo(
|
| 150 |
+
column_name='x', column_type='continuous', transform=None,
|
| 151 |
+
output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')],
|
| 152 |
+
output_dimensions=1 + 3
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
transformer._fit_discrete = Mock()
|
| 156 |
+
transformer._fit_discrete.return_value = ColumnTransformInfo(
|
| 157 |
+
column_name='y', column_type='discrete', transform=None,
|
| 158 |
+
output_info=[SpanInfo(2, 'softmax')],
|
| 159 |
+
output_dimensions=2
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
data = pd.DataFrame({
|
| 163 |
+
'x': np.random.random(size=100),
|
| 164 |
+
'y': np.random.choice(['yes', 'no'], size=100)
|
| 165 |
+
})
|
| 166 |
+
|
| 167 |
+
# Run
|
| 168 |
+
transformer.fit(data, discrete_columns=['y'])
|
| 169 |
+
|
| 170 |
+
# Assert
|
| 171 |
+
transformer._fit_discrete.assert_called_once()
|
| 172 |
+
transformer._fit_continuous.assert_called_once()
|
| 173 |
+
assert transformer.output_dimensions == 6
|
| 174 |
+
|
| 175 |
+
@patch('ctgan.data_transformer.BayesGMMTransformer')
|
| 176 |
+
def test__transform_continuous(self, MockBGM):
|
| 177 |
+
"""Test ``_transform_continuous``.
|
| 178 |
+
|
| 179 |
+
Setup:
|
| 180 |
+
- Mock the ``BayesGMMTransformer`` with the transform method returning
|
| 181 |
+
some dataframe.
|
| 182 |
+
- Create ``DataTransformer``.
|
| 183 |
+
|
| 184 |
+
Input:
|
| 185 |
+
- ``ColumnTransformInfo`` object.
|
| 186 |
+
- A dataframe containing a continuous column.
|
| 187 |
+
|
| 188 |
+
Output:
|
| 189 |
+
- A np.array where the first column contains the normalized part
|
| 190 |
+
of the mocked transform, and the other columns are a one hot encoding
|
| 191 |
+
representation of the component part of the mocked transform.
|
| 192 |
+
"""
|
| 193 |
+
# Setup
|
| 194 |
+
bgm_instance = MockBGM.return_value
|
| 195 |
+
bgm_instance.transform.return_value = pd.DataFrame({
|
| 196 |
+
'x.normalized': [0.1, 0.2, 0.3],
|
| 197 |
+
'x.component': [0.0, 1.0, 1.0]
|
| 198 |
+
})
|
| 199 |
+
|
| 200 |
+
transformer = DataTransformer()
|
| 201 |
+
data = pd.DataFrame({'x': np.array([0.1, 0.3, 0.5])})
|
| 202 |
+
column_transform_info = ColumnTransformInfo(
|
| 203 |
+
column_name='x', column_type='continuous', transform=bgm_instance,
|
| 204 |
+
output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')],
|
| 205 |
+
output_dimensions=1 + 3
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
# Run
|
| 209 |
+
result = transformer._transform_continuous(column_transform_info, data)
|
| 210 |
+
|
| 211 |
+
# Assert
|
| 212 |
+
expected = np.array([
|
| 213 |
+
[0.1, 1, 0, 0],
|
| 214 |
+
[0.2, 0, 1, 0],
|
| 215 |
+
[0.3, 0, 1, 0],
|
| 216 |
+
])
|
| 217 |
+
np.testing.assert_array_equal(result, expected)
|
| 218 |
+
|
| 219 |
+
def test_transform(self):
|
| 220 |
+
"""Test ``transform`` on a dataframe with one continuous and one discrete columns.
|
| 221 |
+
|
| 222 |
+
It should use the appropriate ``_transform`` type for each column and should return
|
| 223 |
+
them concanenated appropriately.
|
| 224 |
+
|
| 225 |
+
Setup:
|
| 226 |
+
- Initialize a ``DataTransformer`` with a ``column_transform_info`` detailing
|
| 227 |
+
a continuous and a discrete columns.
|
| 228 |
+
- Mock the ``_transform_discrete`` and ``_transform_continuous`` methods.
|
| 229 |
+
|
| 230 |
+
Input:
|
| 231 |
+
- A table with one continuous and one discrete columns.
|
| 232 |
+
|
| 233 |
+
Output:
|
| 234 |
+
- np.array containing the transformed columns.
|
| 235 |
+
|
| 236 |
+
Side Effects:
|
| 237 |
+
- ``_transform_discrete`` and ``_transform_continuous`` should each be called once.
|
| 238 |
+
"""
|
| 239 |
+
# Setup
|
| 240 |
+
data = pd.DataFrame({
|
| 241 |
+
'x': np.array([0.1, 0.3, 0.5]),
|
| 242 |
+
'y': np.array(['yes', 'yes', 'no'])
|
| 243 |
+
})
|
| 244 |
+
|
| 245 |
+
transformer = DataTransformer()
|
| 246 |
+
transformer._column_transform_info_list = [
|
| 247 |
+
ColumnTransformInfo(
|
| 248 |
+
column_name='x', column_type='continuous', transform=None,
|
| 249 |
+
output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')],
|
| 250 |
+
output_dimensions=1 + 3
|
| 251 |
+
),
|
| 252 |
+
ColumnTransformInfo(
|
| 253 |
+
column_name='y', column_type='discrete', transform=None,
|
| 254 |
+
output_info=[SpanInfo(2, 'softmax')],
|
| 255 |
+
output_dimensions=2
|
| 256 |
+
)
|
| 257 |
+
]
|
| 258 |
+
|
| 259 |
+
transformer._transform_continuous = Mock()
|
| 260 |
+
selected_normalized_value = np.array([[0.1], [0.3], [0.5]])
|
| 261 |
+
selected_component_onehot = np.array([
|
| 262 |
+
[1, 0, 0],
|
| 263 |
+
[0, 1, 0],
|
| 264 |
+
[0, 1, 0],
|
| 265 |
+
])
|
| 266 |
+
return_value = np.concatenate(
|
| 267 |
+
(selected_normalized_value, selected_component_onehot), axis=1)
|
| 268 |
+
transformer._transform_continuous.return_value = return_value
|
| 269 |
+
|
| 270 |
+
transformer._transform_discrete = Mock()
|
| 271 |
+
transformer._transform_discrete.return_value = np.array([
|
| 272 |
+
[0, 1],
|
| 273 |
+
[0, 1],
|
| 274 |
+
[1, 0],
|
| 275 |
+
])
|
| 276 |
+
|
| 277 |
+
# Run
|
| 278 |
+
result = transformer.transform(data)
|
| 279 |
+
|
| 280 |
+
# Assert
|
| 281 |
+
transformer._transform_continuous.assert_called_once()
|
| 282 |
+
transformer._transform_discrete.assert_called_once()
|
| 283 |
+
|
| 284 |
+
expected = np.array([
|
| 285 |
+
[0.1, 1, 0, 0, 0, 1],
|
| 286 |
+
[0.3, 0, 1, 0, 0, 1],
|
| 287 |
+
[0.5, 0, 1, 0, 1, 0],
|
| 288 |
+
])
|
| 289 |
+
assert result.shape == (3, 6)
|
| 290 |
+
assert (result[:, 0] == expected[:, 0]).all(), 'continuous-cdf'
|
| 291 |
+
assert (result[:, 1:4] == expected[:, 1:4]).all(), 'continuous-softmax'
|
| 292 |
+
assert (result[:, 4:6] == expected[:, 4:6]).all(), 'discrete'
|
| 293 |
+
|
| 294 |
+
@patch('ctgan.data_transformer.BayesGMMTransformer')
|
| 295 |
+
def test__inverse_transform_continuous(self, MockBGM):
|
| 296 |
+
"""Test ``_inverse_transform_continuous``.
|
| 297 |
+
|
| 298 |
+
Setup:
|
| 299 |
+
- Create ``DataTransformer``.
|
| 300 |
+
- Mock the ``BayesGMMTransformer`` where:
|
| 301 |
+
- ``get_output_types`` returns the appropriate dictionary.
|
| 302 |
+
- ``reverse_transform`` returns some dataframe.
|
| 303 |
+
|
| 304 |
+
Input:
|
| 305 |
+
- A ``ColumnTransformInfo`` object.
|
| 306 |
+
- A np.ndarray where:
|
| 307 |
+
- The first column contains the normalized value
|
| 308 |
+
- The remaining columns correspond to the one-hot
|
| 309 |
+
- sigmas = np.ndarray of floats
|
| 310 |
+
- st = index of the sigmas ndarray
|
| 311 |
+
|
| 312 |
+
Output:
|
| 313 |
+
- Dataframe where the first column are floats and the second is a lable encoding.
|
| 314 |
+
|
| 315 |
+
Side Effects:
|
| 316 |
+
- The ``reverse_transform`` method should be called with a dataframe
|
| 317 |
+
where the first column are floats and the second is a lable encoding.
|
| 318 |
+
"""
|
| 319 |
+
# Setup
|
| 320 |
+
bgm_instance = MockBGM.return_value
|
| 321 |
+
bgm_instance.get_output_types.return_value = {
|
| 322 |
+
'x.normalized': 'numerical',
|
| 323 |
+
'x.component': 'numerical'
|
| 324 |
+
}
|
| 325 |
+
|
| 326 |
+
bgm_instance.reverse_transform.return_value = pd.DataFrame({
|
| 327 |
+
'x.normalized': [0.1, 0.2, 0.3],
|
| 328 |
+
'x.component': [0.0, 1.0, 1.0]
|
| 329 |
+
})
|
| 330 |
+
|
| 331 |
+
transformer = DataTransformer()
|
| 332 |
+
column_data = np.array([
|
| 333 |
+
[0.1, 1, 0, 0],
|
| 334 |
+
[0.3, 0, 1, 0],
|
| 335 |
+
[0.5, 0, 1, 0],
|
| 336 |
+
])
|
| 337 |
+
|
| 338 |
+
column_transform_info = ColumnTransformInfo(
|
| 339 |
+
column_name='x', column_type='continuous', transform=bgm_instance,
|
| 340 |
+
output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')],
|
| 341 |
+
output_dimensions=1 + 3
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
# Run
|
| 345 |
+
result = transformer._inverse_transform_continuous(
|
| 346 |
+
column_transform_info, column_data, None, None)
|
| 347 |
+
|
| 348 |
+
# Assert
|
| 349 |
+
expected = pd.DataFrame({
|
| 350 |
+
'x.normalized': [0.1, 0.2, 0.3],
|
| 351 |
+
'x.component': [0.0, 1.0, 1.0]
|
| 352 |
+
})
|
| 353 |
+
|
| 354 |
+
np.testing.assert_array_equal(result, expected)
|
| 355 |
+
|
| 356 |
+
expected_data = pd.DataFrame({
|
| 357 |
+
'x.normalized': [0.1, 0.3, 0.5],
|
| 358 |
+
'x.component': [0, 1, 1]
|
| 359 |
+
})
|
| 360 |
+
|
| 361 |
+
pd.testing.assert_frame_equal(
|
| 362 |
+
bgm_instance.reverse_transform.call_args[0][0],
|
| 363 |
+
expected_data
|
| 364 |
+
)
|
| 365 |
+
|
| 366 |
+
def test_inverse_transform(self):
|
| 367 |
+
"""Test ``inverse_transform`` on a np.ndarray with continuous and discrete columns.
|
| 368 |
+
|
| 369 |
+
It should use the appropriate '_fit' type for each column and should return
|
| 370 |
+
the corresponding columns. Since we are using the same example as the 'test_transform',
|
| 371 |
+
and these two functions are inverse of each other, the returned value here should
|
| 372 |
+
match the input of that function.
|
| 373 |
+
|
| 374 |
+
Setup:
|
| 375 |
+
- Mock _column_transform_info_list
|
| 376 |
+
- Mock _inverse_transform_discrete
|
| 377 |
+
- Mock _inverse_trarnsform_continuous
|
| 378 |
+
|
| 379 |
+
Input:
|
| 380 |
+
- column_data = a concatenation of two np.ndarrays
|
| 381 |
+
- the first one refers to the continuous values
|
| 382 |
+
- the first column contains the normalized values
|
| 383 |
+
- the remaining columns correspond to the a one-hot
|
| 384 |
+
- the second one refers to the discrete values
|
| 385 |
+
- the columns correspond to a one-hot
|
| 386 |
+
Output:
|
| 387 |
+
- numpy array containing a discrete column and a continuous column
|
| 388 |
+
|
| 389 |
+
Side Effects:
|
| 390 |
+
- _transform_discrete and _transform_continuous should each be called once.
|
| 391 |
+
"""
|
| 392 |
+
|
| 393 |
+
def test_convert_column_name_value_to_id(self):
|
| 394 |
+
"""Test ``convert_column_name_value_to_id`` on a simple ``_column_transform_info_list``.
|
| 395 |
+
|
| 396 |
+
Tests that the appropriate indexes are returned when a table of three columns,
|
| 397 |
+
discrete, continuous, discrete, is passed as '_column_transform_info_list'.
|
| 398 |
+
|
| 399 |
+
Setup:
|
| 400 |
+
- Mock ``_column_transform_info_list``.
|
| 401 |
+
|
| 402 |
+
Input:
|
| 403 |
+
- column_name = the name of a discrete column
|
| 404 |
+
- value = the categorical value
|
| 405 |
+
|
| 406 |
+
Output:
|
| 407 |
+
- dictionary containing:
|
| 408 |
+
- ``discrete_column_id`` = the index of the target column,
|
| 409 |
+
when considering only discrete columns
|
| 410 |
+
- ``column_id`` = the index of the target column
|
| 411 |
+
(e.g. 3 = the third column in the data)
|
| 412 |
+
- ``value_id`` = the index of the indicator value in the one-hot encoding
|
| 413 |
+
"""
|
| 414 |
+
# Setup
|
| 415 |
+
ohe = Mock()
|
| 416 |
+
ohe.transform.return_value = pd.DataFrame([
|
| 417 |
+
[0, 1] # one hot encoding, second dimension
|
| 418 |
+
])
|
| 419 |
+
transformer = DataTransformer()
|
| 420 |
+
transformer._column_transform_info_list = [
|
| 421 |
+
ColumnTransformInfo(
|
| 422 |
+
column_name='x', column_type='continuous', transform=None,
|
| 423 |
+
output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')],
|
| 424 |
+
output_dimensions=1 + 3
|
| 425 |
+
),
|
| 426 |
+
ColumnTransformInfo(
|
| 427 |
+
column_name='y', column_type='discrete', transform=ohe,
|
| 428 |
+
output_info=[SpanInfo(2, 'softmax')],
|
| 429 |
+
output_dimensions=2
|
| 430 |
+
)
|
| 431 |
+
]
|
| 432 |
+
|
| 433 |
+
# Run
|
| 434 |
+
result = transformer.convert_column_name_value_to_id('y', 'yes')
|
| 435 |
+
|
| 436 |
+
# Assert
|
| 437 |
+
assert result['column_id'] == 1 # this is the 2nd column
|
| 438 |
+
assert result['discrete_column_id'] == 0 # this is the 1st discrete column
|
| 439 |
+
assert result['value_id'] == 1 # this is the 2nd dimension in the one hot encoding
|
| 440 |
+
|
| 441 |
+
def test_convert_column_name_value_to_id_multiple(self):
|
| 442 |
+
"""Test ``convert_column_name_value_to_id``."""
|
| 443 |
+
# Setup
|
| 444 |
+
ohe = Mock()
|
| 445 |
+
ohe.transform.return_value = pd.DataFrame([
|
| 446 |
+
[0, 1, 0] # one hot encoding, second dimension
|
| 447 |
+
])
|
| 448 |
+
transformer = DataTransformer()
|
| 449 |
+
transformer._column_transform_info_list = [
|
| 450 |
+
ColumnTransformInfo(
|
| 451 |
+
column_name='x', column_type='continuous', transform=None,
|
| 452 |
+
output_info=[SpanInfo(1, 'tanh'), SpanInfo(3, 'softmax')],
|
| 453 |
+
output_dimensions=1 + 3
|
| 454 |
+
),
|
| 455 |
+
ColumnTransformInfo(
|
| 456 |
+
column_name='y', column_type='discrete', transform=ohe,
|
| 457 |
+
output_info=[SpanInfo(2, 'softmax')],
|
| 458 |
+
output_dimensions=2
|
| 459 |
+
),
|
| 460 |
+
ColumnTransformInfo(
|
| 461 |
+
column_name='z', column_type='discrete', transform=ohe,
|
| 462 |
+
output_info=[SpanInfo(2, 'softmax')],
|
| 463 |
+
output_dimensions=2
|
| 464 |
+
)
|
| 465 |
+
]
|
| 466 |
+
|
| 467 |
+
# Run
|
| 468 |
+
result = transformer.convert_column_name_value_to_id('z', 'yes')
|
| 469 |
+
|
| 470 |
+
# Assert
|
| 471 |
+
assert result['column_id'] == 2 # this is the 3rd column
|
| 472 |
+
assert result['discrete_column_id'] == 1 # this is the 2nd discrete column
|
| 473 |
+
assert result['value_id'] == 1 # this is the 1st dimension in the one hot encoding
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/CTGAN/tox.ini
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[tox]
|
| 2 |
+
envlist = py38-lint, py3{6,7,8,9}-{unit,integration,readme}
|
| 3 |
+
|
| 4 |
+
[testenv]
|
| 5 |
+
skipsdist = false
|
| 6 |
+
skip_install = false
|
| 7 |
+
deps =
|
| 8 |
+
invoke
|
| 9 |
+
readme: rundoc
|
| 10 |
+
extras =
|
| 11 |
+
lint: dev
|
| 12 |
+
unit: test
|
| 13 |
+
integration: test
|
| 14 |
+
commands =
|
| 15 |
+
lint: invoke lint
|
| 16 |
+
unit: invoke unit
|
| 17 |
+
integration: invoke integration
|
| 18 |
+
readme: invoke readme
|
| 19 |
+
invoke rmdir --path {envdir}
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/pipeline_tvae.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tomli
|
| 2 |
+
import shutil
|
| 3 |
+
import os
|
| 4 |
+
import argparse
|
| 5 |
+
from train_sample_tvae import train_tvae, sample_tvae
|
| 6 |
+
from scripts.eval_catboost import train_catboost
|
| 7 |
+
import zero
|
| 8 |
+
import lib
|
| 9 |
+
|
| 10 |
+
def load_config(path) :
|
| 11 |
+
with open(path, 'rb') as f:
|
| 12 |
+
return tomli.load(f)
|
| 13 |
+
|
| 14 |
+
def save_file(parent_dir, config_path):
|
| 15 |
+
try:
|
| 16 |
+
dst = os.path.join(parent_dir)
|
| 17 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 18 |
+
shutil.copyfile(os.path.abspath(config_path), dst)
|
| 19 |
+
except shutil.SameFileError:
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
parser = argparse.ArgumentParser()
|
| 24 |
+
parser.add_argument('--config', metavar='FILE')
|
| 25 |
+
parser.add_argument('--train', action='store_true', default=False)
|
| 26 |
+
parser.add_argument('--sample', action='store_true', default=False)
|
| 27 |
+
parser.add_argument('--eval', action='store_true', default=False)
|
| 28 |
+
parser.add_argument('--change_val', action='store_true', default=False)
|
| 29 |
+
|
| 30 |
+
args = parser.parse_args()
|
| 31 |
+
raw_config = lib.load_config(args.config)
|
| 32 |
+
timer = zero.Timer()
|
| 33 |
+
timer.run()
|
| 34 |
+
save_file(os.path.join(raw_config['parent_dir'], 'config.toml'), args.config)
|
| 35 |
+
ctabgan = None
|
| 36 |
+
if args.train:
|
| 37 |
+
ctabgan = train_tvae(
|
| 38 |
+
parent_dir=raw_config['parent_dir'],
|
| 39 |
+
real_data_path=raw_config['real_data_path'],
|
| 40 |
+
train_params=raw_config['train_params'],
|
| 41 |
+
change_val=args.change_val,
|
| 42 |
+
device=raw_config['device']
|
| 43 |
+
)
|
| 44 |
+
if args.sample:
|
| 45 |
+
sample_tvae(
|
| 46 |
+
synthesizer=ctabgan,
|
| 47 |
+
parent_dir=raw_config['parent_dir'],
|
| 48 |
+
real_data_path=raw_config['real_data_path'],
|
| 49 |
+
num_samples=raw_config['sample']['num_samples'],
|
| 50 |
+
train_params=raw_config['train_params'],
|
| 51 |
+
change_val=args.change_val,
|
| 52 |
+
seed=raw_config['sample']['seed'],
|
| 53 |
+
device=raw_config['device']
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
save_file(os.path.join(raw_config['parent_dir'], 'info.json'), os.path.join(raw_config['real_data_path'], 'info.json'))
|
| 57 |
+
if args.eval:
|
| 58 |
+
if raw_config['eval']['type']['eval_model'] == 'catboost':
|
| 59 |
+
train_catboost(
|
| 60 |
+
parent_dir=raw_config['parent_dir'],
|
| 61 |
+
real_data_path=raw_config['real_data_path'],
|
| 62 |
+
eval_type=raw_config['eval']['type']['eval_type'],
|
| 63 |
+
T_dict=raw_config['eval']['T'],
|
| 64 |
+
seed=raw_config['seed'],
|
| 65 |
+
change_val=args.change_val
|
| 66 |
+
)
|
| 67 |
+
# elif raw_config['eval']['type']['eval_model'] == 'mlp':
|
| 68 |
+
# train_mlp(
|
| 69 |
+
# parent_dir=raw_config['parent_dir'],
|
| 70 |
+
# real_data_path=raw_config['real_data_path'],
|
| 71 |
+
# eval_type=raw_config['eval']['type']['eval_type'],
|
| 72 |
+
# T_dict=raw_config['eval']['T'],
|
| 73 |
+
# seed=raw_config['seed'],
|
| 74 |
+
# change_val=args.change_val
|
| 75 |
+
# )
|
| 76 |
+
|
| 77 |
+
print(f'Elapsed time: {str(timer)}')
|
| 78 |
+
|
| 79 |
+
if __name__ == '__main__':
|
| 80 |
+
main()
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/train_sample_tvae.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import lib
|
| 2 |
+
import os
|
| 3 |
+
import numpy as np
|
| 4 |
+
import argparse
|
| 5 |
+
from CTGAN.ctgan import TVAESynthesizer
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import torch
|
| 8 |
+
import pickle
|
| 9 |
+
import warnings
|
| 10 |
+
from sklearn.exceptions import ConvergenceWarning
|
| 11 |
+
|
| 12 |
+
warnings.filterwarnings("ignore", category=ConvergenceWarning)
|
| 13 |
+
|
| 14 |
+
def train_tvae(
|
| 15 |
+
parent_dir,
|
| 16 |
+
real_data_path,
|
| 17 |
+
train_params = {"batch_size": 512},
|
| 18 |
+
change_val=False,
|
| 19 |
+
device = "cpu"
|
| 20 |
+
):
|
| 21 |
+
real_data_path = Path(real_data_path)
|
| 22 |
+
parent_dir = Path(parent_dir)
|
| 23 |
+
device = torch.device(device)
|
| 24 |
+
|
| 25 |
+
if change_val:
|
| 26 |
+
X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
|
| 27 |
+
else:
|
| 28 |
+
X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
|
| 29 |
+
|
| 30 |
+
X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
|
| 31 |
+
|
| 32 |
+
X.columns = [str(_) for _ in X.columns]
|
| 33 |
+
|
| 34 |
+
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 []
|
| 35 |
+
if lib.load_json(real_data_path / "info.json")["task_type"] != "regression":
|
| 36 |
+
cat_features += ["y"]
|
| 37 |
+
|
| 38 |
+
train_params["batch_size"] = min(y_train.shape[0], train_params["batch_size"])
|
| 39 |
+
|
| 40 |
+
print(train_params)
|
| 41 |
+
synthesizer = TVAESynthesizer(
|
| 42 |
+
**train_params,
|
| 43 |
+
device=device
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
synthesizer.fit(X, cat_features)
|
| 47 |
+
|
| 48 |
+
# save_ctabgan(synthesizer, parent_dir)
|
| 49 |
+
with open(parent_dir / "tvae.obj", "wb") as f:
|
| 50 |
+
pickle.dump(synthesizer, f)
|
| 51 |
+
|
| 52 |
+
return synthesizer
|
| 53 |
+
|
| 54 |
+
def sample_tvae(
|
| 55 |
+
synthesizer,
|
| 56 |
+
parent_dir,
|
| 57 |
+
real_data_path,
|
| 58 |
+
num_samples,
|
| 59 |
+
train_params = {"batch_size": 512},
|
| 60 |
+
change_val=False,
|
| 61 |
+
device="cpu",
|
| 62 |
+
seed=0
|
| 63 |
+
):
|
| 64 |
+
real_data_path = Path(real_data_path)
|
| 65 |
+
parent_dir = Path(parent_dir)
|
| 66 |
+
device = torch.device(device)
|
| 67 |
+
|
| 68 |
+
if change_val:
|
| 69 |
+
X_num_train, X_cat_train, y_train, _, _, _ = lib.read_changed_val(real_data_path)
|
| 70 |
+
else:
|
| 71 |
+
X_num_train, X_cat_train, y_train = lib.read_pure_data(real_data_path, 'train')
|
| 72 |
+
|
| 73 |
+
X = lib.concat_to_pd(X_num_train, X_cat_train, y_train)
|
| 74 |
+
|
| 75 |
+
X.columns = [str(_) for _ in X.columns]
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
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 []
|
| 79 |
+
if lib.load_json(real_data_path / "info.json")["task_type"] != "regression":
|
| 80 |
+
cat_features += ["y"]
|
| 81 |
+
|
| 82 |
+
with open(parent_dir / "tvae.obj", 'rb') as f:
|
| 83 |
+
synthesizer = pickle.load(f)
|
| 84 |
+
synthesizer.decoder = synthesizer.decoder.to(device)
|
| 85 |
+
|
| 86 |
+
gen_data = synthesizer.sample(num_samples, seed)
|
| 87 |
+
|
| 88 |
+
y = gen_data['y'].values
|
| 89 |
+
if len(np.unique(y)) == 1:
|
| 90 |
+
y[0] = 0
|
| 91 |
+
y[1] = 1
|
| 92 |
+
|
| 93 |
+
X_cat = gen_data[cat_features].drop('y', axis=1, errors="ignore").values if len(cat_features) else None
|
| 94 |
+
X_num = gen_data.values[:, :X_num_train.shape[1]] if X_num_train is not None else None
|
| 95 |
+
|
| 96 |
+
if X_num_train is not None:
|
| 97 |
+
np.save(parent_dir / 'X_num_train', X_num.astype(float))
|
| 98 |
+
if X_cat_train is not None:
|
| 99 |
+
np.save(parent_dir / 'X_cat_train', X_cat.astype(str))
|
| 100 |
+
y = y.astype(float)
|
| 101 |
+
if lib.load_json(real_data_path / "info.json")["task_type"] != "regression":
|
| 102 |
+
y = y.astype(int)
|
| 103 |
+
np.save(parent_dir / 'y_train', y) # only clf !!!
|
| 104 |
+
|
| 105 |
+
def main():
|
| 106 |
+
parser = argparse.ArgumentParser()
|
| 107 |
+
parser.add_argument('real_data_path', type=str)
|
| 108 |
+
parser.add_argument('parent_dir', type=str)
|
| 109 |
+
parser.add_argument('train_size', type=int)
|
| 110 |
+
args = parser.parse_args()
|
| 111 |
+
|
| 112 |
+
ctabgan = train_tvae(args.parent_dir, args.real_data_path, change_val=True)
|
| 113 |
+
sample_tvae(ctabgan, args.parent_dir, args.real_data_path, args.train_size, change_val=True)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
if __name__ == '__main__':
|
| 117 |
+
main()
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/CTGAN/tune_tvae.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from multiprocessing.sharedctypes import RawValue
|
| 2 |
+
import tempfile
|
| 3 |
+
import subprocess
|
| 4 |
+
import lib
|
| 5 |
+
import os
|
| 6 |
+
import optuna
|
| 7 |
+
import argparse
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from train_sample_tvae import train_tvae, sample_tvae
|
| 10 |
+
from scripts.eval_catboost import train_catboost
|
| 11 |
+
|
| 12 |
+
parser = argparse.ArgumentParser()
|
| 13 |
+
parser.add_argument('data_path', type=str)
|
| 14 |
+
parser.add_argument('train_size', type=int)
|
| 15 |
+
parser.add_argument('eval_type', type=str)
|
| 16 |
+
parser.add_argument('device', type=str)
|
| 17 |
+
|
| 18 |
+
args = parser.parse_args()
|
| 19 |
+
real_data_path = args.data_path
|
| 20 |
+
eval_type = args.eval_type
|
| 21 |
+
train_size = args.train_size
|
| 22 |
+
device = args.device
|
| 23 |
+
assert eval_type in ('merged', 'synthetic')
|
| 24 |
+
|
| 25 |
+
def objective(trial):
|
| 26 |
+
|
| 27 |
+
lr = trial.suggest_loguniform('lr', 0.00001, 0.003)
|
| 28 |
+
|
| 29 |
+
def suggest_dim(name):
|
| 30 |
+
t = trial.suggest_int(name, d_min, d_max)
|
| 31 |
+
return 2 ** t
|
| 32 |
+
|
| 33 |
+
# construct model
|
| 34 |
+
min_n_layers, max_n_layers, d_min, d_max = 1, 3, 6, 9
|
| 35 |
+
n_layers = 2 * trial.suggest_int('n_layers', min_n_layers, max_n_layers)
|
| 36 |
+
d_first = [suggest_dim('d_first')] if n_layers else []
|
| 37 |
+
d_middle = (
|
| 38 |
+
[suggest_dim('d_middle')] * (n_layers - 2)
|
| 39 |
+
if n_layers > 2
|
| 40 |
+
else []
|
| 41 |
+
)
|
| 42 |
+
d_last = [suggest_dim('d_last')] if n_layers > 1 else []
|
| 43 |
+
d_layers = d_first + d_middle + d_last
|
| 44 |
+
####
|
| 45 |
+
|
| 46 |
+
steps = trial.suggest_categorical('steps', [5000, 20000, 30000])
|
| 47 |
+
# steps = trial.suggest_categorical('steps', [1000])
|
| 48 |
+
batch_size = trial.suggest_categorical('batch_size', [256, 4096])
|
| 49 |
+
|
| 50 |
+
num_samples = int(train_size * (2 ** trial.suggest_int('frac_samples', -2, 3)))
|
| 51 |
+
embedding_dim = 2 ** trial.suggest_int('embedding_dim', 6, 10)
|
| 52 |
+
loss_factor = trial.suggest_loguniform('loss_factor', 0.001, 10)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
train_params = {
|
| 56 |
+
"lr": lr,
|
| 57 |
+
"epochs": steps,
|
| 58 |
+
"embedding_dim": embedding_dim,
|
| 59 |
+
"batch_size": batch_size,
|
| 60 |
+
"loss_factor": loss_factor,
|
| 61 |
+
"compress_dims": d_layers,
|
| 62 |
+
"decompress_dims": d_layers
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
trial.set_user_attr("train_params", train_params)
|
| 66 |
+
trial.set_user_attr("num_samples", num_samples)
|
| 67 |
+
|
| 68 |
+
score = 0.0
|
| 69 |
+
with tempfile.TemporaryDirectory() as dir_:
|
| 70 |
+
dir_ = Path(dir_)
|
| 71 |
+
ctabgan = train_tvae(
|
| 72 |
+
parent_dir=dir_,
|
| 73 |
+
real_data_path=real_data_path,
|
| 74 |
+
train_params=train_params,
|
| 75 |
+
change_val=True,
|
| 76 |
+
device=device
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
for sample_seed in range(5):
|
| 80 |
+
sample_tvae(
|
| 81 |
+
ctabgan,
|
| 82 |
+
parent_dir=dir_,
|
| 83 |
+
real_data_path=real_data_path,
|
| 84 |
+
num_samples=num_samples,
|
| 85 |
+
train_params=train_params,
|
| 86 |
+
change_val=True,
|
| 87 |
+
seed=sample_seed,
|
| 88 |
+
device=device
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
T_dict = {
|
| 92 |
+
"seed": 0,
|
| 93 |
+
"normalization": None,
|
| 94 |
+
"num_nan_policy": None,
|
| 95 |
+
"cat_nan_policy": None,
|
| 96 |
+
"cat_min_frequency": None,
|
| 97 |
+
"cat_encoding": None,
|
| 98 |
+
"y_policy": "default"
|
| 99 |
+
}
|
| 100 |
+
metrics = train_catboost(
|
| 101 |
+
parent_dir=dir_,
|
| 102 |
+
real_data_path=real_data_path,
|
| 103 |
+
eval_type=eval_type,
|
| 104 |
+
T_dict=T_dict,
|
| 105 |
+
change_val=True,
|
| 106 |
+
seed = 0
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
score += metrics.get_val_score()
|
| 110 |
+
return score / 5
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
study = optuna.create_study(
|
| 114 |
+
direction='maximize',
|
| 115 |
+
sampler=optuna.samplers.TPESampler(seed=0),
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
study.optimize(objective, n_trials=50, show_progress_bar=True)
|
| 119 |
+
|
| 120 |
+
os.makedirs(f"exp/{Path(real_data_path).name}/tvae/", exist_ok=True)
|
| 121 |
+
config = {
|
| 122 |
+
"parent_dir": f"exp/{Path(real_data_path).name}/tvae/",
|
| 123 |
+
"real_data_path": real_data_path,
|
| 124 |
+
"seed": 0,
|
| 125 |
+
"device": args.device,
|
| 126 |
+
"train_params": study.best_trial.user_attrs["train_params"],
|
| 127 |
+
"sample": {"seed": 0, "num_samples": study.best_trial.user_attrs["num_samples"]},
|
| 128 |
+
"eval": {
|
| 129 |
+
"type": {"eval_model": "catboost", "eval_type": eval_type},
|
| 130 |
+
"T": {
|
| 131 |
+
"seed": 0,
|
| 132 |
+
"normalization": None,
|
| 133 |
+
"num_nan_policy": None,
|
| 134 |
+
"cat_nan_policy": None,
|
| 135 |
+
"cat_min_frequency": None,
|
| 136 |
+
"cat_encoding": None,
|
| 137 |
+
"y_policy": "default"
|
| 138 |
+
},
|
| 139 |
+
}
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
train_tvae(
|
| 143 |
+
parent_dir=f"exp/{Path(real_data_path).name}/tvae/",
|
| 144 |
+
real_data_path=real_data_path,
|
| 145 |
+
train_params=study.best_trial.user_attrs["train_params"],
|
| 146 |
+
change_val=False,
|
| 147 |
+
device=device
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
lib.dump_config(config, config["parent_dir"]+"config.toml")
|
| 151 |
+
|
| 152 |
+
subprocess.run(['python3.9', "scripts/eval_seeds.py", '--config', f'{config["parent_dir"]+"config.toml"}',
|
| 153 |
+
'10', "tvae", eval_type, "catboost", "5"], check=True)
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2022 Akim Kotelnikov
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/README.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# TabDDPM: Modelling Tabular Data with Diffusion Models
|
| 2 |
+
This is the official code for our paper "TabDDPM: Modelling Tabular Data with Diffusion Models" ([paper](https://arxiv.org/abs/2209.15421))
|
| 3 |
+
|
| 4 |
+
<!-- ## Results
|
| 5 |
+
You can view all the results and build your own tables with this [notebook](notebooks/Reports.ipynb). -->
|
| 6 |
+
|
| 7 |
+
## Setup the environment
|
| 8 |
+
1. Install [conda](https://docs.conda.io/en/latest/miniconda.html) (just to manage the env).
|
| 9 |
+
2. Run the following commands
|
| 10 |
+
```bash
|
| 11 |
+
export REPO_DIR=/path/to/the/code
|
| 12 |
+
cd $REPO_DIR
|
| 13 |
+
|
| 14 |
+
conda create -n tddpm python=3.9.7
|
| 15 |
+
conda activate tddpm
|
| 16 |
+
|
| 17 |
+
pip install torch==1.10.1+cu111 -f https://download.pytorch.org/whl/torch_stable.html
|
| 18 |
+
pip install -r requirements.txt
|
| 19 |
+
|
| 20 |
+
# if the following commands do not succeed, update conda
|
| 21 |
+
conda env config vars set PYTHONPATH=${PYTHONPATH}:${REPO_DIR}
|
| 22 |
+
conda env config vars set PROJECT_DIR=${REPO_DIR}
|
| 23 |
+
|
| 24 |
+
conda deactivate
|
| 25 |
+
conda activate tddpm
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
## Running the experiments
|
| 29 |
+
|
| 30 |
+
Here we describe the neccesary info for reproducing the experimental results.
|
| 31 |
+
Use `agg_results.ipynb` to print results for all dataset and all methods.
|
| 32 |
+
|
| 33 |
+
### Datasets
|
| 34 |
+
|
| 35 |
+
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.
|
| 36 |
+
|
| 37 |
+
You could load the datasets with the following commands:
|
| 38 |
+
|
| 39 |
+
``` bash
|
| 40 |
+
conda activate tddpm
|
| 41 |
+
cd $PROJECT_DIR
|
| 42 |
+
wget "https://www.dropbox.com/s/rpckvcs3vx7j605/data.tar?dl=0" -O data.tar
|
| 43 |
+
tar -xvf data.tar
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
### File structure
|
| 47 |
+
`tab-ddpm/` -- implementation of the proposed method
|
| 48 |
+
`tuned_models/` -- tuned hyperparameters of evaluation model (CatBoost or MLP)
|
| 49 |
+
|
| 50 |
+
All main scripts are in `scripts/` folder:
|
| 51 |
+
|
| 52 |
+
- `scripts/pipeline.py` are used to train, sample and eval TabDDPM using a given config
|
| 53 |
+
- `scripts/tune_ddpm.py` -- tune hyperparameters of TabDDPM
|
| 54 |
+
- `scripts/eval_[catboost|mlp|simple].py` -- evaluate synthetic data using a tuned evaluation model or simple models
|
| 55 |
+
- `scripts/eval_seeds.py` -- eval using multiple sampling and multuple eval seeds
|
| 56 |
+
- `scripts/eval_seeds_simple.py` -- eval using multiple sampling and multuple eval seeds (for simple models)
|
| 57 |
+
- `scripts/tune_evaluation_model.py` -- tune hyperparameters of eval model (CatBoost or MLP)
|
| 58 |
+
- `scripts/resample_privacy.py` -- privacy calculation
|
| 59 |
+
|
| 60 |
+
Experiments folder (`exp/`):
|
| 61 |
+
- All results and synthetic data are stored in `exp/[ds_name]/[exp_name]/` folder
|
| 62 |
+
- `exp/[ds_name]/config.toml` is a base config for tuning TabDDPM
|
| 63 |
+
- `exp/[ds_name]/eval_[catboost|mlp].json` stores results of evaluation (`scripts/eval_seeds.py`)
|
| 64 |
+
|
| 65 |
+
To understand the structure of `config.toml` file, read `CONFIG_DESCRIPTION.md`.
|
| 66 |
+
|
| 67 |
+
Baselines:
|
| 68 |
+
- `smote/`
|
| 69 |
+
- `CTGAN/` -- TVAE [official repo](https://github.com/sdv-dev/CTGAN)
|
| 70 |
+
- `CTAB-GAN/` -- [official repo](https://github.com/Team-TUD/CTAB-GAN)
|
| 71 |
+
- `CTAB-GAN-Plus/` -- [official repo](https://github.com/Team-TUD/CTAB-GAN-Plus)
|
| 72 |
+
|
| 73 |
+
### Examples
|
| 74 |
+
|
| 75 |
+
<ins>Run TabDDPM tuning.</ins>
|
| 76 |
+
|
| 77 |
+
Template and example (`--eval_seeds` is optional):
|
| 78 |
+
```bash
|
| 79 |
+
python scripts/tune_ddpm.py [ds_name] [train_size] synthetic [catboost|mlp] [exp_name] --eval_seeds
|
| 80 |
+
python scripts/tune_ddpm.py churn2 6500 synthetic catboost ddpm_tune --eval_seeds
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
<ins>Run TabDDPM pipeline.</ins>
|
| 84 |
+
|
| 85 |
+
Template and example (`--train`, `--sample`, `--eval` are optional):
|
| 86 |
+
```bash
|
| 87 |
+
python scripts/pipeline.py --config [path_to_your_config] --train --sample --eval
|
| 88 |
+
python scripts/pipeline.py --config exp/churn2/ddpm_cb_best/config.toml --train --sample
|
| 89 |
+
```
|
| 90 |
+
It takes approximately 7min to run the script above (NVIDIA GeForce RTX 2080 Ti).
|
| 91 |
+
|
| 92 |
+
<ins>Run evaluation over seeds</ins>
|
| 93 |
+
Before running evaluation, you have to train the model with the given hyperparameters (the example above).
|
| 94 |
+
|
| 95 |
+
Template and example:
|
| 96 |
+
```bash
|
| 97 |
+
python scripts/eval_seeds.py --config [path_to_your_config] [n_eval_seeds] [ddpm|smote|ctabgan|ctabgan-plus|tvae] synthetic [catboost|mlp] [n_sample_seeds]
|
| 98 |
+
python scripts/eval_seeds.py --config exp/churn2/ddpm_cb_best/config.toml 10 ddpm synthetic catboost 5
|
| 99 |
+
```
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/_compat_run.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections, collections.abc
|
| 2 |
+
for _a in ('Sequence','MutableSequence','MutableMapping','Mapping','MutableSet','Set','Callable','Iterable','Iterator'):
|
| 3 |
+
if not hasattr(collections, _a): setattr(collections, _a, getattr(collections.abc, _a, None))
|
| 4 |
+
import sys, runpy
|
| 5 |
+
sys.argv = sys.argv[1:]
|
| 6 |
+
runpy.run_path(sys.argv[0], run_name='__main__')
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/agg_results.ipynb
ADDED
|
@@ -0,0 +1,315 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"## Aggregating results to DataFrame"
|
| 8 |
+
]
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"cell_type": "code",
|
| 12 |
+
"execution_count": 1,
|
| 13 |
+
"metadata": {},
|
| 14 |
+
"outputs": [],
|
| 15 |
+
"source": [
|
| 16 |
+
"import os\n",
|
| 17 |
+
"import lib\n",
|
| 18 |
+
"import numpy as np\n",
|
| 19 |
+
"import pandas as pd\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"DATASETS = [\n",
|
| 22 |
+
" \"abalone\",\n",
|
| 23 |
+
" \"adult\",\n",
|
| 24 |
+
" \"buddy\",\n",
|
| 25 |
+
" \"california\",\n",
|
| 26 |
+
" \"cardio\",\n",
|
| 27 |
+
" \"churn2\",\n",
|
| 28 |
+
" \"default\",\n",
|
| 29 |
+
" \"diabetes\",\n",
|
| 30 |
+
" \"fb-comments\",\n",
|
| 31 |
+
" \"gesture\",\n",
|
| 32 |
+
" \"higgs-small\",\n",
|
| 33 |
+
" \"house\",\n",
|
| 34 |
+
" \"insurance\",\n",
|
| 35 |
+
" \"king\",\n",
|
| 36 |
+
" \"miniboone\",\n",
|
| 37 |
+
" \"wilt\"\n",
|
| 38 |
+
"]\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"_REGRESSION = [\n",
|
| 41 |
+
" \"abalone\",\n",
|
| 42 |
+
" \"california\",\n",
|
| 43 |
+
" \"fb-comments\",\n",
|
| 44 |
+
" \"house\",\n",
|
| 45 |
+
" \"insurance\",\n",
|
| 46 |
+
" \"king\",\n",
|
| 47 |
+
"]\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"method2exp = {\n",
|
| 51 |
+
" \"real\": \"exp/{}/ddpm_cb_best/\",\n",
|
| 52 |
+
" \"tab-ddpm\": \"exp/{}/ddpm_cb_best/\",\n",
|
| 53 |
+
" \"smote\": \"exp/{}/smote/\",\n",
|
| 54 |
+
" \"ctabgan+\": \"exp/{}/ctabgan-plus/\",\n",
|
| 55 |
+
" \"ctabgan\": \"exp/{}/ctabgan/\",\n",
|
| 56 |
+
" \"tvae\": \"exp/{}/tvae/\"\n",
|
| 57 |
+
"}\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"eval_file = \"eval_catboost.json\"\n",
|
| 60 |
+
"show_std = False\n",
|
| 61 |
+
"df = pd.DataFrame(columns=[\"method\"] + [_[:3].upper() for _ in DATASETS])\n",
|
| 62 |
+
"\n",
|
| 63 |
+
"for algo in method2exp: \n",
|
| 64 |
+
" algo_res = []\n",
|
| 65 |
+
" for ds in DATASETS:\n",
|
| 66 |
+
" if not os.path.exists(os.path.join(method2exp[algo].format(ds), eval_file)):\n",
|
| 67 |
+
" algo_res.append(\"--\")\n",
|
| 68 |
+
" continue\n",
|
| 69 |
+
" metric = \"r2\" if ds in _REGRESSION else \"f1\"\n",
|
| 70 |
+
" res_dict = lib.load_json(os.path.join(method2exp[algo].format(ds), eval_file))\n",
|
| 71 |
+
"\n",
|
| 72 |
+
" if algo == \"real\":\n",
|
| 73 |
+
" res = f'{res_dict[\"real\"][\"test\"][metric + \"-mean\"]:.4f}' \n",
|
| 74 |
+
" if show_std: res += f'+-{res_dict[\"real\"][\"test\"][metric + \"-std\"]:.4f}'\n",
|
| 75 |
+
" else:\n",
|
| 76 |
+
" res = f'{res_dict[\"synthetic\"][\"test\"][metric + \"-mean\"]:.4f}'\n",
|
| 77 |
+
" if show_std: res += f'+-{res_dict[\"synthetic\"][\"test\"][metric + \"-std\"]:.4f}'\n",
|
| 78 |
+
"\n",
|
| 79 |
+
" algo_res.append(res)\n",
|
| 80 |
+
" df.loc[len(df)] = [algo] + algo_res"
|
| 81 |
+
]
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"execution_count": 2,
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"outputs": [
|
| 88 |
+
{
|
| 89 |
+
"data": {
|
| 90 |
+
"text/html": [
|
| 91 |
+
"<div>\n",
|
| 92 |
+
"<style scoped>\n",
|
| 93 |
+
" .dataframe tbody tr th:only-of-type {\n",
|
| 94 |
+
" vertical-align: middle;\n",
|
| 95 |
+
" }\n",
|
| 96 |
+
"\n",
|
| 97 |
+
" .dataframe tbody tr th {\n",
|
| 98 |
+
" vertical-align: top;\n",
|
| 99 |
+
" }\n",
|
| 100 |
+
"\n",
|
| 101 |
+
" .dataframe thead th {\n",
|
| 102 |
+
" text-align: right;\n",
|
| 103 |
+
" }\n",
|
| 104 |
+
"</style>\n",
|
| 105 |
+
"<table border=\"1\" class=\"dataframe\">\n",
|
| 106 |
+
" <thead>\n",
|
| 107 |
+
" <tr style=\"text-align: right;\">\n",
|
| 108 |
+
" <th></th>\n",
|
| 109 |
+
" <th>method</th>\n",
|
| 110 |
+
" <th>ABA</th>\n",
|
| 111 |
+
" <th>ADU</th>\n",
|
| 112 |
+
" <th>BUD</th>\n",
|
| 113 |
+
" <th>CAL</th>\n",
|
| 114 |
+
" <th>CAR</th>\n",
|
| 115 |
+
" <th>CHU</th>\n",
|
| 116 |
+
" <th>DEF</th>\n",
|
| 117 |
+
" <th>DIA</th>\n",
|
| 118 |
+
" <th>FB-</th>\n",
|
| 119 |
+
" <th>GES</th>\n",
|
| 120 |
+
" <th>HIG</th>\n",
|
| 121 |
+
" <th>HOU</th>\n",
|
| 122 |
+
" <th>INS</th>\n",
|
| 123 |
+
" <th>KIN</th>\n",
|
| 124 |
+
" <th>MIN</th>\n",
|
| 125 |
+
" <th>WIL</th>\n",
|
| 126 |
+
" </tr>\n",
|
| 127 |
+
" </thead>\n",
|
| 128 |
+
" <tbody>\n",
|
| 129 |
+
" <tr>\n",
|
| 130 |
+
" <th>0</th>\n",
|
| 131 |
+
" <td>real</td>\n",
|
| 132 |
+
" <td>0.5562</td>\n",
|
| 133 |
+
" <td>0.8152</td>\n",
|
| 134 |
+
" <td>0.9063</td>\n",
|
| 135 |
+
" <td>0.8568</td>\n",
|
| 136 |
+
" <td>0.7379</td>\n",
|
| 137 |
+
" <td>0.7403</td>\n",
|
| 138 |
+
" <td>0.6880</td>\n",
|
| 139 |
+
" <td>0.7849</td>\n",
|
| 140 |
+
" <td>0.8371</td>\n",
|
| 141 |
+
" <td>0.6365</td>\n",
|
| 142 |
+
" <td>0.7238</td>\n",
|
| 143 |
+
" <td>0.6616</td>\n",
|
| 144 |
+
" <td>0.8137</td>\n",
|
| 145 |
+
" <td>0.9070</td>\n",
|
| 146 |
+
" <td>0.9342</td>\n",
|
| 147 |
+
" <td>0.8982</td>\n",
|
| 148 |
+
" </tr>\n",
|
| 149 |
+
" <tr>\n",
|
| 150 |
+
" <th>1</th>\n",
|
| 151 |
+
" <td>tab-ddpm</td>\n",
|
| 152 |
+
" <td>0.5499</td>\n",
|
| 153 |
+
" <td>0.7951</td>\n",
|
| 154 |
+
" <td>0.9057</td>\n",
|
| 155 |
+
" <td>0.8362</td>\n",
|
| 156 |
+
" <td>0.7374</td>\n",
|
| 157 |
+
" <td>0.7548</td>\n",
|
| 158 |
+
" <td>0.6910</td>\n",
|
| 159 |
+
" <td>0.7398</td>\n",
|
| 160 |
+
" <td>0.7128</td>\n",
|
| 161 |
+
" <td>0.5967</td>\n",
|
| 162 |
+
" <td>0.7218</td>\n",
|
| 163 |
+
" <td>0.6766</td>\n",
|
| 164 |
+
" <td>0.8092</td>\n",
|
| 165 |
+
" <td>0.8331</td>\n",
|
| 166 |
+
" <td>0.9362</td>\n",
|
| 167 |
+
" <td>0.9045</td>\n",
|
| 168 |
+
" </tr>\n",
|
| 169 |
+
" <tr>\n",
|
| 170 |
+
" <th>2</th>\n",
|
| 171 |
+
" <td>smote</td>\n",
|
| 172 |
+
" <td>0.5486</td>\n",
|
| 173 |
+
" <td>0.7912</td>\n",
|
| 174 |
+
" <td>0.8906</td>\n",
|
| 175 |
+
" <td>0.8397</td>\n",
|
| 176 |
+
" <td>0.7323</td>\n",
|
| 177 |
+
" <td>0.7432</td>\n",
|
| 178 |
+
" <td>0.6930</td>\n",
|
| 179 |
+
" <td>0.6835</td>\n",
|
| 180 |
+
" <td>0.8035</td>\n",
|
| 181 |
+
" <td>0.6579</td>\n",
|
| 182 |
+
" <td>0.7219</td>\n",
|
| 183 |
+
" <td>0.6625</td>\n",
|
| 184 |
+
" <td>0.8119</td>\n",
|
| 185 |
+
" <td>0.8416</td>\n",
|
| 186 |
+
" <td>0.9323</td>\n",
|
| 187 |
+
" <td>0.9127</td>\n",
|
| 188 |
+
" </tr>\n",
|
| 189 |
+
" <tr>\n",
|
| 190 |
+
" <th>3</th>\n",
|
| 191 |
+
" <td>ctabgan+</td>\n",
|
| 192 |
+
" <td>0.4672</td>\n",
|
| 193 |
+
" <td>0.7724</td>\n",
|
| 194 |
+
" <td>0.8844</td>\n",
|
| 195 |
+
" <td>0.5247</td>\n",
|
| 196 |
+
" <td>0.7327</td>\n",
|
| 197 |
+
" <td>0.7024</td>\n",
|
| 198 |
+
" <td>0.6865</td>\n",
|
| 199 |
+
" <td>0.7339</td>\n",
|
| 200 |
+
" <td>0.5088</td>\n",
|
| 201 |
+
" <td>0.4055</td>\n",
|
| 202 |
+
" <td>0.6639</td>\n",
|
| 203 |
+
" <td>0.5040</td>\n",
|
| 204 |
+
" <td>0.7966</td>\n",
|
| 205 |
+
" <td>0.4438</td>\n",
|
| 206 |
+
" <td>0.8920</td>\n",
|
| 207 |
+
" <td>0.7983</td>\n",
|
| 208 |
+
" </tr>\n",
|
| 209 |
+
" <tr>\n",
|
| 210 |
+
" <th>4</th>\n",
|
| 211 |
+
" <td>ctabgan</td>\n",
|
| 212 |
+
" <td>--</td>\n",
|
| 213 |
+
" <td>0.7831</td>\n",
|
| 214 |
+
" <td>0.8552</td>\n",
|
| 215 |
+
" <td>--</td>\n",
|
| 216 |
+
" <td>0.7171</td>\n",
|
| 217 |
+
" <td>0.6875</td>\n",
|
| 218 |
+
" <td>0.6437</td>\n",
|
| 219 |
+
" <td>0.7310</td>\n",
|
| 220 |
+
" <td>--</td>\n",
|
| 221 |
+
" <td>0.3922</td>\n",
|
| 222 |
+
" <td>0.5748</td>\n",
|
| 223 |
+
" <td>--</td>\n",
|
| 224 |
+
" <td>--</td>\n",
|
| 225 |
+
" <td>--</td>\n",
|
| 226 |
+
" <td>0.8892</td>\n",
|
| 227 |
+
" <td>0.9060</td>\n",
|
| 228 |
+
" </tr>\n",
|
| 229 |
+
" <tr>\n",
|
| 230 |
+
" <th>5</th>\n",
|
| 231 |
+
" <td>tvae</td>\n",
|
| 232 |
+
" <td>0.4328</td>\n",
|
| 233 |
+
" <td>0.7810</td>\n",
|
| 234 |
+
" <td>0.8638</td>\n",
|
| 235 |
+
" <td>0.7518</td>\n",
|
| 236 |
+
" <td>0.7174</td>\n",
|
| 237 |
+
" <td>0.7317</td>\n",
|
| 238 |
+
" <td>0.6564</td>\n",
|
| 239 |
+
" <td>0.7136</td>\n",
|
| 240 |
+
" <td>0.6853</td>\n",
|
| 241 |
+
" <td>0.4340</td>\n",
|
| 242 |
+
" <td>0.6378</td>\n",
|
| 243 |
+
" <td>0.4926</td>\n",
|
| 244 |
+
" <td>0.7842</td>\n",
|
| 245 |
+
" <td>0.8238</td>\n",
|
| 246 |
+
" <td>0.9125</td>\n",
|
| 247 |
+
" <td>0.5006</td>\n",
|
| 248 |
+
" </tr>\n",
|
| 249 |
+
" </tbody>\n",
|
| 250 |
+
"</table>\n",
|
| 251 |
+
"</div>"
|
| 252 |
+
],
|
| 253 |
+
"text/plain": [
|
| 254 |
+
" method ABA ADU BUD CAL CAR CHU DEF DIA \\\n",
|
| 255 |
+
"0 real 0.5562 0.8152 0.9063 0.8568 0.7379 0.7403 0.6880 0.7849 \n",
|
| 256 |
+
"1 tab-ddpm 0.5499 0.7951 0.9057 0.8362 0.7374 0.7548 0.6910 0.7398 \n",
|
| 257 |
+
"2 smote 0.5486 0.7912 0.8906 0.8397 0.7323 0.7432 0.6930 0.6835 \n",
|
| 258 |
+
"3 ctabgan+ 0.4672 0.7724 0.8844 0.5247 0.7327 0.7024 0.6865 0.7339 \n",
|
| 259 |
+
"4 ctabgan -- 0.7831 0.8552 -- 0.7171 0.6875 0.6437 0.7310 \n",
|
| 260 |
+
"5 tvae 0.4328 0.7810 0.8638 0.7518 0.7174 0.7317 0.6564 0.7136 \n",
|
| 261 |
+
"\n",
|
| 262 |
+
" FB- GES HIG HOU INS KIN MIN WIL \n",
|
| 263 |
+
"0 0.8371 0.6365 0.7238 0.6616 0.8137 0.9070 0.9342 0.8982 \n",
|
| 264 |
+
"1 0.7128 0.5967 0.7218 0.6766 0.8092 0.8331 0.9362 0.9045 \n",
|
| 265 |
+
"2 0.8035 0.6579 0.7219 0.6625 0.8119 0.8416 0.9323 0.9127 \n",
|
| 266 |
+
"3 0.5088 0.4055 0.6639 0.5040 0.7966 0.4438 0.8920 0.7983 \n",
|
| 267 |
+
"4 -- 0.3922 0.5748 -- -- -- 0.8892 0.9060 \n",
|
| 268 |
+
"5 0.6853 0.4340 0.6378 0.4926 0.7842 0.8238 0.9125 0.5006 "
|
| 269 |
+
]
|
| 270 |
+
},
|
| 271 |
+
"execution_count": 2,
|
| 272 |
+
"metadata": {},
|
| 273 |
+
"output_type": "execute_result"
|
| 274 |
+
}
|
| 275 |
+
],
|
| 276 |
+
"source": [
|
| 277 |
+
"df"
|
| 278 |
+
]
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"execution_count": null,
|
| 283 |
+
"metadata": {},
|
| 284 |
+
"outputs": [],
|
| 285 |
+
"source": []
|
| 286 |
+
}
|
| 287 |
+
],
|
| 288 |
+
"metadata": {
|
| 289 |
+
"kernelspec": {
|
| 290 |
+
"display_name": "Python 3.9.7 ('base')",
|
| 291 |
+
"language": "python",
|
| 292 |
+
"name": "python3"
|
| 293 |
+
},
|
| 294 |
+
"language_info": {
|
| 295 |
+
"codemirror_mode": {
|
| 296 |
+
"name": "ipython",
|
| 297 |
+
"version": 3
|
| 298 |
+
},
|
| 299 |
+
"file_extension": ".py",
|
| 300 |
+
"mimetype": "text/x-python",
|
| 301 |
+
"name": "python",
|
| 302 |
+
"nbconvert_exporter": "python",
|
| 303 |
+
"pygments_lexer": "ipython3",
|
| 304 |
+
"version": "3.9.7"
|
| 305 |
+
},
|
| 306 |
+
"orig_nbformat": 4,
|
| 307 |
+
"vscode": {
|
| 308 |
+
"interpreter": {
|
| 309 |
+
"hash": "a06af253165e97d0c1e75e8bf6d3252013856f30b8177e11b02d3fa36c37333d"
|
| 310 |
+
}
|
| 311 |
+
}
|
| 312 |
+
},
|
| 313 |
+
"nbformat": 4,
|
| 314 |
+
"nbformat_minor": 2
|
| 315 |
+
}
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/data.tar
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d9530d0aaff4791e7dfd44697594bfc45819ecb571a80d3bd4af60217fb61ee8
|
| 3 |
+
size 544923648
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_train.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8d2be5d993d10dfbfe8997fc73ada380331396c1265d4b66464e978b8a734e87
|
| 3 |
+
size 166049
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_cat_unnorm.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ada8f67106f3f6e8dad2dc55d8857edf2a3256da2234278f04d4e5e478b1e77
|
| 3 |
+
size 662528
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_train.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9c6c7d846995e547e63c454379e094bc793da6b8a3fbdaa7e360236bcd992bc5
|
| 3 |
+
size 2208128
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/X_num_unnorm.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2ccfb8b86bb13792e6150ef8dfe40a8a34f5f94e5fa7df9933cb3cd94773c05d
|
| 3 |
+
size 2428928
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/config.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:db1cf55340ae5364a05a1c840094ca47fff79dd584850c9ee751b2a097f7b075
|
| 3 |
+
size 922
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/info.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3dcb118d387bd15e6a79e571ad80c7a4fe900858c45ccea903e70a9550c86203
|
| 3 |
+
size 256
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/loss.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:426ab9f8eb46c9344fff5853a5e7543939beb14314f8f3f10e079a216dd108ef
|
| 3 |
+
size 610
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d879e391140052f56e8b1896df4fd47bfa25aee889ec81f7a47cfdc7beea8acc
|
| 3 |
+
size 1521051
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/model_ema.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ab7a9a3f8e65e549445f0ce927ad6849568a2f42061d0c9350128354ccd27efb
|
| 3 |
+
size 1521827
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/synth_train.csv
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6120646eb9dc9d83006b8ec2565f020c1b7aec589229211b8bf1d5432a3f4e07
|
| 3 |
+
size 1380080
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/Tab-Cate-1/ddpm_mlp_best/y_train.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:283e1a42f3e03025d2241c3c39135ca9c64ba4b7baf2d9586ee25004b68cc936
|
| 3 |
+
size 220928
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/config.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fe8c63e9f9a09cd9ca89affd4bb5e4d1545d59cdb31f9f73fb486257bbfd447f
|
| 3 |
+
size 920
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/config.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6bd872ae66f715fffcc92f2c7c4cc2246980b4df0e02b93738a8c9b4f697af0
|
| 3 |
+
size 539
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_catboost.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:42a3a2e2f22ebc24b66aaa3403869283f6576ce04e5fafa81fec15735d66aee3
|
| 3 |
+
size 459
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/eval_simple.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4d6478bba03b9309a26ef6e1247d95ce86668437fa08a6c5f15776ec9848a5e2
|
| 3 |
+
size 2424
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ctabgan-plus/info.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4b49fbcbcb81f577c2c56d703b327294a63a52fce9afa7b5fb98b20b61556c8c
|
| 3 |
+
size 199
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/config.toml
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cc6aa7d00bb5078f766e5d73ea4e04bbe8437bac44636cfd80a36b9262df0a01
|
| 3 |
+
size 920
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_catboost.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7ef5506437037908e0c0d5f0bd0c5eb3c61747d9de491d345dc0e8e8be3845b8
|
| 3 |
+
size 909
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_mlp.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fe4a3e4e117924a65d2da76254394ba8aae00555e30bebae916e154a925f0e3e
|
| 3 |
+
size 910
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aaf9df7911d5911b85f1a805c48a1c6d0e978e287c10f9ef78365b08a14da806
|
| 3 |
+
size 4809
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_ada.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0684462d69e5c1c8db2b1fad1ae7760be1849abcc5a623b5eaf07255b04a17f8
|
| 3 |
+
size 454
|
SynthData0523/main/c6/tabddpm/tabddpm-c6-20260510_222430/_tabddpm_runtime/exp/abalone/ddpm_cb_best/eval_simple_lr.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ce2cdfb51f7d37053edfa2250af17d1adef47d3e0eb141926a6a74a613c6cbb2
|
| 3 |
+
size 442
|