We are going to design a synthetic data factory benchmarking framework that evaluates:
- Fidelity metrics: how well the synthetic data mimics the real data in terms of statistical properties and machine learning utility.
- Privacy risks: the leakage of private information from the real data to the synthetic data.
- Downstream uplift: the improvement (if any) in downstream task performance when using synthetic data compared to using real data (or other baselines) in a privacy-preserving setting.
We'll break down the design into steps and define the key components.
Steps:
-
Data Ingestion and Preprocessing:
- We assume we have a real dataset D_real (with both features and labels, or just features for unsupervised tasks).
- Preprocess D_real: handle missing values, encode categorical variables, normalize, etc. We must store the preprocessing pipeline to apply the same to synthetic data.
-
Synthetic Data Generation:
- Use one or more synthetic data generation algorithms (e.g., SDV, CTGAN, TVAE, etc.) to generate synthetic datasets D_syn of the same size as D_real (or user-specified).
- The synthetic data should follow the same schema as the real data.
-
Fidelity Metrics:
a. Statistical Similarity:
- For each column (feature) in the dataset:
* For numerical: compare distributions using KL divergence, Wasserstein distance, or Earth Mover's Distance.
* For categorical: compare using total variation distance or chi-square test.
- For the joint distribution, we can use:
* PCA: Project both real and synthetic data onto principal components and compare the distributions (e.g., using MMD or Wasserstein).
* Pairwise correlations: Compute correlation matrix for real and synthetic (for numerical features) and compute Frobenius norm of the difference.
* For mixed data, we can use metrics like the Hellinger distance on binned frequencies or use the synthetic data metric from SDV (Normalized Synthesis Error).
b. Machine Learning Utility:
- Train a model (or set of models) on D_syn and evaluate on a holdout set from D_real (or vice versa) for a set of tasks (classification, regression, clustering).
- We can also do: train on real, evaluate on real (as a baseline) and on synthetic? But note: we want to see if models trained on synthetic can generalize to real.
- Alternatively, we can do:
* Split D_real into train and test.
* Train model on D_syn and evaluate on test (from real). Compare to model trained on real train and evaluated on same test.
* Also, we can do privacy-preserving training: train on synthetic and then fine-tune on a small amount of real data (if allowed) and compare.
- We report metrics like accuracy, F1, AUC, etc. (depending on task) and the relative drop/gain compared to training on real.
-
Privacy Risk Metrics:
a. Membership Inference Attacks (MIA):
- We assume an attacker has access to the synthetic data and some background knowledge (e.g., a set of records that may or may not be in the real data).
- We can perform a black-box MIA: train an attacker model to distinguish between samples that are in the real training set and those that are not, using the synthetic data as a reference.
- Alternatively, we can use the state-of-the-art MIA for synthetic data (like the one in SDV) which computes the distance (in feature space) of a query record to the synthetic data and compares to the distribution of distances for real records.
- Report the attack success rate (or advantage over random) and AUC.
b. Attribute Disclosure:
- For each record in the synthetic data, we can try to infer a sensitive attribute (if present) given the other attributes, and compare to the real data's baseline.
- We can also do: given a set of non-sensitive attributes, how well can we predict a sensitive one? Compare the model's accuracy on real vs synthetic.
c. Identity Disclosure (Re-identification):
- Measure the uniqueness of records in synthetic data compared to real. For example, the number of records in synthetic that are too close (in terms of a distance metric) to a single record in real.
- We can also use k-anonymity: for each synthetic record, find the number of real records that are within a certain distance (or in the same equivalence class). Low k means high risk.
d. Differential Privacy (if the generator is DP):
- If the generator claims to be differentially private, we can measure the privacy budget (epsilon, delta) spent.
-
Downstream Uplift:
- This is about the utility of synthetic data in a downstream task when real data is limited or cannot be used due to privacy.
- We consider a scenario where we have a small amount of real data (for validation and maybe fine-tuning) and we generate synthetic data to augment the training.
- We compare:
a. Training a model on real data only (with the available real data, which is small).
b. Training a model on synthetic data only (and then evaluating on real test).
c. Training a model on a mix of real and synthetic (with varying proportions).
- We measure the performance (e.g., accuracy) on a held-out real test set.
- The uplift is the improvement of (b) or (c) over (a). We can also compare to a baseline of no synthetic data (only real) and see if adding synthetic helps.
-
Reporting:
- We should produce a report that includes:
- Fidelity: statistical similarity scores and ML utility scores.
- Privacy: MIA success rate, attribute disclosure accuracy, re-identification risk, etc.
- Downstream: performance of models trained on synthetic, real, and mixed, with the relative improvement.
-
Implementation Plan:
- We can build this as a Python package that takes:
- Real dataset (and optionally a synthetic dataset, or a generator to generate synthetic)
- Configuration: which metrics to compute, which models to use, etc.
- Steps in code:
a. Preprocess real data and save the pipeline.
b. Generate synthetic data (if not provided) using the chosen generator(s).
c. Preprocess synthetic data with the same pipeline.
d. Compute fidelity metrics.
e. Compute privacy metrics.
f. Compute downstream uplift (if downstream task is specified).
g. Generate a report (JSON, HTML, or PDF).
-
Challenges and Considerations:
- The choice of metrics may depend on the data type (tabular, images, etc.) and the task. We focus on tabular data for now.
- Privacy metrics can be expensive (e.g., training an attacker model). We might need to subsample for large datasets.
- Downstream tasks require defining the task (classification/regression) and the model. We should allow the user to specify or use defaults.
Let's outline the code structure:
class SyntheticDataBenchmark:
def init(self, real_data, generator, downstream_task=None, task_type='classification', random_state=42):
self.real_data = real_data
self.generator = generator # an object with a sample method
self.downstream_task = downstream_task # if None, we skip downstream
self.task_type = task_type
self.random_state = random_state
def preprocess(self, data):
# implement preprocessing (or use a provided pipeline)
pass
def generate_synthetic(self, num_samples=None):
if num_samples is None:
num_samples = len(self.real_data)
synthetic_data = self.generator.sample(num_samples)
return synthetic_data
def compute_fidelity(self, real, synthetic):
# returns a dict of fidelity metrics
pass
def compute_privacy(self, real, synthetic):
# returns a dict of privacy metrics
pass
def compute_downstream(self, real_train, real_test, synthetic, mix_ratios=[0.0, 0.1, 0.5, 1.0]):
# mix_ratios: proportion of synthetic in the training set (0 means only real, 1 means only synthetic)
# We split the real data into train and test. Then for each ratio, we create a training set by mixing synthetic and real_train (by the ratio).
# Then train a model (maybe a simple one like RandomForest or a user-specified model) and evaluate on real_test.
# Return a dict: {ratio: performance_metric}
pass
def run(self):
# Step 1: preprocess real data and split for downstream (if needed)
# Step 2: generate synthetic
# Step 3: preprocess synthetic
# Step 4: compute fidelity
# Step 5: compute privacy
# Step 6: compute downstream if task provided
# Step 7: return a report
However, note: the downstream task might require a specific label column. We assume the real_data has a 'label' column or the user specifies the target.
Let's adjust:
We assume the input real_data is a DataFrame and we have a target column name.
We'll split the real data into:
real_train (for training models and for privacy attacks) and real_test (for evaluating downstream).
For privacy attacks, we might use the entire real data (or just the training part) to simulate membership.
Steps for privacy:
MIA: We split the real data into two parts: D_real_train and D_real_test (for the task). Then we generate synthetic data from D_real_train (or from the whole real?).
But note: the synthetic data generator is trained on the entire real data? In practice, we train the generator on the real data we have (which might be the training set for the downstream task). So:
Let D_real be the entire dataset we have (for training the generator). We split D_real into D_real_train (for training the generator) and D_real_test (for evaluation of downstream and for MIA?).
However, for MIA we want to see if the synthetic data leaks information about the training set of the generator. So we should train the generator on D_real_train and generate synthetic from that.
Then for MIA, we can have:
- A set of records that are in D_real_train (members)
- A set of records that are in D_real_test (non-members)
We then train an attacker on the synthetic data and these two sets.
Alternatively, we can do:
real_data_for_generator = D_real_train (if we are simulating a scenario where we generate synthetic from the training data) and then we have D_real_test for evaluation.
But note: the real_data we have might be the entire data we are allowed to use. So:
Scenario 1: We have a fixed real dataset D. We generate synthetic from D. Then we want to evaluate:
Fidelity: compare D_syn to D.
Privacy: we want to see if D_syn leaks about D (the entire set). So for MIA, we consider every record in D as a member and we need non-members. We can sample non-members from a different dataset (if available) or use a holdout from D? But note: if we holdout from D, then we are not generating synthetic from that holdout. So:
We split D into D_train and D_test.
Train generator on D_train -> generate D_syn.
Then for MIA:
members: D_train
non-members: D_test (and maybe an external dataset if available)
But then fidelity: we compare D_syn to D_train? Or to the entire D? Usually, we compare to the data the generator was trained on (D_train). So:
Steps:
1. Split real data D into D_train (for training generator) and D_test (for downstream and for non-members in MIA).
2. Train generator on D_train.
3. Generate synthetic data D_syn from the generator (same size as D_train or user specified).
4. Preprocess D_train, D_test, and D_syn with the same pipeline (fit on D_train, transform on all).
5. Fidelity: compare D_syn (preprocessed) to D_train (preprocessed).
6. Privacy:
a. MIA: we have members = D_train, non-members = D_test (and optionally external). We train an attacker to distinguish.
b. Attribute disclosure: we can train a model to predict a sensitive attribute on D_train and then see if the same model (trained on D_syn) can predict the same on D_test? Or we can directly compute the predictive power of the sensitive attribute from the non-sensitive ones in D_syn and compare to D_train?
Actually, attribute disclosure is about the leakage of the sensitive attribute in the synthetic data. We can do:
- Train a model on D_syn (without the sensitive attribute) to predict the sensitive attribute, and evaluate on D_test. Compare to a model trained on D_train (without sensitive) to predict sensitive on D_test. If the model trained on D_syn is almost as good, then there is leakage.
- Alternatively, we can compute the mutual information between the sensitive attribute and the other attributes in D_syn and compare to D_train.
c. Identity disclosure: We can compute for each record in D_syn, the minimum distance to any record in D_train. If there is a record that is too close (or identical) then there is risk. We can set a threshold and compute the proportion of synthetic records that are within that threshold of a real record.
7. Downstream:
We have D_train (real) and D_syn. We want to train a model for a task (with target label). We can do:
- Train on D_train (only real) and evaluate on D_test -> baseline.
- Train on D_syn (only synthetic) and evaluate on D_test -> synthetic only.
- Train on a mixture: (1-alpha)*D_train + alpha*D_syn, for alpha in [0,0.1,...,1] and evaluate on D_test.
So we need to split the real data at the beginning.
Let's adjust the class:
We assume the input is a DataFrame real_data and we have a test_size (for the holdout) and a random_state.
Steps:
1. Split real_data into train and test (stratified if classification).
2. Preprocess: fit preprocessing on train, transform train and test.
3. Train generator on preprocessed train.
4. Generate synthetic from the generator (same size as train or user specified).
5. Preprocess synthetic with the same pipeline (already fitted on train, so just transform).
6. Then run the three sets of metrics.
However, note: the generator might require the original (unpreprocessed) data? It depends. Some generators can handle categorical and numerical without preprocessing. But to be consistent, we might want to preprocess the data to a numerical format (one-hot for categorical, etc.) because many generators require numerical. Alternatively, we can let the user specify the preprocessing for the generator.
We can design:
- The user can pass a preprocessing pipeline for the generator (which might be different from the downstream preprocessing). But for simplicity, we assume we preprocess the real data to a numerical matrix (with one-hot for categorical) and then generate synthetic in that space. Then we can invert the preprocessing for the synthetic? But then for downstream we might want the original format.
Alternatively, we can:
- Keep the real data in original format for the generator (if the generator can handle mixed types). Then for fidelity and downstream, we preprocess to a common numerical format.
Let's assume:
We have two preprocessing steps:
1. Preprocessing for the generator: this might be specific to the generator (e.g., SDV's TableMetadata and then fit_transform). We can let the user pass a `generator_preprocessor` that takes a DataFrame and returns a DataFrame (or array) that the generator can use.
2. Preprocessing for downstream: we might want to one-hot encode categoricals and normalize numericals for the downstream model.
But then we have to be consistent: the synthetic data we generate is in the generator's preprocessed space. We then need to preprocess the real train and test in the same way for fidelity? Actually, for fidelity we want to compare in the same space. So:
Option A: Use the same preprocessing for both generator and downstream (and for fidelity). Then we preprocess the real data (train and test) and then train the generator on the preprocessed train. Then synthetic is in that space. Then for downstream we use the same preprocessed data.
But note: some generators (like CTGAN) require the data to be in a specific format (e.g., one-hot encoded). So we might have to preprocess for the generator and then for downstream we might want to use the same one-hot, but then the downstream model might work better with one-hot.
So we can do:
1. Preprocess the real data (train and test) with a pipeline that:
- For numerical: standard scaling (or min-max) and maybe keep as is.
- For categorical: one-hot encoding.
2. Then train the generator on the preprocessed train.
3. Generate synthetic in the preprocessed space.
4. Then for fidelity, we compare the preprocessed train and the synthetic (both in the same space).
5. For downstream, we use the preprocessed train (real) and synthetic (already preprocessed) and preprocessed test.
6. For privacy, we use the preprocessed train and test and synthetic.
So we assume the user provides a preprocessing function that we apply to the real train and test, and then the generator is trained on the preprocessed train.
But note: the generator might have its own way of handling categoricals. For example, CTGAN uses a one-hot encoding internally. So if we one-hot encode externally, then CTGAN will see the one-hot columns as separate. That's acceptable.
Alternatively, we can let the generator handle the preprocessing? But then we have to reverse it for the synthetic data to compare with the real? It gets messy.
Let's stick to: we preprocess the real data to a numerical matrix (with one-hot for categorical) and then train the generator on that. Then synthetic is in that same matrix. We don't need to invert.
Steps:
real_data: DataFrame with mixed types.
Preprocessing:
numerical_cols = real_data.select_dtypes(include=['int64', 'float64']).columns
categorical_cols = real_data.select_dtypes(include=['object', 'category']).columns
Preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), numerical_cols),
('cat', OneHotEncoder(handle_unknown='ignore'), categorical_cols)
])
Then fit on real_train, transform real_train and real_test.
Then train generator on real_train_preprocessed.
Then generate synthetic_preprocessed.
Then:
Fidelity: compare real_train_preprocessed and synthetic_preprocessed.
Privacy: use real_train_preprocessed, real_test_preprocessed, synthetic_preprocessed.
Downstream: use real_train_preprocessed, synthetic_preprocessed, real_test_preprocessed.
But note: the downstream task might require the original labels? We assume the label is included in the preprocessed data? Or we separate?
We should separate the features and the label for downstream.
Let's assume the user specifies the target column (label). Then:
In the real_data, we have a column for the label. We do not preprocess the label? Actually, for classification, we might need to encode the label. But note: the generator should not generate the label? It depends. If we are generating synthetic for the entire dataset (including label) then we include the label in the preprocessing? But then the generator will generate the label too.
We have two cases:
1. We generate synthetic for the entire dataset (features and label). Then we preprocess the entire dataset (including label) but then separate for downstream.
2. We generate synthetic only for the features, and then we use the real labels? But then we cannot generate synthetic labels that match the features? So we must generate the label as well.
So we assume the generator is trained on the entire dataset (features and label) for supervised tasks. For unsupervised, we don't have a label.
Therefore, we include the label in the preprocessing? But note:
For the label:
If it's categorical, we one-hot encode? But then for classification we usually have a single column for the label (with integer or string). If we one-hot encode the label, then we have multiple columns for the label. Then the downstream model would have to output multiple columns? That's not standard.
So we should not one-hot encode the label. We should leave the label as is (or encode as integer for classification) and then for regression, leave as numerical.
How to handle:
We separate the label column before preprocessing the features? But then the generator needs the label to be in the same space?
Alternatively, we can preprocess the features and the label separately.
Let's adjust:
We have:
X_real_train = real_train.drop(columns=[label])
y_real_train = real_train[label]
Then preprocess X_real_train -> X_real_train_preprocessed.
Then we concatenate X_real_train_preprocessed and y_real_train (if y_real_train is categorical, we might need to encode it to integer? but the generator expects the same type as the original?).
Actually, the generator should be trained on the entire table (with the label as a column). So we need to put the label back.
But then when we generate synthetic, we get a table with the same columns (including the label). Then we separate into X_syn and y_syn.
For downstream, we train on (X_syn, y_syn) and test on (X_real_test_preprocessed, y_real_test).
But note: the label might be categorical and we haven't encoded it. Then the downstream model must handle the label as string? That's okay for some models (like RandomForest) but not for others.
Alternatively, we can encode the label to integer for the generator? But then the synthetic label will be integer. And the downstream model will get integer labels.
So:
Preprocessing for features: as above.
For the label: if it's string, we use a LabelEncoder to convert to integer. Then we inverse transform after generation? But we don't need to inverse for downstream because we are comparing the label in the same integer space.
Steps:
1. Encode the label:
le = LabelEncoder()
y_real_train_encoded = le.fit_transform(y_real_train)
y_real_test_encoded = le.transform(y_real_test)
2. Preprocess X_real_train -> X_real_train_preprocessed.
3. Form the training table for generator:
train_table = pd.concat([X_real_train_preprocessed, pd.Series(y_real_train_encoded, index=X_real_train_preprocessed.index, name=label)], axis=1)
4. Train generator on train_table.
5. Generate synthetic_table (same size as train_table) from generator.
6. Separate synthetic_table into X_syn_preprocessed and y_syn_encoded.
7. For downstream: we have (X_syn_preprocessed, y_syn_encoded) and (X_real_test_preprocessed, y_real_test_encoded).
But note: the synthetic data might have label columns that are not exactly the integers 0,1,... because the generator might generate continuous values? We need to round? Or the generator should be trained with integer labels and generate integers? It depends on the generator.
Alternatively, we can treat the label as categorical and one-hot encode it? Then the generator would generate multiple columns for the label? Then for classification, we would have to convert the one-hot back to integer? This is getting complicated.
Simpler: for classification, we keep the label as integer (or string) and let the generator handle it as a categorical column. For regression, we keep it as numerical.
So in the preprocessing, we only preprocess the features. The label is left as is (but we might encode string labels to integer for consistency).
Then the table for the generator has the preprocessed features and the original label (which might be integer for classification, or float for regression).
Then when we generate synthetic, we get a table with the same columns. We then separate the label.
This is acceptable.
But note: the generator might require all columns to be of the same type? Usually, they can handle mixed.
So let's design:
We assume:
real_data: DataFrame.
label: string, the name of the target column.
We split real_data into train and test (with stratification if classification).
Preprocessing:
numerical_features = real_data.select_dtypes(include=['int64', 'float64']).columns.drop(label)
categorical_features = real_data.select_dtypes(include=['object', 'category']).columns.drop(label)
preprocessor = ColumnTransformer(
transformers=[
('num', StandardScaler(), numerical_features),
('cat', OneHotEncoder(handle_unknown='ignore'), categorical_features)
])
Fit on X_train (without label). Transform X_train and X_test.
Then:
X_train_preprocessed = preprocessor.transform(X_train) -> this is a numpy array (or sparse matrix)
X_test_preprocessed = preprocessor.transform(X_test)
We also have y_train and y_test.
If y_train is string, we encode it with a LabelEncoder to get y_train_encoded and y_test_encoded.
Then form the training table for the generator:
train_table = pd.DataFrame(X_train_preprocessed, columns=preprocessor.get_feature_names_out())
train_table[label] = y_train_encoded # or y_train if already numeric
Then train generator on train_table.
Then generate synthetic_table (with same number of rows as train_table) from generator.
Then:
X_syn_preprocessed = synthetic_table.drop(columns=[label])
y_syn_encoded = synthetic_table[label]
Then for downstream:
We have:
Real: (X_train_preprocessed, y_train_encoded) and (X_test_preprocessed, y_test_encoded)
Synthetic: (X_syn_preprocessed, y_syn_encoded)
For downstream uplift, we can mix X_train_preprocessed and X_syn_preprocessed, and correspondingly y_train_encoded and y_syn_encoded.
For fidelity: compare train_table (which is X_train_preprocessed + y_train_encoded) and synthetic_table (X_syn_preprocessed + y_syn_encoded) on all columns? But note: the label distribution should also be similar? Yes.
So for fidelity, we treat the entire table (including label) as the data to compare.
For privacy: we use the preprocessed train and test (including label) and synthetic.
However, note: the one-hot encoded features for categoricals are now multiple columns. The generator might generate synthetic values that are not exactly 0/1? We might need to threshold? But the generator should generate in the same domain.
Given the complexity, we might want to let the user specify the preprocessing for the generator and for the downstream separately? But that would break the consistency.
Alternatively, we can avoid one-hot encoding for the generator and use an encoding that the generator can handle (like integer encoding for categoricals) and then for downstream we use one-hot? But then the synthetic data would be in integer encoding for categoricals and we would have to one-hot encode it for downstream? That would be inconsistent.
Given the time, let's assume we use the same preprocessing for both generator and downstream, and that the generator can handle the preprocessed data (which is all numerical). Then:
- All features are numerical (after one-hot for categoricals).
- The label is either integer (for classification) or float (for regression).
Then the generator is trained on a numerical table.
Then synthetic is numerical.
Then for downstream, we use the same numerical features.
This is consistent.
Steps:
1. Split real_data into train and test.
2. Preprocess the features (X) of train and test to numerical (one-hot for categorical, scale for numerical).
3. Encode the label (if string) to integer for classification.
4. Form train_table (preprocessed X + encoded y) and test_table (preprocessed X_test + encoded y_test).
5. Train generator on train_table.
6. Generate synthetic_table (same size as train_table).
7. Now we have:
real_train = train_table (DataFrame with numerical columns and label column)
real_test = test_table
synthetic = synthetic_table
8. Fidelity: compare real_train and synthetic (all columns). We can do:
For each column (including label):
if numerical: compute Wasserstein distance, etc.
if categorical? But note: after one-hot, we have multiple columns for one categorical. So we should group by the original categorical? Or treat each one-hot column as binary? Then we can compute the difference in the proportion of 1s for each one-hot column.
Alternatively, we can compute the overall distribution by flattening all columns? Not ideal.
We can compute:
For numerical columns (including the label if regression, or the encoded label for classification) we use Wasserstein.
For the one-hot columns (which are binary) we can use the total variation of the proportion of 1s.
But note: the one-hot columns are derived from the same categorical. We might want to compute the distribution of the original categorical. How?
We can convert the one-hot columns back to the original categorical by taking argmax? But if the synthetic generates values that are not exactly 0/1, we might get multiple 1s? We should threshold at 0.5? This is messy.
Alternatively, we can compute the fidelity on the original (unpreprocessed) data? But then the synthetic data is in the preprocessed space. We would have to invert the preprocessing for the synthetic? But one-hot encoding is not invertible if there are unknown categories.
Given the complexity, we might decide to only compute fidelity on the numerical columns (including the label) and ignore the one-hot columns? But that ignores the categorical distributions.
Another idea: we can compute the fidelity on the joint distribution by using a model-based metric. For example, train a classifier to distinguish real from synthetic (using all preprocessed features) and report the AUC. If the classifier cannot distinguish, then the distributions are similar.
This is a common approach in synthetic data evaluation: the discriminative metric.
So we can do:
Combine real_train and synthetic, label them as 0 and 1, and train a classifier (like a gradient boosting) to distinguish. Then the AUC (or accuracy) indicates how distinguishable they are. Lower is better (0.5 is random).
This captures both marginals and joint.
We can also do this for each individual column? But the joint is more important.
So we propose:
Fidelity metric 1: Discriminative AUC (or accuracy) of a classifier trained to separate real and synthetic.
Fidelity metric 2: For each original column (before one-hot), we can compute the distribution similarity by:
For numerical: Wasserstein between real and synthetic (using the original numerical column, but note: the synthetic is generated from the preprocessed data, so we have to invert the preprocessing for that numerical column? Actually, the numerical columns are scaled. We can unscale? We stored the scaler, so we can inverse transform the numerical columns in the synthetic and real_train to the original scale and then compute Wasserstein? That would be on the original scale.
For categorical: we can compute the frequency of each category in real and synthetic (by converting the one-hot columns back to the original categorical) and then compute total variation.
But note: the one-hot columns in synthetic might not be exactly 0/1. We can take the one-hot column with the maximum value as the category? Or we can use the probabilities?
Given the complexity, we might skip the per-column metrics and rely on the discriminative metric and the downstream utility.
However, the discriminative metric does not tell us which aspects are bad.
We can do:
For each original column (feature or label):
If numerical:
unscale the column in real_train and synthetic (using the stored scaler for that column) and compute Wasserstein.
If categorical:
For real_train: we have the original categorical (since we didn't change it). For synthetic: we have the one-hot columns. We can convert the one-hot to categorical by taking the column with the highest value as the category. Then compute the frequency of each category in real and synthetic and then the total variation.
But note: the synthetic might generate values that are not exactly one-hot (e.g., 0.3, 0.7). We can take the argmax as the category.
This is doable.
So we store:
For numerical: the scaler (StandardScaler) for each numerical column? Actually, the ColumnTransformer stores the scaler for the numerical part. We can get the scaler for each column by the order? Or we can store the feature names and the scalers.
Alternatively, we can avoid inverting the scaling and compute the Wasserstein on the scaled data? But then the scale is arbitrary and the Wasserstein distance would be on the scaled space, which might not be interpretable.
We want to compare in the original space.
So we need to store the scalers for the numerical columns to inverse transform.
Similarly for the label if it's numerical? We don't scale the label? We only scale the features. The label is left as is (or encoded as integer). So for the label, we don't need to inverse.
So:
For numerical features: we have a scaler. We can unscale both real_train and synthetic for that feature and then compute Wasserstein.
For categorical features: we have the original categorical in real_train. For synthetic, we convert the one-hot columns (for that categorical) to the original by taking the argmax.
But note: the one-hot columns are named like 'cat_feature_<category>'. We can group by the original feature name.
Steps for categorical:
Suppose we have a categorical feature 'color' with categories ['red','green','blue'].
In the preprocessed data, we have columns: 'color_red', 'color_green', 'color_blue'.
For each row in synthetic, we look at these three columns and pick the one with the maximum value as the category. If there are ties? Then we can pick randomly? Or we can use the one with the highest value and if tie, then choose the first? This might introduce bias.
Alternatively, we can use the synthetic probabilities and compute the expected distribution? That would be:
For each category, the synthetic probability is the average of the corresponding one-hot column (if we had true one-hot, then it would be the frequency). But if the synthetic generates values that are not exactly one-hot, we can still average the column and that gives the marginal probability of that category.
So we can compute:
real_dist: frequency of each category in real_train['color'].
synthetic_dist: the mean of the one-hot columns for 'color_red', etc.
Then we compute total variation between these two distributions.
This is better because it uses the soft assignments.
So for categorical, we compute the marginal distribution by averaging the one-hot columns.
For the label:
If the label is categorical, we do the same: we have one-hot columns for the label? No, we did not one-hot the label. We encoded it as integer. So for the label, we have a single column (integer). Then we can compute the frequency of each integer class in real and synthetic and then total variation.
If the label is numerical (regression), we compute Wasserstein on the original scale? But we didn't scale the label. So we can compute directly.
So:
For each column in the original table (features and label):
If numerical (and not the label? but the label could be numerical) and the column was scaled (so it's in the numerical_features) then we unscale and compute Wasserstein.
If categorical (and not the label) then we compute the marginal distribution by averaging the one-hot columns (for that feature) and then total variation.
If the label is categorical (and we encoded as integer) then we compute the frequency of each integer and total variation.
If the label is numerical (regression) then we compute Wasserstein (without scaling because we didn't scale the label).
But note: the label column in the preprocessed table is the encoded label (for classification) or the original (for regression). So we can treat it separately.
We can store:
- The list of numerical features (that were scaled) and their scalers.
- The list of categorical features (that were one-hotted) and the one-hot encoder.
- The label column and its type (categorical or numerical).
Then:
For a numerical feature (that was scaled):
real_column = real_train[feature] * scaler.scale_ + scaler.mean_ (or use inverse_transform)
synthetic_column = synthetic[feature] * scaler.scale_ + scaler.mean_
Then compute Wasserstein(real_column, synthetic_column)
For a categorical feature (that was one-hotted):
real_dist: we can get from real_train[original_feature] by counting (but we have the original real_train? We have the original real_data? We should store the original real_train for the categorical? Actually, we have the original real_train (before preprocessing) for the categorical features? We have the original real_train (the split) which has the original categorical. So we can compute the real_dist from that.
synthetic_dist: for the one-hot columns for that feature, compute the mean of each one-hot column (these are the probabilities for each category). Then we have a distribution over the categories.
Then total variation between real_dist and synthetic_dist.
For the label:
If label is categorical (and we encoded as integer):
real_dist: frequency of each integer in y_train_encoded.
synthetic_dist: frequency of each integer in y_syn_encoded.
total variation.
If label is numerical:
real: y_train (original, not scaled) and synthetic: y_syn_encoded (which is the same as the label in the synthetic table? and we didn't scale the label). So we can compute Wasserstein.
But note: the synthetic label for classification is integer, same as y_syn_encoded.
This seems consistent.
However, note: the synthetic data might have label values that are not in the training set? Then for categorical, we would have a category that doesn't exist in real? We should include all categories from the real in the distribution for real, and for synthetic we might have extra? Then the total variation would be computed on the union of categories? We can do:
categories = sorted(set(real_dist.keys()) | set(synthetic_dist.keys()))
Then create vectors for real and synthetic of length len(categories) with 0 for missing.
This is getting very detailed.
Given the time, we might simplify:
We compute:
1. Discriminative AUC (for the entire table) as a joint fidelity metric.
2. For each column (as originally in real_data, including label) we compute:
if numerical:
We have the original real_train column (without preprocessing) and we have the synthetic column? But the synthetic column is in the preprocessed space? We have the synthetic table in the preprocessed space. We can un-preprocess the synthetic column for that numerical feature? We stored the scaler for that feature? Actually, we have the scaler for the numerical features. So we can unscale the synthetic column for that feature and compare to the original real_train column.
if categorical:
We have the original real_train column (categorical) and from the synthetic we have the one-hot columns for that categorical. We compute the synthetic distribution by averaging the one-hot columns. Then we compute the total variation between the real distribution (from real_train) and the synthetic distribution.
But note: the synthetic might have one-hot columns for categories that were not in the training set? Then the one-hot encoder for the real data didn't have that category, so the synthetic might have a column for a new category? We set handle_unknown='ignore' in the one-hot encoder, so the synthetic should not have columns for unknown categories? Actually, the one-hot encoder we used for the real data has a fixed set of categories. The synthetic data is generated in the same space, so it should only have the same one-hot columns? Not necessarily: the generator might generate values that when argmax'ed give a category that was not in the training set? But the one-hot columns are fixed. So the synthetic data will have the same set of one-hot columns as the real train? Yes, because the generator is trained on the preprocessed data that has the same columns (including the one-hot columns). So the synthetic table will have the same columns as the train_table. So the one-hot columns for a categorical feature are fixed and known.
Therefore, for a categorical feature, the synthetic distribution is a vector of length equal to the number of categories (from the one-hot encoder). The real distribution is a vector of the same length (with zeros for categories that didn't appear in the real train? But the one-hot encoder was fit on the real train, so it has all categories that appear in the real train. So the real distribution is computed from the real_train[feature] and will have non-zero only for the categories that appear. But the synthetic distribution might have non-zero for categories that are in the one-hot encoder but didn't appear in real? That's possible. Then the total variation will account for that.
So:
real_dist = pd.Series(0, index=one_hot_columns_for_this_feature)
real_counts = real_train[feature].value_counts()
for category, count in real_counts.items():
column_name = f"{feature}_{category}"
if column_name in one_hot_columns_for_this_feature:
real_dist[column_name] = count / len(real_train)
synthetic_dist = synthetic[one_hot_columns_for_this_feature].mean()
Then total_variation = 0.5 * np.sum(np.abs(real_dist - synthetic_dist))
This is for each categorical feature.
For numerical feature:
We have the scaler for that feature. We unscale both real and synthetic:
real_original = real_train[feature] * scaler.scale_ + scaler.mean_
synthetic_original = synthetic[feature] * scaler.scale_ + scaler.mean_
Then compute Wasserstein(real_original, synthetic_original)
For the label:
If label is categorical (and we encoded as integer) then we don't have one-hot for the label. We have a single column. So:
real_dist: value_counts of y_train_encoded (normalized)
synthetic_dist: value_counts of y_syn_encoded (normalized)
total_variation.
If label is numerical:
We didn't scale the label, so we can compute Wasserstein between y_train and y_syn_encoded.
This seems workable.
But note: the synthetic data for the label in classification is integer, but the generator might have generated non-integer? We round? We assume the generator generates integer for the label if it's categorical? Not necessarily. We might have to round to the nearest integer and then clip to the valid range.
Alternatively, we can compute the distribution without rounding? For example, we can bin the synthetic label values and compare to the real distribution? But the real are integers.
Given the complexity, we might assume that for classification the label is integer and the generator generates integer? Or we can round the synthetic label to the nearest integer and then clip to [0, n_classes-1].
We'll do:
If label is categorical and we encoded as integer:
y_syn_encoded_rounded = np.round(y_syn_encoded).astype(int)
y_syn_encoded_rounded = np.clip(y_syn_encoded_rounded, 0, n_classes-1)
Then compute distribution.
For regression, we don't round.
Now, for privacy:
We have:
real_train_preprocessed (which is the train_table without the label? or with the label? We have the entire train_table). We'll use the entire table (features and label) for privacy? Because the synthetic data includes the label. So for MIA, we want to see if the synthetic data leaks about any column (including the label).
So we use the preprocessed data (including the label) for privacy.
Steps for MIA:
We have:
members: real_train_preprocessed (the data used to train the generator)
non-members: real_test_preprocessed (and optionally external data)
We generate an attacker that, given a record (from either members or non-members), predicts the probability that it is a member.
How to train the attacker?
We can train a binary classifier on the synthetic data and the real data? But note: the attacker is trying to distinguish between real members and real non-members. So we need a dataset of records with membership labels.
We can take:
positive examples: real_train_preprocessed (members)
negative examples: real_test_preprocessed (non-members) and maybe external data (if available) to make it harder.
But then the attacker is trained on real data? That might not be the threat model. The attacker only has the synthetic data and maybe some side information? Actually, in MIA for synthetic data, the attacker has the synthetic data and wants to know if a given record (which is either from the real training set or not) is in the training set.
We can do:
Train a model (the attacker) on the synthetic data? But the synthetic data does not have membership labels.
Alternatively, we can use the approach from the paper "Synthetic Data Privacy Evaluation" (SDV) where they use the distance to the synthetic data.
Another approach: train a classifier on the synthetic data to predict the record's features? Then use the prediction error as a signal? Not sure.
We can do:
We assume the attacker has access to the synthetic data and the target record (with all features). Then the attacker can compute the distance (e.g., Euclidean) from the target record to the synthetic data. Then we compare the distribution of distances for members and non-members.
Steps:
For each record in members (real_train_preprocessed) and non-members (real_test_preprocessed):
Compute the minimum distance to any synthetic record (in the same feature space).
Then we have two distributions of distances. We can train a classifier (like a threshold or a logistic regression) on these distances to predict membership.
Then we compute the AUC of this classifier.
This is a simple MIA.
We can also use more complex attacks, like training a shadow generator? But that's more expensive.
We'll implement:
For each real record (in members and non-members), compute:
d = min_{s in synthetic} ||real_record - s||_2
Then we have a vector of distances for members and for non-members.
Then we train a logistic regression (or just use a threshold) to distinguish.
We report the AUC.
We might also want to report the true positive rate at a false positive rate of 0.1, etc.
Attribute disclosure:
We assume there is a sensitive attribute (which could be the label or another column). We need to specify which column is sensitive.
Steps:
Let S be the sensitive attribute column.
We want to know: given the non-sensitive attributes, can we predict S? And does the synthetic data leak information about S?
We can do:
Train a model (attribute inference attack) on the synthetic data (without S) to predict S. Then evaluate on the real test data (without S) and compare to the accuracy of a model trained on the real train data (without S) and evaluated on the real test.
But note: the synthetic data might have a different distribution of S? So the baseline accuracy on real test for a model trained on real train might be high because the distributions match. If the synthetic data has a different distribution of S, then the model trained on synthetic might have low accuracy even without leakage.
Alternatively, we can compute the mutual information between S and the non-sensitive attributes in the synthetic data and compare to the real data.
We can do:
For real_train: compute the mutual information between S and the non-sensitive features (maybe using a decision tree or just using the conditional entropy?).
For synthetic: compute the same.
But mutual information is hard to estimate.
Another approach: train a classifier to predict S from the non-sensitive features on the real_train and get accuracy A_real. Then train the same classifier on synthetic (without S) and evaluate on real_test to get accuracy A_syn_on_real. Then if A_syn_on_real is close to A_real, then the synthetic data has similar predictive power of S from the non-sensitive features, meaning there is leakage.
However, note: the synthetic data might have a different distribution of the non-sensitive features. So we should evaluate both models on the same real_test. Then:
Model1 (trained on real_train) on real_test: accuracy1.
Model2 (trained on synthetic) on real_test: accuracy2.
Then we compare accuracy2 to accuracy1. If accuracy2 is close to accuracy1, then the synthetic data preserved the relationship.
But what if the synthetic data has a different distribution of S? Then even if the relationship is preserved, the accuracy might be low because the test distribution of S is different? We are evaluating on the same real_test, so the distribution of S in the test is fixed. So if the synthetic model has learned the same relationship, then accuracy2 should be close to accuracy1.
So:
Let S be the sensitive attribute (which we assume is a column in the data). We remove S from the features and use it as the label for the attribute inference attack.
Steps:
1. For real_train:
X_train = real_train without S
y_train = real_train[S]
2. For synthetic:
X_syn = synthetic without S
y_syn = synthetic[S]
3. For real_test:
X_test = real_test without S
y_test = real_test[S]
4. Train a model (e.g., RandomForest) on (X_train, y_train) -> model_real
5. Train the same model on (X_syn, y_syn) -> model_syn
6. Evaluate both on (X_test, y_test) and compute accuracy (or other metrics).
7. The leakage is the difference in accuracy? Or the ratio? We can report both accuracies.
But note: if S is the label for the downstream task, then we are already using S as the label. Then this attack is exactly the downstream task? Not necessarily: the downstream task might use all features including S? Actually, in the downstream task we are trying to predict the label (which might be S). So this is the same as the downstream task? But in the downstream task we are allowed to use S as a feature? No, in the downstream task we are predicting the label, so we use all features except the label? Actually, in supervised learning, we use all features except the label to predict the label.
So if S is the label, then the attribute inference attack is exactly the downstream task. Then we are already measuring that in the downstream uplift.
Therefore, attribute disclosure is only meaningful for a sensitive attribute that is not the downstream label.
So we require the user to specify a sensitive attribute column that is not the label.
Identity disclosure:
We measure the risk of re-identification.
We can compute:
For each synthetic record s, find the minimum Euclidean distance to any real record in the real_train (or real_train_preprocessed). Then we can set a threshold (e.g., the distance within which we consider two records to be the same). Then compute the proportion of synthetic records that are within that threshold of a real record.
But the threshold is arbitrary.
Alternatively, we can compute the k-anonymity: for each synthetic record, find the number of real records that are within a certain distance (or in the same equivalence class). We can define the equivalence class by the values of quasi-identifiers (which are a subset of columns). But we don't know which columns are quasi-identifiers.
We can do a simple metric:
For each synthetic record s, compute:
d(s) = min_{r in real_train} ||s - r||_2
Then we can report the minimum, median, and maximum of d(s). Also, we can report the proportion of synthetic records that have d(s) < epsilon for a set of epsilons.
But note: the data is high-dimensional (after one-hot) and the Euclidean distance might not be meaningful.
Another approach: for each synthetic record, find the nearest real record and then compute the number of matching columns? But with one-hot, two records can be close in Euclidean but have different categorical values? Actually, one-hot encoding makes categoricals into a sparse vector, so Euclidean distance might be dominated by the categoricals if we don't scale.
We scaled the numerical features and one-hot encoded the categoricals. Then the Euclidean distance is a weighted sum (with the scaling for numerical). This might be okay.
We can also use a distance metric that is a weighted sum:
d(s, r) = sqrt( sum_{num} ( (s_num - r_num)^2 ) + sum_{cat} (1 if s_cat != r_cat else 0) )
But we don't have the original categoricals for synthetic? We have the one-hot, so we can convert to the original categorical by taking the argmax. Then we can compute the Hamming distance for categoricals.
However, note: the synthetic might have a categorical value that is not exactly one of the real categories? Then we take the argmax and it will be one of the one-hot columns (which correspond to the real categories). So we can convert.
Steps for identity:
For synthetic record s:
Convert the one-hot part to the original categorical by taking the argmax for each categorical feature. Similarly for real record r.
Then:
distance = 0
for each numerical feature:
d_num = (s_num - r_num)^2 [note: we are in the original scale? or preprocessed? We want to compare in the original scale? Because the numerical features are scaled. We should unscale both to original scale?]
for each categorical feature:
if s_cat != r_cat: d_cat = 1 else 0
Then total distance = sqrt( sum(d_num) + sum(d_cat) )? But the sum of d_num and d_cat are in different scales. We might want to normalize.
Given the complexity, we might stick to the Euclidean distance in the preprocessed space (with scaling) and then also report the proportion of synthetic records that have a real neighbor within a small Euclidean distance (e.g., the median distance among real records?).
Alternatively, we can compute:
For each synthetic record, find the nearest real record (in preprocessed space) and then check if they have the same label? That might be a stronger condition.
But note: if the synthetic record has a different label from the nearest real, then it's not an identity match.
We can define an identity match as: same label and same values for all quasi-identifiers? But we don't know the quasi-identifiers.
Given the time, we'll do:
For each synthetic record s:
Find the nearest real record r (in preprocessed space, using Euclidean) and compute the distance d(s).
Also, check if s and r have the same label? (if label is categorical, compare the integer; if numerical, compare within a tolerance?).
Then we can report:
- The proportion of synthetic records that have a real neighbor with the same label and distance < epsilon.
But epsilon is arbitrary.
We might skip the identity metric and rely on the MIA and attribute disclosure.
Given the complexity and time, we'll focus on:
Fidelity:
1. Discriminative AUC (classifier to separate real and synthetic).
2. For each numerical feature (including label if numerical): Wasserstein distance in the original scale.
3. For each categorical feature (including label if categorical): total variation of the marginal distribution.
Privacy:
1. MIA: AUC of a distance-based attack (using minimum distance to synthetic as the score).
2. Attribute disclosure: accuracy of a model trained on synthetic to predict the sensitive attribute on real test, compared to a model trained on real train.
Downstream:
For a given mix_ratio of synthetic in the training set, we train a model on the mixed set and evaluate on real test. We report the performance (accuracy, F1, etc.) and the uplift relative to training on real only.
Implementation:
We'll create a class that takes:
real_data: DataFrame
label: string (column name for the label)
sensitive_attribute: string (column name for the sensitive attribute, optional)
generator: an object with a sample(n) method that returns a DataFrame with the same columns as the training table (including the label)
test_size: float (default 0.2)
random_state: int
Steps:
1. Split real_data into train and test (stratified if classification).
2. Preprocess the features (X) of train and test to numerical (one-hot for categorical, scale for numerical). Store the preprocessor.
3. Encode the label if string.
4. Form train_table and test_table (with preprocessed features and encoded label).
5. Train generator on train_table.
6. Generate synthetic_table.
7. Preprocess the synthetic_table? It's already in the same space as train_table? The generator generates the table in the same column format. So we don't need to preprocess again.
8. Now we have:
real_train = train_table
real_test = test_table
synthetic = synthetic_table
9. Fidelity:
a. Discriminative:
Combine real_train and synthetic, label 0 for real, 1 for synthetic.
Train a classifier (GradientBoosting) on this combined set (with 5-fold CV?) and get the AUC.
b. Per-column:
We need to map the columns in the preprocessed table to the original features.
We have:
numerical_features: list of original numerical feature names (that were scaled)
categorical_features: list of original categorical feature names (that were one-hotted)
For each numerical feature in numerical_features:
Get the column in real_train and synthetic? But note: after one-hot, the numerical features are still there? Yes, the ColumnTransformer leaves the numerical features as is (but scaled). So the column name for a numerical feature is the same as the original.
So:
real_col = real_train[feature]
syn_col = synthetic[feature]
But these are scaled. We have the scaler for that feature? We stored the ColumnTransformer, so we can get the scaler for that feature by:
scaler = preprocessor.named_transformers_['num'].named_steps['standardscaler']? Actually, the ColumnTransformer has a list of transformers. We stored the numerical transformer as ('num', StandardScaler(), numerical_features). Then the StandardScaler is applied to the numerical_features in order. So we can get the scaler for a feature by:
index = numerical_features.index(feature)
scaler = preprocessor.named_transformers_['num'].scaler_? Actually, the StandardScaler has attributes mean_ and scale_. We can get the scaler for each feature by:
scaler_mean = preprocessor.named_transformers_['num'].mean_[index]
scaler_scale = preprocessor.named_transformers_['num'].scale_[index]
Then unscale:
real_original = real_col * scaler_scale + scaler_mean
syn_original = syn_col * scaler_scale + scaler_mean
Then compute Wasserstein(real_original, syn_original).
For each categorical feature in categorical_features:
We need to get the one-hot columns for that feature. The one-hot encoder creates columns with names: f"{feature}_{category}" for each category in the training set.
So:
one_hot_columns = [col for col in real_train.columns if col.startswith(f"{feature}_")]
Then:
real_dist: from the original real_train (before preprocessing) we have the categorical feature. We can compute the value counts and then create a vector of length len(one_hot_columns) with the frequency for each category. For categories not present in real_train, we set 0.
syn_dist: synthetic[one_hot_columns].mean()
Then total_variation = 0.5 * np.sum(np.abs(real_dist - syn_dist))
For the label:
If label in numerical_features? Then we treat as numerical (but note: we didn't scale the label). Actually, the label is not in numerical_features because we dropped it before preprocessing. So the label is a separate column.
We have:
real_label = real_train[label]
syn_label = synthetic[label]
If the label is categorical (we encoded as integer):
real_dist = value_counts of real_label (normalized) over the integer classes.
syn_dist = value_counts of syn_label (normalized) over the integer classes.
Then total_variation.
If the label is numerical:
We didn't scale the label, so real_label and syn_label are in the original scale. Then Wasserstein.
10. Privacy:
a. MIA:
We have:
members = real_train (preprocessed, without the label? or with? The attack should be on all columns? We include the label because the synthetic data includes the label. So we use all columns.
non_members = real_test (preprocessed)
For each record in members and non_members, compute:
d = min_{s in synthetic} ||record - s||_2 (Euclidean in the preprocessed space)
Then we have:
distances_members = [d for r in members]
distances_non_members = [d for r in non_members]
Then we train a logistic regression to predict membership (1 for member, 0 for non-member) based on the distance? But the distance is a scalar. We can just use the distance as the score and compute the AUC by ranking.
Alternatively, we can use the distance directly: the smaller the distance, the more likely it is a member. So we can compute the AUC by:
scores = -np.concatenate([distances_members, distances_non_members]) # because smaller distance -> higher likelihood of member
labels = [1]*len(distances_members) + [0]*len(distances_non_members)
auc = roc_auc_score(labels, scores)
We can also train a logistic regression on the distances (and maybe other features? but we only have the distance). But since it's a scalar, we can just use the distance.
b. Attribute disclosure:
We assume the sensitive attribute is a column in the data (and not the label). We have:
sensitive_attribute: string.
We need to remove this column from the features and use it as the label for the attack.
Steps:
For real_train:
X_train = real_train.drop(columns=[sensitive_attribute])
y_train = real_train[sensitive_attribute]
For synthetic:
X_syn = synthetic.drop(columns=[sensitive_attribute])
y_syn = synthetic[sensitive_attribute]
For real_test:
X_test = real_test.drop(columns=[sensitive_attribute])
y_test = real_test[sensitive_attribute]
Train a model (e.g., RandomForest) on (X_train, y_train) -> model_real
Train the same model on (X_syn, y_syn) -> model_syn
Evaluate both on (X_test, y_test) and compute accuracy.
We report:
accuracy_real = model_real.score(X_test, y_test)
accuracy_syn = model_syn.score(X_test, y_test)
The leakage is the difference? Or the ratio? We report both.
Note: if the sensitive attribute is categorical, we use classification. If numerical, regression? But the sensitive attribute is usually categorical. We assume categorical.
11. Downstream uplift:
We have the downstream task (with the label). We already have:
real_train (with label) and real_test (with label) and synthetic (with label).
We want to train a model on various mixtures of real_train and synthetic and evaluate on real_test.
Let mix_ratios = [0.0, 0.1, 0.5, 1.0] # 0 means only real_train, 1 means only synthetic.
For each alpha in mix_ratios:
n_real = len(real_train)
n_syn = len(synthetic)
n_real_used = int((1-alpha) * n_real) # but we want to keep the total training size fixed? Or we can fix the total size and vary the proportion?
We can do:
total_size = n_real # we fix the total training size to be the same as the real train size? Or we can use the same total size for all mixtures?
Option 1: For each alpha, we take:
real_used = min(n_real, int((1-alpha)*total_size))
syn_used = total_size - real_used
But then the total size is fixed (total_size). We can set total_size = n_real (so when alpha=0, we use all real; when alpha=1, we use no real and only synthetic? But we only have n_syn synthetic. So we set total_size = min(n_real, n_syn) for alpha=1? This is messy.
Alternatively, we can fix the real part and vary the synthetic part? But then the training size changes.
Common in literature: fix the total training size and vary the proportion of synthetic. But we have to make sure we have enough synthetic.
We can set:
total_size = min(n_real, n_syn) # so that when alpha=1 we have enough synthetic.
Then for each alpha:
n_real_in_mix = int((1-alpha) * total_size)
n_syn_in_mix = total_size - n_real_in_mix
If n_real_in_mix > n_real, then we use all real and reduce synthetic? But we set total_size <= n_real, so n_real_in_mix <= total_size <= n_real.
Similarly, n_syn_in_mix <= total_size <= n_syn? We set total_size <= min(n_real, n_syn).
So:
total_size = min(n_real, n_syn)
Then for alpha=0: n_real_in_mix = total_size, n_syn_in_mix = 0 -> use real_train[0:total_size]
For alpha=1: n_real_in_mix = 0, n_syn_in_mix = total_size -> use synthetic[0:total_size]
For alpha=0.5: n_real_in_mix = int(0.5*total_size), n_syn_in_mix = total_size - n_real_in_mix.
But note: we are sampling without replacement from real_train and synthetic? We can sample randomly for each alpha to reduce variance? Or we can use the same subset of real_train for all alphas?
We'll do:
For each alpha, we sample n_real_in_mix from real_train (without replacement) and n_syn_in_mix from synthetic (without replacement) and then concatenate.
Then train a model (e.g., RandomForest) on this mixed set and evaluate on real_test.
We repeat this multiple times (e.g., 5) and average the performance to reduce variance.
We report:
For each alpha: average performance (and standard deviation) over the repetitions.
The uplift is the performance at alpha>0 compared to alpha=0.
12. Report:
We return a dictionary with:
fidelity: {
'discriminative_auc': ...,
'per_feature': {
feature_name: {
'type': 'numerical' or 'categorical',
'metric': 'wasserstein' or 'total_variation',
'value': ...,
}
}
}
privacy: {
'mia_auc': ...,
'attribute_disclosure': {
'accuracy_real': ...,
'accuracy_syn': ...,
}
}
downstream: {
alpha1: { 'mean': ..., 'std': ... },
alpha2: ...,
}
This is a comprehensive benchmark.
However, note: the downstream task might be regression, then we use appropriate metrics (MSE, R2).
We assume the user specifies the task_type ('classification' or 'regression') and we use appropriate models and metrics.
For downstream:
If classification: we use a RandomForest (or a user-specified model) and evaluate with accuracy (or F1 if imbalanced?).
If regression: use RandomForestRegressor and evaluate with R2 or MSE.
We'll let the user pass a downstream model (with a fit and predict method) or use a default.
Given the complexity, we'll implement a simplified version that can be extended.
We'll code accordingly.
Let's code the class structure.
Note: This is a big task. We might not be able to code every detail, but we provide the design.
We'll write the class with the following methods:
__init__
_split_data
_preprocess
_generate_synthetic
_compute_fidelity
_compute_privacy
_compute_downstream
run
We assume the generator is already trained? Or we train it in _generate_synthetic? We train it on the preprocessed train_table.
Let's code step by step.
Due to the length, we provide a skeleton and leave some details as comments.
We assume the user will provide a generator that has a sample(n) method and can be trained with fit(data). But in our design, we train the generator in _generate_synthetic? Actually, we train the generator on the preprocessed train_table. So we assume the generator has a fit method.
So:
generator.fit(train_table)
synthetic = generator.sample(len(train_table))
But some generators (like SDV) have a fit_sample method that does both.
We'll assume the generator has a fit method and a sample method.
If the generator is already trained, then we can skip the fit? We'll design so that if the generator is already fitted, we don't fit again? But we want to fit on the current train_table. So we always fit.
Alternatively, we can let the user pass a generator that is already trained on the real data? But then we would have to split the real data before training the generator? We want to train the generator on the train set only. So we fit the generator in our code.
So we assume the generator is an instance that we can call fit on.
Let's code.
Note: This is a design document, so we don't have to write the full code, but we outline.
We'll write in Python-like pseudocode.
Given the complexity, we might use existing libraries for some metrics (e.g., from sdmetrics for fidelity, from ART for privacy?).
But for the purpose of this design, we implement our own.
Let's start.
I'll design a comprehensive Synthetic Data Factory Benchmarking Framework that systematically evaluates synthetic data across three critical dimensions: fidelity, privacy, and downstream utility. This framework enables reproducible comparisons between synthetic data generation methods.
1. Framework Architecture
1.1 Core Components
class SyntheticDataBenchmark:
"""
Comprehensive benchmarking framework for synthetic data generation
"""
def __init__(self, real_data, metadata, task_type='classification'):
self.real_data = real_data
self.metadata = metadata # Schema, data types, PII fields
self.task_type = task_type
self.results = {}
def evaluate_generator(self, generator, config):
"""
End-to-end evaluation pipeline for a synthetic data generator
"""
# 1. Generate synthetic data
synthetic_data = generator.generate(self.real_data, config)
# 2. Compute metrics
fidelity_metrics = self.compute_fidelity(synthetic_data)
privacy_metrics = self.compute_privacy_risks(synthetic_data)
downstream_metrics = self.compute_downstream_uplift(synthetic_data)
return {
'fidelity': fidelity_metrics,
'privacy': privacy_metrics,
'downstream': downstream_metrics,
'config': config
}
2. Fidelity Metrics (Statistical & ML Utility)
2.1 Statistical Similarity
| Metric | Description | Implementation |
|---|
| Univariate Distribution | 1D distribution matching (KS test for numerical, chi² for categorical) | scipy.stats.ks_2samp, sklearn.metrics.pairwise_distances |
| Multivariate Correlation | Difference in correlation matrices (Frobenius norm) | np.linalg.norm(C_real - C_syn, 'fro') |
| PCA Reconstruction Error | Reconstruction loss when projecting synthetic→real→synthetic | PCA on real, transform synthetic, inverse transform |
| Density Estimation | KL divergence between kernel density estimates | sklearn.neighbors.KernelDensity |
| Column Pair Relationships | Mutual information preservation for feature pairs | sklearn.metrics.normalized_mutual_info_score |
| Tail Distribution | Wasserstein distance in distribution tails (top/bottom 10%) | scipy.stats.wasserstein_distance on quantiles |
2.2 Machine Learning Utility
class MLUtilityEvaluator:
def evaluate(self, real_data, synthetic_data, test_data):
"""
Train models on synthetic, test on real holdout
"""
results = {}
# A. Train-on-Synthetic, Test-on-Real (TSTR)
model = self.train_model(synthetic_data)
tstr_score = self.evaluate_model(model, test_data)
# B. Train-on-Real, Test-on-Real (Baseline)
real_model = self.train_model(real_data)
real_score = self.evaluate_model(real_model, test_data)
# C. Train-on-Synthetic+Real, Test-on-Real
mixed_data = self.create_mixed_dataset(real_data, synthetic_data, ratio=0.5)
mixed_model = self.train_model(mixed_data)
mixed_score = self.evaluate_model(mixed_model, test_data)
return {
'tstr_relative': tstr_score / real_score,
'mixed_improvement': (mixed_score - real_score) / real_score,
'synthetic_only_auc': tstr_score,
'real_only_auc': real_score
}
Task-Specific Models:
- Classification: XGBoost, Random Forest, Logistic Regression
- Regression: Gradient Boosting, Linear Regression
- Clustering: Silhouette score comparing cluster assignments on real vs synthetic
3. Privacy Risk Assessment
3.1 Membership Inference Attacks (MIA)
class MembershipInferenceAttack:
def __init__(self, attack_model='rf'):
self.attack_model = attack_model
def evaluate(self, real_train, real_test, synthetic_data):
"""
Shadow model approach for MIA
"""
# 1. Create attack dataset
attack_data = self._create_attack_dataset(
real_train, real_test, synthetic_data
)
# 2. Train attack model
X_attack, y_attack = attack_data['features'], attack_data['labels']
attack_clf = RandomForestClassifier()
attack_clf.fit(X_attack, y_attack)
# 3. Evaluate attack performance
attack_auc = roc_auc_score(y_attack, attack_clf.predict_proba(X_attack)[:, 1])
attack_advantage = self._compute_advantage(attack_clf, X_attack, y_attack)
return {
'mia_auc': attack_auc,
'mia_advantage': attack_advantage,
'privacy_estimate': self._estimate_privacy_budget(attack_auc)
}
Attack Strategies:
- Shadow Training: Train shadow models on synthetic data subsets
- Distance-based: Record distance to nearest synthetic neighbor
- Confidence-based: Classification confidence as membership signal
3.2 Attribute Inference
def attribute_inference_risk(synthetic_data, sensitive_attrs, known_attrs):
"""
Measure leakage of sensitive attributes given known attributes
"""
risks = {}
for attr in sensitive_attrs:
# Train attribute predictor on synthetic
X_syn = synthetic_data[known_attrs]
y_syn = synthetic_data[attr]
predictor = RandomForestClassifier()
predictor.fit(X_syn, y_syn)
# Evaluate on real data (if available) or holdout
accuracy = predictor.score(real_data[known_attrs], real_data[attr])
# Baseline: random guess / majority class
baseline = max(real_data[attr].value_counts(normalize=True))
risks[attr] = {
'accuracy': accuracy,
'relative_risk': accuracy / baseline,
'attribute_disclosure': accuracy > baseline * 1.2 # Significant leakage
}
return risks
3.3 Identity Disclosure
| Metric | Method |
|---|
| k-anonymity | For each synthetic record, count real records within ε-distance |
| Uniqueness | % of synthetic records with Euclidean distance < δ to any real record |
| RecordLinkage | Success rate of linking synthetic→real via quasi-identifiers |
| Differential Privacy ε | If DP generator: compute (ε,δ) from mechanism parameters |
4. Downstream Uplift Metrics
4.1 Experimental Protocol
Real Data: D_real = D_train + D_test + D_validation
Synthetic: D_syn (from D_train)
Conditions:
1. Baseline: Train on D_train → Test on D_test
2. Synthetic Only: Train on D_syn → Test on D_test (TSTR)
3. Mixed: Train on α·D_syn + (1-α)·D_train → Test on D_test
4. Pre-training: Pretrain on D_syn, fine-tune on D_train
4.2 Uplift Metrics
class DownstreamUpliftEvaluator:
def evaluate(self, real_train, real_test, synthetic_data):
"""
Quantify utility gains from synthetic data
"""
results = {}
# 1. Privacy-utility tradeoff curve
alphas = np.linspace(0, 1, 11) # Synthetic proportion
for alpha in alphas:
mixed = self._mix_datasets(real_train, synthetic_data, alpha)
model = self.train_model(mixed)
score = self.evaluate_model(model, real_test)
results[f'mixed_alpha_{alpha:.1f}'] = score
# 2. Sample efficiency: How much real data can synthetic replace?
real_sample_sizes = [0.1, 0.2, 0.5, 1.0]
for size_ratio in real_sample_sizes:
# Use only size_ratio of real data
real_small = real_train.sample(frac=size_ratio)
score_no_syn = self.train_and_evaluate(real_small, real_test)
score_with_syn = self.train_and_evaluate(
pd.concat([real_small, synthetic_data]),
real_test
)
results[f'reduction_{size_ratio:.1f}'] = {
'without_synthetic': score_no_syn,
'with_synthetic': score_with_syn,
'uplift': (score_with_syn - score_no_syn) / score_no_syn
}
# 3. Cold start improvement (no real data)
results['synthetic_only'] = self.train_and_evaluate(
synthetic_data, real_test
)
return results
Task-Specific Metrics:
- Classification: AUC-ROC, F1-score, Balanced accuracy
- Regression: R², RMSE, MAE
- Imbalanced Data: PR-AUC, Matthews Correlation Coefficient
- Calibration: Brier score, reliability diagrams
5. Comprehensive Benchmark Suite
5.1 Test Scenarios
| Scenario | Description | Use Case |
|---|
| Low-Diversity | Limited feature/target combinations | Healthcare rare diseases |
| High-Cardinality | Many categorical levels | User behavior data |
| Time-Series | Temporal dependencies | IoT sensor data |
| Graph/Relational | Relationships between records | Social networks |
| Privacy-Sensitive | PII, HIPAA, GDPR | Medical/financial data |
5.2 Generators to Benchmark
GENERATORS = {
'traditional': [
'SMOTE', 'ADASYN', 'CTGAN', 'TVAE', 'CopulaGAN'
],
'dp_enabled': [
'DP-CTGAN', 'DP-GAN', 'PATE-GAN'
],
'foundation': [
'Tab diffusion', 'GReaT', 'TabDDPM'
],
'commercial': [
'MostlyAI', 'Synthetic Data Vault (SDV)', 'Hazy'
]
}
5.3 Benchmark Dataset Collection
Benchmark Datasets:
1. UCI Adult (income prediction) - moderate size, mixed types
2. California Housing - regression, numeric
3. Covertype - large, multiclass
4. Higgs - large, physics
5. Synthea (synthetic pediatric EMR) - healthcare with PII
6.财新新闻数据 - Chinese text + structured metadata
7. Financial Transactions - high-cardinality, sequential
6. Unified Scoring System
class CompositeScore:
"""
Normalize and combine metrics into interpretable scores
"""
def compute_overall_score(self, metrics):
# Normalize each metric to [0,1] where 1 is optimal
normalized = {
'fidelity': self._normalize_fidelity(metrics['fidelity']),
'privacy': self._normalize_privacy(metrics['privacy']), # Higher is safer
'downstream': metrics['downstream']['synthetic_only'] /
metrics['downstream']['real_only']
}
# Weighted combination (user-configurable)
weights = {'fidelity': 0.4, 'privacy': 0.3, 'downstream': 0.3}
score = sum(normalized[k] * weights[k] for k in weights)
return {
'overall_score': score,
'radar_chart_data': normalized,
'grade': self._assign_grade(score)
}
def _normalize_privacy(self, privacy_metrics):
"""
Convert privacy metrics to safety score [0,1]
MIA AUC 0.5 → 1.0 (safe), 0.9 → 0.0 (unsafe)
"""
mia_score = 1.0 - 2 * (privacy_metrics['mia_auc'] - 0.5)
return np.clip(mia_score, 0, 1)
7. Implementation Roadmap
Phase 1: Core Metrics (2 weeks)
- Implement univariate/multivariate fidelity metrics
- Basic MIA attack (distance-based)
- TSTR evaluation pipeline
Phase 2: Advanced Privacy (3 weeks)
- Shadow model MIA
- Attribute inference attacks
- DP accounting if applicable
Phase 3: Downstream Protocols (2 weeks)
- Mixed training protocols
- Sample efficiency curves
- Multiple downstream tasks
Phase 4: Visualization & Reporting (1 week)
- Radar charts for fidelity-privacy-utility tradeoffs
- Calibration curves for TSTR vs real performance
- Privacy-utility Pareto fronts
- HTML/PDF reports with statistical significance testing
8. Example Output Report Structure
Benchmark Report: CTGAN vs TVAE on Adult Dataset
================================================
1. Fidelity Metrics
- Univariate Wasserstein: 0.042 (CTGAN) vs 0.067 (TVAE)
- Correlation Matrix Error: 0.18 vs 0.31
- Discriminative AUC (real vs syn): 0.51 vs 0.58
2. Privacy Risks
- Membership Inference AUC: 0.53 vs 0.51 (both ≈ random)
- Attribute Disclosure (gender): 0.71 vs 0.69 accuracy
- k-anonymity (k=5): 78% vs 82% of syn records
3. Downstream Uplift (Income Prediction)
- Real-only AUC: 0.891
- Synthetic-only AUC: 0.843 (CTGAN), 0.812 (TVAE)
- Mixed (50% syn): 0.887 (CTGAN), 0.879 (TVAE)
- Sample efficiency: Replace 40% real data with CTGAN without loss
4. Composite Scores
- CTGAN: 0.78 (B+)
- TVAE: 0.72 (C+)
5. Recommendations
- Use CTGAN for: Utility-critical applications
- Use TVAE for: Better privacy guarantees (lower MIA)
- Avoid both for: High-risk PII data without DP
9. Advanced Considerations
9.1 Temporal Benchmarking
- Concept Drift: Evaluate synthetic data across time slices
- Temporal Fidelity: Autocorrelation preservation, trend matching
- Causal Inference: Do synthetic data preserve causal relationships?
9.2 Multimodal Data
- Image+Tabular: CLIP-based similarity metrics
- Text+Tabular: BERT embeddings distance
- Graph+Tabular: GNN-based distribution matching
9.3 Regulatory Compliance
GDPR Checkpoints:
☑️ Purpose limitation: Synthetic only for stated purpose
☑️ Data minimization: No excessive detail
☑️ Accuracy: Fidelity > threshold for intended use
☑️ Storage limitation: Synthetic not considered personal data
☑️ Integrity: No record linkage possible (k-anonymity > 10)
10. Usage Example
# Initialize benchmark
benchmark = SyntheticDataBenchmark(
real_data=adult_df,
metadata=adult_metadata,
task_type='classification'
)
# Evaluate multiple generators
results = {}
for generator_name, generator in GENERATORS.items():
for config in generator.configurations:
results[generator_name] = benchmark.evaluate_generator(
generator, config
)
# Generate comparison report
report = BenchmarkReport(results)
report.generate_radar_chart()
report.export_to_html('synthetic_benchmark_report.html')
11. Key Design Principles
- Reproducibility: Fixed random seeds, versioned datasets
- Modularity: Swap metrics/generators/tasks independently
- Interpretability: All scores normalized to [0,1] with clear semantics
- Extensibility: Plugin architecture for new metrics
- Actionable: Recommendations tied to use cases
- Statistically Sound: Confidence intervals, multiple runs
This framework provides a scientific, multi-dimensional evaluation crucial for:
- Data buyers: Assess synthetic data quality before purchase
- Researchers: Compare novel synthetic methods fairly
- Compliance officers: Verify privacy guarantees
- ML engineers: Quantify utility for specific downstream tasks
The benchmark transforms synthetic data from "looks real" to quantifiably trustworthy through rigorous, standardized evaluation across the privacy-utility frontier.