# CTGAN Model¶

In this guide we will go through a series of steps that will let you discover functionalities of the CTGAN model, including how to:

• Create an instance of CTGAN.

• Fit the instance to your data.

• Generate synthetic versions of your data.

• Use CTGAN to anonymize PII information.

• Specify hyperparameters to improve the output quality.

## What is CTGAN?¶

The sdv.tabular.CTGAN model is based on the GAN-based Deep Learning data synthesizer which was presented at the NeurIPS 2020 conference by the paper titled Modeling Tabular data using Conditional GAN.

Let’s now discover how to learn a dataset and later on generate synthetic data with the same format and statistical properties by using the CTGAN class from SDV.

## Quick Usage¶

We will start by loading one of our demo datasets, the student_placements, which contains information about MBA students that applied for placements during the year 2020.

Warning

In order to follow this guide you need to have ctgan installed on your system. If you have not done it yet, please install ctgan now by executing the command pip install sdv in a terminal.

In [1]: from sdv.demo import load_tabular_demo

Out[3]:
student_id gender  second_perc  ...  start_date   end_date  duration
0       17264      M        67.00  ...  2020-07-23 2020-10-12       3.0
1       17265      M        79.33  ...  2020-01-11 2020-04-09       3.0
2       17266      M        65.00  ...  2020-01-26 2020-07-13       6.0
3       17267      M        56.00  ...         NaT        NaT       NaN
4       17268      M        85.80  ...  2020-07-04 2020-09-27       3.0

[5 rows x 17 columns]


As you can see, this table contains information about students which includes, among other things:

• Their id and gender

• Their work experience

• The salary that they were offered

• The duration and dates of their placement

You will notice that there is data with the following characteristics:

• There are float, integer, boolean, categorical and datetime values.

• There are some variables that have missing data. In particular, all the data related to the placement details is missing in the rows where the student was not placed.

Let us use CTGAN to learn this data and then sample synthetic data about new students to see how well the model captures the characteristics indicated above. In order to do this you will need to:

• Import the sdv.tabular.CTGAN class and create an instance of it.

• Call its fit method passing our table.

• Call its sample method indicating the number of synthetic rows that you want to generate.

In [4]: from sdv.tabular import CTGAN

In [5]: model = CTGAN()

In [6]: model.fit(data)


Note

Notice that the model fitting process took care of transforming the different fields using the appropriate Reversible Data Transforms to ensure that the data has a format that the underlying CTGANSynthesizer class can handle.

### Generate synthetic data from the model¶

Once the modeling has finished you are ready to generate new synthetic data by calling the sample method from your model passing the number of rows that we want to generate. The number of rows (num_rows) is a required parameter.

In [7]: new_data = model.sample(num_rows=200)


This will return a table identical to the one which the model was fitted on, but filled with new data which resembles the original one.

In [8]: new_data.head()
Out[8]:
student_id gender  second_perc  ...  start_date   end_date  duration
0       17411      M        55.67  ...  2020-09-24        NaT       5.0
1       17397      M        55.15  ...  2020-02-11 2020-08-17       NaN
2       17478      M        61.54  ...         NaT        NaT       NaN
3       17409      M        47.60  ...         NaT        NaT      11.0
4       17364      M        49.55  ...         NaT 2020-06-23       NaN

[5 rows x 17 columns]


Note

There are a number of other parameters in this method that you can use to optimize the process of generating synthetic data. Use output_file_path to directly write results to a CSV file, batch_size to break up sampling into smaller pieces & track their progress and randomize_samples to determine whether to generate the same synthetic data every time. See the API section for more details.

### Save and Load the model¶

In many scenarios it will be convenient to generate synthetic versions of your data directly in systems that do not have access to the original data source. For example, if you may want to generate testing data on the fly inside a testing environment that does not have access to your production database. In these scenarios, fitting the model with real data every time that you need to generate new data is feasible, so you will need to fit a model in your production environment, save the fitted model into a file, send this file to the testing environment and then load it there to be able to sample from it.

Let’s see how this process works.

#### Save and share the model¶

Once you have fitted the model, all you need to do is call its save method passing the name of the file in which you want to save the model. Note that the extension of the filename is not relevant, but we will be using the .pkl extension to highlight that the serialization protocol used is pickle.

In [9]: model.save('my_model.pkl')


This will have created a file called my_model.pkl in the same directory in which you are running SDV.

Important

If you inspect the generated file you will notice that its size is much smaller than the size of the data that you used to generate it. This is because the serialized model contains no information about the original data, other than the parameters it needs to generate synthetic versions of it. This means that you can safely share this my_model.pkl file without the risc of disclosing any of your real data!

#### Load the model and generate new data¶

The file you just generated can be sent over to the system where the synthetic data will be generated. Once it is there, you can load it using the CTGAN.load method, and then you are ready to sample new data from the loaded instance:

In [10]: loaded = CTGAN.load('my_model.pkl')



Warning

Notice that the system where the model is loaded needs to also have sdv and ctgan installed, otherwise it will not be able to load the model and use it.

### Specifying the Primary Key of the table¶

One of the first things that you may have noticed when looking at the demo data is that there is a student_id column which acts as the primary key of the table, and which is supposed to have unique values. Indeed, if we look at the number of times that each value appears, we see that all of them appear at most once:

In [12]: data.student_id.value_counts().max()
Out[12]: 1


However, if we look at the synthetic data that we generated, we observe that there are some values that appear more than once:

In [13]: new_data[new_data.student_id == new_data.student_id.value_counts().index[0]]
Out[13]:
student_id gender  second_perc  ...  start_date   end_date  duration
9         17478      F        58.62  ...         NaT        NaT       6.0
13        17478      M        47.09  ...         NaT 2020-07-16       4.0
33        17478      M        42.60  ...         NaT 2020-08-23       NaN
38        17478      M        52.41  ...  2020-03-23 2020-08-02       NaN
56        17478      M        45.83  ...         NaT 2020-12-21      12.0
58        17478      M        68.76  ...         NaT 2020-11-14       NaN
98        17478      F        63.39  ...  2020-03-20 2020-08-08       NaN
113       17478      M        57.11  ...  2020-08-26 2020-08-30       NaN
123       17478      M        44.97  ...         NaT        NaT       6.0
138       17478      M        40.89  ...  2020-01-10 2020-08-04       5.0
143       17478      M        48.86  ...  2020-03-08 2020-08-29       NaN
145       17478      M        66.12  ...         NaT 2020-08-08       4.0
148       17478      F        54.20  ...         NaT 2021-03-02      12.0
156       17478      M        49.41  ...         NaT 2021-01-06       7.0
159       17478      M        64.20  ...  2020-01-12 2020-08-06       NaN
172       17478      F        40.89  ...  2020-08-23        NaT       6.0
175       17478      M        64.05  ...  2020-02-03        NaT       5.0
188       17478      M        51.86  ...  2020-03-21        NaT       6.0
195       17478      M        65.28  ...  2020-01-19 2020-08-24       NaN
199       17478      M        54.67  ...  2020-01-01 2020-12-01       NaN

[20 rows x 17 columns]


This happens because the model was not notified at any point about the fact that the student_id had to be unique, so when it generates new data it will provoke collisions sooner or later. In order to solve this, we can pass the argument primary_key to our model when we create it, indicating the name of the column that is the index of the table.

In [14]: model = CTGAN(
....:     primary_key='student_id'
....: )
....:

In [15]: model.fit(data)

In [16]: new_data = model.sample(200)

Out[17]:
student_id gender  second_perc  ...  start_date   end_date  duration
0           0      M        60.20  ...  2020-03-02        NaT       6.0
1           1      M        79.40  ...         NaT 2020-07-09       3.0
2           2      M        45.56  ...  2020-03-25        NaT       NaN
3           3      F        40.89  ...  2020-08-08        NaT       5.0
4           4      M        76.72  ...  2020-03-17        NaT       4.0

[5 rows x 17 columns]


As a result, the model will learn that this column must be unique and generate a unique sequence of values for the column:

In [18]: new_data.student_id.value_counts().max()
Out[18]: 1


### Anonymizing Personally Identifiable Information (PII)¶

There will be many cases where the data will contain Personally Identifiable Information which we cannot disclose. In these cases, we will want our Tabular Models to replace the information within these fields with fake, simulated data that looks similar to the real one but does not contain any of the original values.

Let’s load a new dataset that contains a PII field, the student_placements_pii demo, and try to generate synthetic versions of it that do not contain any of the PII fields.

Note

The student_placements_pii dataset is a modified version of the student_placements dataset with one new field, address, which contains PII information about the students. Notice that this additional address field has been simulated and does not correspond to data from the real users.

In [19]: data_pii = load_tabular_demo('student_placements_pii')

Out[20]:
student_id  ... duration
0       17264  ...      3.0
1       17265  ...      3.0
2       17266  ...      6.0
3       17267  ...      NaN
4       17268  ...      3.0

[5 rows x 18 columns]


If we use our tabular model on this new data we will see how the synthetic data that it generates discloses the addresses from the real students:

In [21]: model = CTGAN(
....:     primary_key='student_id',
....: )
....:

In [22]: model.fit(data_pii)

In [23]: new_data_pii = model.sample(200)

Out[24]:
student_id  ... duration
0           0  ...      5.0
1           1  ...      5.0
2           2  ...      6.0
3           3  ...      NaN
4           4  ...      NaN

[5 rows x 18 columns]


More specifically, we can see how all the addresses that have been generated actually come from the original dataset:

In [25]: new_data_pii.address.isin(data_pii.address).sum()
Out[25]: 200


In order to solve this, we can pass an additional argument anonymize_fields to our model when we create the instance. This anonymize_fields argument will need to be a dictionary that contains:

• The name of the field that we want to anonymize.

• The category of the field that we want to use when we generate fake values for it.

The list complete list of possible categories can be seen in the Faker Providers page, and it contains a huge list of concepts such as:

• name

• country

• city

• ssn

• credit_card_number

• credit_card_expire

• credit_card_security_code

• email

• telephone

In this case, since the field is an address, we will pass a dictionary indicating the category address

In [26]: model = CTGAN(
....:     primary_key='student_id',
....:     anonymize_fields={
....:     }
....: )
....:

In [27]: model.fit(data_pii)


As a result, we can see how the real address values have been replaced by other fake addresses:

In [28]: new_data_pii = model.sample(200)

Out[29]:
student_id  ... duration
0           0  ...      3.0
1           1  ...      4.0
2           2  ...      6.0
3           3  ...      NaN
4           4  ...      6.0

[5 rows x 18 columns]


Which means that none of the original addresses can be found in the sampled data:

In [30]: data_pii.address.isin(new_data_pii.address).sum()
Out[30]: 0


Now that we have discovered the basics, let’s go over a few more advanced usage examples and see the different arguments that we can pass to our CTGAN Model in order to customize it to our needs.

### Setting Bounds and Specifying Rounding for Numerical Columns¶

By default, the model will learn the upper and lower bounds of the input data, and use that for sampling. This means that all sampled data will be between the maximum and minimum values found in the original dataset for each numeric column. This option can be overwritten using the min_value and max_value model arguments. These values can either be set to a numeric value, set to 'auto' which is the default setting, or set to None which will mean the column is boundless.

The model will also learn the number of decimal places to round to by default. This option can be overwritten using the rounding parameter. The value can be an int specifying how many decimal places to round to, 'auto' which is the default setting, or None which means the data will not be rounded.

Since we may want to sample values outside of the ranges in the original data, let’s pass the min_value and max_value arguments as None to the model. To keep the number of decimals consistent across columns, we can set rounding to be 2.

In [31]: model = CTGAN(
....:     primary_key='student_id',
....:     min_value=None,
....:     max_value=None,
....:     rounding=2
....: )
....:

In [32]: model.fit(data)

In [33]: unbounded_data = model.sample(10)

In [34]: unbounded_data
Out[34]:
student_id gender  second_perc  ...  start_date   end_date  duration
0           0      M        52.48  ...         NaT 2020-07-18       NaN
1           1      F        35.84  ...  2019-12-20 2020-08-04      5.78
2           2      M        74.03  ...  2020-02-03 2020-07-28      6.46
3           3      M        73.36  ...  2020-01-14 2020-07-29      6.72
4           4      M        39.92  ...         NaT 2020-09-05       NaN
5           5      M        50.21  ...         NaT 2020-03-19       NaN
6           6      M        54.30  ...  2020-08-20        NaT       NaN
7           7      M        91.89  ...         NaT 2020-07-26      6.30
8           8      F        59.69  ...         NaT 2020-07-19      5.26
9           9      F        55.75  ...         NaT 2020-05-07      2.52

[10 rows x 17 columns]


As you may notice, the sampled data may have values outside the range of the original data.

### How to modify the CTGAN Hyperparameters?¶

A part from the common Tabular Model arguments, CTGAN has a number of additional hyperparameters that control its learning behavior and can impact on the performance of the model, both in terms of quality of the generated data and computational time.

• epochs and batch_size: these arguments control the number of iterations that the model will perform to optimize its parameters, as well as the number of samples used in each step. Its default values are 300 and 500 respectively, and batch_size needs to always be a value which is multiple of 10.

These hyperparameters have a very direct effect in time the training process lasts but also on the performance of the data, so for new datasets, you might want to start by setting a low value on both of them to see how long the training process takes on your data and later on increase the number to acceptable values in order to improve the performance.

• log_frequency: Whether to use log frequency of categorical levels in conditional sampling. It defaults to True. This argument affects how the model processes the frequencies of the categorical values that are used to condition the rest of the values. In some cases, changing it to False could lead to better performance.

• embedding_dim (int): Size of the random sample passed to the Generator. Defaults to 128.

• generator_dim (tuple or list of ints): Size of the output samples for each one of the Residuals. A Resiudal Layer will be created for each one of the values provided. Defaults to (256, 256).

• discriminator_dim (tuple or list of ints): Size of the output samples for each one of the Discriminator Layers. A Linear Layer will be created for each one of the values provided. Defaults to (256, 256).

• generator_lr (float): Learning rate for the generator. Defaults to 2e-4.

• generator_decay (float): Generator weight decay for the Adam Optimizer. Defaults to 1e-6.

• discriminator_lr (float): Learning rate for the discriminator. Defaults to 2e-4.

• discriminator_decay (float): Discriminator weight decay for the Adam Optimizer. Defaults to 1e-6.

• discriminator_steps (int): Number of discriminator updates to do for each generator update. From the WGAN paper: https://arxiv.org/abs/1701.07875. WGAN paper default is 5. Default used is 1 to match original CTGAN implementation.

• verbose: Whether to print fit progress on stdout. Defaults to False.

• cuda (bool or str): If True, use CUDA. If a str, use the indicated device. If False, do not use cuda at all.

Warning

Notice that the value that you set on the batch_size argument must always be a multiple of 10!

As an example, we will try to fit the CTGAN model slightly increasing the number of epochs, reducing the batch_size, adding one additional layer to the models involved and using a smaller wright decay.

Before we start, we will evaluate the quality of the previously generated data using the sdv.evaluation.evaluate function

In [35]: from sdv.evaluation import evaluate

In [36]: evaluate(new_data, data)
Out[36]: 0.4685678149375716


Afterwards, we create a new instance of the CTGAN model with the hyperparameter values that we want to use

In [37]: model = CTGAN(
....:     primary_key='student_id',
....:     epochs=500,
....:     batch_size=100,
....:     generator_dim=(256, 256, 256),
....:     discriminator_dim=(256, 256, 256)
....: )
....:


And fit to our data.

In [38]: model.fit(data)


Finally, we are ready to generate new data and evaluate the results.

In [39]: new_data = model.sample(len(data))

In [40]: evaluate(new_data, data)
Out[40]: 0.42504941285091624


As we can see, in this case these modifications changed the obtained results slightly, but they did neither introduce dramatic changes in the performance.

### Conditional Sampling¶

As the name implies, conditional sampling allows us to sample from a conditional distribution using the CTGAN model, which means we can generate only values that satisfy certain conditions. These conditional values can be passed to the sample_conditions method as a list of sdv.sampling.Condition objects or to the sample_remaining_columns method as a dataframe.

When specifying a sdv.sampling.Condition object, we can pass in the desired conditions as a dictionary, as well as specify the number of desired rows for that condition.

In [41]: from sdv.sampling import Condition

In [42]: condition = Condition({
....:     'gender': 'M'
....: }, num_rows=5)
....:

In [43]: model.sample_conditions(conditions=[condition])
Out[43]:
student_id gender  second_perc  ...  start_date   end_date  duration
0           2      M        76.00  ...  2020-02-17 2020-09-10       3.0
1           7      M        86.67  ...  2020-03-15        NaT       5.0
2          10      M        64.77  ...         NaT        NaT       NaN
3          13      M        42.96  ...         NaT        NaT       NaN
4          15      M        89.40  ...  2019-12-27 2020-11-24       4.0

[5 rows x 17 columns]


It’s also possible to condition on multiple columns, such as gender = M, 'experience_years': 0.

In [44]: condition = Condition({
....:     'gender': 'M',
....:     'experience_years': 0
....: }, num_rows=5)
....:

In [45]: model.sample_conditions(conditions=[condition])
Out[45]:
student_id gender  second_perc  ...  start_date   end_date  duration
0           0      M        60.45  ...  2020-01-09 2021-04-17       NaN
1           2      M        62.61  ...  2020-03-01        NaT       NaN
2           5      M        51.81  ...         NaT        NaT       NaN
3           9      M        89.40  ...  2020-06-17 2021-04-15       4.0
4          11      M        89.40  ...  2019-12-30 2021-02-15       7.0

[5 rows x 17 columns]


In the sample_remaining_columns method, conditions is passed as a dataframe. In that case, the model will generate one sample for each row of the dataframe, sorted in the same order. Since the model already knows how many samples to generate, passing it as a parameter is unnecessary. For example, if we want to generate three samples where gender = M and three samples with gender = F, we can do the following:

In [46]: import pandas as pd

In [47]: conditions = pd.DataFrame({
....:     'gender': ['M', 'M', 'M', 'F', 'F', 'F'],
....: })
....:

In [48]: model.sample_remaining_columns(conditions)
Out[48]:
student_id gender  second_perc  ...  start_date   end_date  duration
0           0      M        89.06  ...  2019-12-23 2021-05-04       6.0
1           1      M        89.40  ...  2020-02-08        NaT       4.0
2           2      M        89.40  ...  2020-02-03 2020-10-28       4.0
3           3      F        72.44  ...         NaT        NaT       NaN
4           4      F        76.14  ...         NaT        NaT       6.0
5           5      F        40.89  ...         NaT        NaT       NaN

[6 rows x 17 columns]


CTGAN also supports conditioning on continuous values, as long as the values are within the range of seen numbers. For example, if all the values of the dataset are within 0 and 1, CTGAN will not be able to set this value to 1000.

In [49]: condition = Condition({
....:     'degree_perc': 70.0
....: }, num_rows=5)
....:

In [50]: model.sample_conditions(conditions=[condition])
Out[50]:
student_id gender  second_perc  ...  start_date end_date  duration
0          36      F        76.99  ...         NaT      NaT       NaN
1          20      F        88.83  ...         NaT      NaT       NaN
2           3      M        60.77  ...         NaT      NaT       NaN
3          24      F        72.99  ...         NaT      NaT       5.0
4          11      M        56.64  ...  2020-02-14      NaT       NaN

[5 rows x 17 columns]


Note

Conditional sampling works through a rejection sampling process, where rows are sampled repeatedly until one that satisfies the conditions is found. In case you are not able to sample enough valid rows, update the related parameters: increasing max_tries or increasing batch_size_per_try. More information about these paramters can be found in the API section

If you have many conditions that cannot easily be satisified, consider switching to the GaussianCopula model, which is able to handle conditional sampling more efficiently.

### How do I specify constraints?¶

If you look closely at the data you may notice that some properties were not completely captured by the model. For example, you may have seen that sometimes the model produces an experience_years number greater than 0 while also indicating that work_experience is False. These types of properties are what we call Constraints and can also be handled using SDV. For further details about them please visit the Constraints guide.

### Can I evaluate the Synthetic Data?¶

A very common question when someone starts using SDV to generate synthetic data is: “How good is the data that I just generated?”

In order to answer this question, SDV has a collection of metrics and tools that allow you to compare the real that you provided and the synthetic data that you generated using SDV or any other tool.