Danger

You are looking at the documentation for an older version of the SDV! We are no longer supporting or maintaining this version of the software

Click here to go to the new docs pages.

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

In [2]: data = load_tabular_demo('student_placements')

In [3]: data.head()
Out[3]: 
   student_id gender  second_perc  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0       17264      M        67.00      91.00  Commerce        58.00    Sci&Tech            False                 0                55.0   Mkt&HR     58.80  27000.0    True 2020-07-23 2020-10-12       3.0
1       17265      M        79.33      78.33   Science        77.48    Sci&Tech             True                 1                86.5  Mkt&Fin     66.28  20000.0    True 2020-01-11 2020-04-09       3.0
2       17266      M        65.00      68.00      Arts        64.00   Comm&Mgmt            False                 0                75.0  Mkt&Fin     57.80  25000.0    True 2020-01-26 2020-07-13       6.0
3       17267      M        56.00      52.00   Science        52.00    Sci&Tech            False                 0                66.0   Mkt&HR     59.43      NaN   False        NaT        NaT       NaN
4       17268      M        85.80      73.60  Commerce        73.30   Comm&Mgmt            False                 0                96.8  Mkt&Fin     55.50  42500.0    True 2020-07-04 2020-09-27       3.0

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

  • Their id and gender

  • Their grades and specializations

  • 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 CTGAN 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  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0       17461      M        60.67      56.03   Science        64.02   Comm&Mgmt             True                 1               77.88  Mkt&Fin     70.02      NaN   False        NaT        NaT       NaN
1       17464      F        60.13      60.04  Commerce        64.72   Comm&Mgmt             True                 0               87.46  Mkt&Fin     70.57      NaN   False        NaT        NaT       3.0
2       17431      M        52.64      39.54   Science        51.99    Sci&Tech            False                 1               75.06   Mkt&HR     67.18  47048.0    True 2019-12-22 2020-09-10       3.0
3       17478      M        40.89      60.94   Science        58.69   Comm&Mgmt             True                 1               51.64   Mkt&HR     77.89  30191.0   False 2019-12-21        NaT       6.0
4       17338      M        81.63      59.22   Science        65.85   Comm&Mgmt            False                 1               96.12   Mkt&HR     72.02  30539.0    True        NaT        NaT      11.0

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 cloudpickle.

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')

In [11]: new_data = loaded.sample(num_rows=200)

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  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
1         17478      F        43.43      86.64   Science        73.96   Comm&Mgmt             True                 0               75.84  Mkt&Fin     77.89  29730.0    True        NaT        NaT       NaN
7         17478      F        66.45      86.09      Arts        74.95   Comm&Mgmt            False                 1               50.00   Mkt&HR     65.56  47017.0    True        NaT 2020-10-05       NaN
8         17478      F        56.91      54.37  Commerce        50.00   Comm&Mgmt             True                 1               50.11  Mkt&Fin     65.76  60011.0   False 2020-01-06 2020-12-04       NaN
10        17478      M        83.08      68.06   Science        71.00   Comm&Mgmt             True                 1               70.77   Mkt&HR     75.57  31220.0   False        NaT 2020-06-17       NaN
12        17478      M        58.29      70.74  Commerce        54.37      Others            False                 1               50.00  Mkt&Fin     67.89      NaN    True        NaT 2020-11-08       5.0
14        17478      M        78.84      62.00   Science        74.65   Comm&Mgmt            False                 0               98.00  Mkt&Fin     71.90  33099.0    True 2020-01-02 2020-04-27       3.0
30        17478      M        57.61      77.63  Commerce        55.57   Comm&Mgmt            False                 1               72.26   Mkt&HR     51.88      NaN    True 2019-12-19 2020-09-11       3.0
32        17478      F        89.40      61.22  Commerce        52.87   Comm&Mgmt            False                 0               81.06   Mkt&HR     62.25  30426.0   False        NaT        NaT       6.0
33        17478      F        78.32      70.49  Commerce        50.00   Comm&Mgmt            False                 0               84.86  Mkt&Fin     51.48      NaN   False 2020-01-05        NaT       NaN
37        17478      M        54.90      50.63  Commerce        68.23   Comm&Mgmt             True                 1               57.02  Mkt&Fin     55.35  29544.0    True 2020-03-08 2021-04-21       NaN
38        17478      M        55.99      66.24  Commerce        50.00    Sci&Tech            False                 1               54.90  Mkt&Fin     56.01  47990.0   False 2020-02-25        NaT       3.0
41        17478      M        40.89      54.95      Arts        72.40   Comm&Mgmt            False                 1               57.20   Mkt&HR     67.22  94000.0   False 2019-12-12 2020-07-10       NaN
45        17478      M        52.12      97.70  Commerce        76.07   Comm&Mgmt            False                 1               85.79  Mkt&Fin     58.53  31939.0    True        NaT 2020-06-23       3.0
52        17478      M        52.80      37.43  Commerce        50.00   Comm&Mgmt             True                 0               60.14   Mkt&HR     64.52  32931.0    True 2020-01-29 2020-09-17       4.0
55        17478      F        78.22      54.56  Commerce        59.58      Others            False                 0               75.34  Mkt&Fin     74.63  35076.0   False 2020-02-14        NaT       4.0
68        17478      M        50.21      61.63   Science        52.48   Comm&Mgmt             True                 0               50.00   Mkt&HR     63.85      NaN    True 2020-02-12 2020-07-31       NaN
71        17478      M        61.98      60.65   Science        50.00   Comm&Mgmt            False                 0               70.95  Mkt&Fin     60.40  30909.0   False 2020-02-11 2020-11-19       3.0
76        17478      M        64.58      80.07      Arts        50.00   Comm&Mgmt             True                 1               71.90   Mkt&HR     75.51  31376.0   False        NaT        NaT       NaN
77        17478      M        78.42      82.83  Commerce        55.71   Comm&Mgmt            False                 0               50.00  Mkt&Fin     67.34  30498.0   False        NaT        NaT       NaN
84        17478      M        55.02      50.31   Science        62.68    Sci&Tech            False                 0               75.49  Mkt&Fin     61.73      NaN   False 2020-01-10 2020-08-29       NaN
97        17478      M        58.64      63.79  Commerce        68.60    Sci&Tech            False                 1               50.00   Mkt&HR     62.56  45493.0   False 2020-01-08 2020-12-03       3.0
105       17478      M        66.67      66.81   Science        57.42   Comm&Mgmt            False                 2               53.31  Mkt&Fin     56.02  56703.0   False 2020-02-26 2021-03-14       NaN
110       17478      F        40.89      70.01  Commerce        61.43    Sci&Tech            False                 1               67.79   Mkt&HR     70.05  25997.0    True        NaT        NaT       5.0
111       17478      M        49.41      70.86  Commerce        71.66   Comm&Mgmt             True                 1               91.22  Mkt&Fin     68.83      NaN   False 2020-01-14        NaT       5.0
113       17478      F        67.29      81.38  Commerce        52.50    Sci&Tech            False                 1               50.00   Mkt&HR     77.89      NaN   False 2020-02-19 2021-01-06       NaN
117       17478      F        75.07      71.04  Commerce        55.58   Comm&Mgmt            False                 0               50.00  Mkt&Fin     58.54      NaN   False 2020-01-03 2020-06-20       6.0
118       17478      M        75.35      60.75  Commerce        67.01   Comm&Mgmt             True                 1               50.00  Mkt&Fin     71.45  25065.0   False 2020-05-06 2020-12-18       6.0
121       17478      F        57.64      65.60  Commerce        75.27   Comm&Mgmt            False                 0               60.40  Mkt&Fin     60.05      NaN    True 2019-12-24 2021-05-10       NaN
123       17478      F        73.32      64.75  Commerce        76.83   Comm&Mgmt             True                 1               50.00  Mkt&Fin     72.97  27005.0    True 2020-07-12        NaT       7.0
132       17478      M        76.86      59.74  Commerce        50.00    Sci&Tech            False                 0               50.00   Mkt&HR     60.83      NaN   False 2020-04-25 2021-03-10       NaN
136       17478      M        72.93      68.26  Commerce        50.00   Comm&Mgmt            False                 1               51.75  Mkt&Fin     57.58      NaN    True 2020-01-26        NaT       NaN
140       17478      M        85.16      92.56  Commerce        50.00   Comm&Mgmt             True                 1               58.47   Mkt&HR     75.37  30766.0   False 2019-12-14 2020-10-16       6.0
146       17478      F        43.58      73.35  Commerce        80.00      Others             True                 1               61.02  Mkt&Fin     69.98  30711.0   False        NaT        NaT       5.0
148       17478      M        75.38      88.95  Commerce        76.32   Comm&Mgmt            False                 0               77.55  Mkt&Fin     60.62      NaN   False 2020-05-26 2020-07-24       3.0
157       17478      M        61.66      68.07   Science        50.00      Others             True                 1               58.71  Mkt&Fin     69.95  30223.0    True        NaT        NaT       NaN
166       17478      M        89.40      72.41   Science        60.48    Sci&Tech            False                 0               77.57   Mkt&HR     66.30      NaN   False        NaT 2020-09-07       NaN
167       17478      F        55.73      51.75   Science        50.00    Sci&Tech             True                 0               96.10  Mkt&Fin     71.87      NaN    True 2019-12-24 2020-11-06       3.0
173       17478      M        40.89      44.95  Commerce        50.00    Sci&Tech            False                 1               50.00  Mkt&Fin     72.93  29553.0   False        NaT 2020-12-09       4.0
174       17478      M        53.80      58.88  Commerce        50.00   Comm&Mgmt             True                 1               52.69  Mkt&Fin     69.87      NaN    True 2020-03-12        NaT       NaN
175       17478      M        40.89      63.35  Commerce        50.00   Comm&Mgmt            False                 0               68.14   Mkt&HR     72.68      NaN    True 2020-01-15 2021-03-07       NaN
177       17478      F        79.26      61.98   Science        51.19   Comm&Mgmt            False                 1               53.82  Mkt&Fin     63.78      NaN   False        NaT 2020-08-09       NaN
181       17478      M        58.42      56.92  Commerce        50.00   Comm&Mgmt            False                 1               61.56   Mkt&HR     64.69      NaN   False        NaT        NaT       3.0
184       17478      M        57.38      58.80  Commerce        54.65    Sci&Tech            False                 0               82.06   Mkt&HR     62.56  32389.0    True 2019-12-14 2020-12-08       NaN
186       17478      F        79.39      68.25   Science        74.76   Comm&Mgmt            False                 1               50.00  Mkt&Fin     64.27      NaN    True 2020-01-01        NaT       7.0
193       17478      M        58.44      71.96  Commerce        50.00   Comm&Mgmt            False                 1               50.00   Mkt&HR     72.55      NaN   False 2019-12-27        NaT       3.0
198       17478      M        40.89      68.14  Commerce        56.50    Sci&Tech            False                 0               54.62   Mkt&HR     68.49      NaN   False        NaT        NaT       3.0

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)

In [17]: new_data.head()
Out[17]: 
   student_id gender  second_perc  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0           0      M        40.89      53.16   Science        67.04      Others            False                 0               50.00   Mkt&HR     77.89      NaN   False        NaT        NaT       5.0
1           1      M        40.89      67.39  Commerce        66.94   Comm&Mgmt            False                 0               51.88   Mkt&HR     66.86      NaN   False        NaT        NaT       NaN
2           2      F        40.89      63.36   Science        75.98   Comm&Mgmt             True                 0               91.19   Mkt&HR     71.83  30556.0    True 2020-03-08 2020-09-05       NaN
3           3      M        63.81      37.00  Commerce        72.60   Comm&Mgmt             True                 0               91.97  Mkt&Fin     70.17  20000.0    True 2020-02-12 2020-06-17       5.0
4           4      M        40.89      38.76  Commerce        61.99   Comm&Mgmt            False                 2               50.00  Mkt&Fin     61.44      NaN    True        NaT 2020-11-17       NaN

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')

In [20]: data_pii.head()
Out[20]: 
   student_id                                            address gender  second_perc  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0       17264        70304 Baker Turnpike\nEricborough, MS 15086      M        67.00      91.00  Commerce        58.00    Sci&Tech            False                 0                55.0   Mkt&HR     58.80  27000.0    True 2020-07-23 2020-10-12       3.0
1       17265    805 Herrera Avenue Apt. 134\nMaryview, NJ 36510      M        79.33      78.33   Science        77.48    Sci&Tech             True                 1                86.5  Mkt&Fin     66.28  20000.0    True 2020-01-11 2020-04-09       3.0
2       17266        3702 Bradley Island\nNorth Victor, FL 12268      M        65.00      68.00      Arts        64.00   Comm&Mgmt            False                 0                75.0  Mkt&Fin     57.80  25000.0    True 2020-01-26 2020-07-13       6.0
3       17267                   Unit 0879 Box 3878\nDPO AP 42663      M        56.00      52.00   Science        52.00    Sci&Tech            False                 0                66.0   Mkt&HR     59.43      NaN   False        NaT        NaT       NaN
4       17268  96493 Kelly Canyon Apt. 145\nEast Steven, NC 3...      M        85.80      73.60  Commerce        73.30   Comm&Mgmt            False                 0                96.8  Mkt&Fin     55.50  42500.0    True 2020-07-04 2020-09-27       3.0

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)

In [24]: new_data_pii.head()
Out[24]: 
   student_id                                            address gender  second_perc  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0           0                   PSC 1354, Box 1414\nAPO AA 25325      F        77.14      66.18  Commerce        56.92    Sci&Tech             True                 0               84.88  Mkt&Fin     53.41  40712.0    True 2020-01-06 2020-05-06       6.0
1           1  61808 Catherine Center\nEast Lonnieport, OK 54464      M        74.49      49.82   Science        71.26   Comm&Mgmt            False                 1               50.00   Mkt&HR     57.48      NaN    True 2020-01-07        NaT       6.0
2           2                200 Rivera Club\nCarlfort, SC 50953      M        60.82      60.56      Arts        78.25   Comm&Mgmt             True                 0               50.00  Mkt&Fin     62.26  20000.0    True 2020-01-09 2020-10-18       4.0
3           3     0845 Jeremy Land Apt. 585\nAvilaport, AK 23097      M        86.95      73.96   Science        55.00   Comm&Mgmt             True                 0               58.53  Mkt&Fin     55.61      NaN   False        NaT        NaT       6.0
4           4  99895 Jorge Manor Apt. 381\nWest Christine, FL...      F        79.42      58.46  Commerce        50.00    Sci&Tech             True                 1               50.00  Mkt&Fin     57.44      NaN    True        NaT 2020-09-01       7.0

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

  • address

  • 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={
   ....:         'address': 'address'
   ....:     }
   ....: )
   ....: 

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)

In [29]: new_data_pii.head()
Out[29]: 
   student_id                                            address gender  second_perc  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0           0  4380 Fitzpatrick Freeway\nMichellechester, MO ...      F        77.18      56.23   Science        76.70   Comm&Mgmt            False                 0               50.00   Mkt&HR     51.21  30419.0    True 2020-02-16        NaT       4.0
1           1                           USNS Owens\nFPO AA 94022      M        81.69      60.22   Science        68.69   Comm&Mgmt             True                 1               66.43  Mkt&Fin     63.26  21396.0   False 2020-01-12 2020-09-30       NaN
2           2  36720 Edward Falls Suite 953\nNew Andrewport, ...      M        80.64      56.91  Commerce        71.39    Sci&Tech            False                 1               79.06   Mkt&HR     52.69  20000.0    True        NaT        NaT       3.0
3           3    0650 David Common Apt. 122\nBlackstad, HI 94580      F        68.81      69.27   Science        81.72   Comm&Mgmt             True                 0               70.38  Mkt&Fin     61.88  20000.0   False 2020-02-06 2020-07-15       3.0
4           4           326 Adam Parkway\nLake Miatown, NE 72367      M        47.09      62.82  Commerce        79.82    Sci&Tech            False                 1               77.73  Mkt&Fin     68.68  30228.0   False 2020-09-20 2020-08-28       3.0

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

Advanced Usage

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.

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 [31]: from sdv.evaluation import evaluate

In [32]: evaluate(new_data, data)
Out[32]: 0.7265329082377604

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

In [33]: 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 [34]: model.fit(data)

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

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

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

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 [37]: from sdv.sampling import Condition

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

In [39]: model.sample_conditions(conditions=[condition])
Out[39]: 
   student_id gender  second_perc  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0           0      M        89.40      84.80   Science        67.28    Sci&Tech            False                 0               69.70  Mkt&Fin     57.90  32892.0    True 2020-01-02 2020-10-05       3.0
1           1      M        60.44      75.61  Commerce        63.29    Sci&Tech            False                 0               85.36  Mkt&Fin     73.18  20000.0    True 2020-02-10        NaT       5.0
2           2      M        40.89      56.60   Science        50.00   Comm&Mgmt            False                 0               98.00   Mkt&HR     53.43      NaN   False        NaT        NaT       4.0
3           3      M        71.85      97.70  Commerce        80.49   Comm&Mgmt             True                 0               98.00  Mkt&Fin     51.46  25796.0    True 2020-02-13 2020-07-23       3.0
4           4      M        46.31      85.86  Commerce        71.10   Comm&Mgmt            False                 0               98.00   Mkt&HR     52.69  27775.0    True 2020-01-09        NaT       5.0

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

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

In [41]: model.sample_conditions(conditions=[condition])
Out[41]: 
   student_id gender  second_perc  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0           0      M        62.17      73.87  Commerce        79.26   Comm&Mgmt             True                 0               98.00  Mkt&Fin     51.21  28116.0    True        NaT 2020-06-11       5.0
1           1      M        40.89      59.74   Science        61.67    Sci&Tech            False                 0               69.73   Mkt&HR     55.72      NaN   False        NaT        NaT       NaN
2           2      M        86.32      96.33  Commerce        88.04   Comm&Mgmt             True                 0               87.58   Mkt&HR     60.19  28658.0    True 2020-01-24 2020-09-01       4.0
3           3      M        79.06      73.74  Commerce        91.00   Comm&Mgmt            False                 0               79.71  Mkt&Fin     54.56  31253.0    True 2020-01-23 2020-02-29       3.0
4           4      M        89.40      56.40  Commerce        81.56   Comm&Mgmt             True                 0               91.70  Mkt&Fin     56.28  27407.0    True 2020-03-11 2020-08-26       3.0

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 [42]: import pandas as pd

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

In [44]: model.sample_remaining_columns(conditions)
Out[44]: 
   student_id gender  second_perc  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0           0      M        40.89      70.35   Science        53.58   Comm&Mgmt            False                 0               85.59   Mkt&HR     56.94  30823.0   False        NaT        NaT       3.0
1           1      M        82.37      69.54   Science        88.12   Comm&Mgmt            False                 0               98.00  Mkt&Fin     53.12  27236.0    True 2020-01-05 2020-08-20       3.0
2           2      M        40.89      53.11  Commerce        65.31   Comm&Mgmt            False                 0               84.51   Mkt&HR     61.37      NaN    True 2020-05-20 2020-07-24       6.0
3           3      F        59.12      45.68      Arts        76.61   Comm&Mgmt            False                 0               79.98  Mkt&Fin     51.21  25809.0    True 2020-08-20 2020-09-06       3.0
4           4      F        42.30      68.50   Science        66.65   Comm&Mgmt             True                 0               98.00   Mkt&HR     54.36  32954.0    True 2020-01-12        NaT       6.0
5           5      F        89.40      54.97  Commerce        77.76   Comm&Mgmt            False                 0               97.29  Mkt&Fin     52.90  20000.0    True 2020-01-15 2020-06-17       3.0

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 [45]: condition = Condition({
   ....:     'degree_perc': 70.0
   ....: }, num_rows=5)
   ....: 

In [46]: model.sample_conditions(conditions=[condition])
Out[46]: 
   student_id gender  second_perc  high_perc high_spec  degree_perc degree_type  work_experience  experience_years  employability_perc mba_spec  mba_perc   salary  placed start_date   end_date  duration
0          22      M        71.05      59.75   Science         70.0   Comm&Mgmt            False                 0               98.00  Mkt&Fin     57.86      NaN    True        NaT 2021-03-08       NaN
1          38      F        69.72      69.68   Science         70.0   Comm&Mgmt            False                 0               81.67   Mkt&HR     64.93      NaN   False 2020-03-23 2020-11-30       5.0
2          34      F        52.30      37.00  Commerce         70.0   Comm&Mgmt            False                 3               71.50   Mkt&HR     57.50      NaN   False        NaT 2020-09-30       NaN
3          20      F        53.54      65.50   Science         70.0   Comm&Mgmt            False                 0               82.22   Mkt&HR     51.21      NaN   False        NaT 2020-08-02       NaN
4          47      M        53.93      78.79      Arts         70.0   Comm&Mgmt            False                 0               54.13  Mkt&Fin     54.94  28347.0   False 2020-01-08 2020-07-28       3.0

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, try increasing max_tries_per_batch. More information about this parameter 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?

After creating synthetic data, you may be wondering how you can evaluate it against the original data. You can use the SDMetrics library to get more insights, generate reports and visualize the data. This library is automatically installed with SDV.

To get started, visit: https://docs.sdv.dev/sdmetrics/