Try the new SDV 1.0 Beta! We are transitioning to a new version of SDV with improved workflows, new features and an updated documentation site. Click here to go to the new docs pages.
Try the new SDV 1.0 Beta!
We are transitioning to a new version of SDV with improved workflows, new features and an updated documentation site.
Click here to go to the new docs pages.
In this guide we will go through a series of steps that will let you discover functionalities of the CTGAN model, including how to:
CTGAN
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.
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.
sdv.tabular.CTGAN
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.
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.
student_placements
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.
ctgan
pip install sdv
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.
fit
Call its sample method indicating the number of synthetic rows that you want to generate.
sample
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.
fitting
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.
num_rows
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 17264 M 55.70 91.78 Science 74.60 Others False 0 52.01 Mkt&Fin 66.71 30905.0 False NaT 2020-10-03 5.0 1 17393 M 52.53 58.92 Commerce 50.85 Comm&Mgmt False 0 87.33 Mkt&HR 60.00 29723.0 True 2020-01-04 NaT NaN 2 17290 M 64.88 81.04 Science 50.69 Comm&Mgmt False 1 69.71 Mkt&HR 59.94 NaN True NaT NaT 3.0 3 17264 M 69.74 66.78 Commerce 83.45 Others False 0 77.89 Mkt&HR 52.12 NaN False 2020-02-14 2020-09-22 5.0 4 17365 M 70.11 73.82 Science 58.63 Sci&Tech True 0 61.85 Mkt&HR 56.40 NaN True NaT 2020-07-15 3.0
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.
output_file_path
batch_size
randomize_samples
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.
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.
save
.pkl
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.
my_model.pkl
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!
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:
CTGAN.load
In [10]: loaded = CTGAN.load('my_model.pkl') In [11]: new_data = loaded.sample(num_rows=200)
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.
sdv
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:
student_id
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 4 17264 M 61.10 70.01 Science 59.12 Others False 0 55.63 Mkt&Fin 65.84 30064.0 False 2020-03-12 2020-12-09 4.0 9 17264 M 41.50 86.68 Science 60.26 Comm&Mgmt False 0 54.99 Mkt&Fin 53.69 29731.0 False 2020-01-05 NaT NaN 19 17264 M 67.94 59.88 Science 58.42 Comm&Mgmt True 1 50.00 Mkt&Fin 51.21 NaN False 2020-03-04 2020-08-14 NaN 29 17264 M 64.90 79.74 Commerce 77.28 Others False 0 69.56 Mkt&Fin 56.32 27755.0 False 2019-12-18 2020-08-03 5.0 30 17264 M 68.05 65.88 Commerce 51.99 Comm&Mgmt False 0 78.62 Mkt&HR 64.75 26718.0 True NaT 2020-07-04 3.0 33 17264 M 66.61 37.00 Commerce 70.46 Comm&Mgmt False 0 56.26 Mkt&Fin 56.97 NaN True NaT 2020-08-10 NaN 38 17264 M 79.96 75.49 Commerce 75.83 Sci&Tech True 1 96.66 Mkt&Fin 51.21 27193.0 True NaT 2020-08-18 NaN 43 17264 M 47.64 54.41 Science 54.97 Sci&Tech True 0 68.61 Mkt&Fin 57.99 29732.0 True 2020-03-21 2020-07-18 NaN 51 17264 M 49.79 65.93 Science 65.07 Comm&Mgmt False 1 56.52 Mkt&Fin 77.89 NaN True 2020-09-26 NaT NaN 58 17264 M 82.17 66.56 Science 70.51 Others False 1 58.07 Mkt&HR 58.96 73349.0 True NaT NaT NaN 63 17264 M 77.07 58.89 Science 64.97 Sci&Tech False 0 60.98 Mkt&HR 68.58 NaN False 2020-01-08 2020-08-10 6.0 75 17264 M 56.73 60.72 Science 50.00 Sci&Tech False 0 66.30 Mkt&HR 61.01 35520.0 True 2020-02-23 NaT 5.0 79 17264 M 82.02 59.64 Science 75.16 Comm&Mgmt False 1 61.92 Mkt&Fin 67.79 30121.0 False NaT 2021-04-10 NaN 91 17264 M 40.89 72.78 Science 50.00 Sci&Tech False 2 78.17 Mkt&Fin 59.07 26959.0 True 2020-03-11 2020-06-05 7.0 97 17264 F 61.12 42.21 Commerce 69.65 Sci&Tech False 1 69.90 Mkt&HR 65.46 NaN False NaT 2020-09-10 6.0 104 17264 M 70.00 89.34 Science 66.08 Comm&Mgmt False 1 52.76 Mkt&Fin 59.98 21629.0 True NaT 2020-10-10 NaN 112 17264 F 71.44 62.41 Commerce 55.90 Comm&Mgmt False 0 87.10 Mkt&HR 51.21 25431.0 False NaT 2020-06-09 NaN 113 17264 M 40.89 64.67 Commerce 54.99 Others True 1 85.99 Mkt&Fin 51.21 NaN True 2020-03-10 2020-05-10 3.0 118 17264 F 63.66 53.78 Commerce 75.19 Comm&Mgmt False 0 58.37 Mkt&HR 71.47 NaN False 2020-03-10 2020-08-07 NaN 123 17264 M 61.89 60.13 Commerce 76.21 Others False 0 85.01 Mkt&HR 51.21 NaN True NaT 2020-08-16 NaN 125 17264 M 79.91 69.04 Science 70.22 Comm&Mgmt True 1 95.55 Mkt&HR 73.14 25246.0 False NaT 2020-09-24 NaN 128 17264 F 51.83 51.38 Science 66.52 Comm&Mgmt False 1 58.64 Mkt&HR 51.21 31619.0 False 2020-02-29 2020-06-24 NaN 140 17264 F 82.91 53.97 Science 50.00 Comm&Mgmt False 0 60.73 Mkt&HR 53.32 NaN False 2019-12-19 NaT 3.0 145 17264 M 56.87 45.53 Commerce 64.94 Comm&Mgmt False 0 73.75 Mkt&HR 51.21 NaN True NaT 2020-08-16 NaN 146 17264 M 43.16 80.67 Commerce 61.87 Sci&Tech False 0 89.02 Mkt&Fin 62.10 27567.0 True 2020-03-26 2020-10-27 3.0 151 17264 M 60.33 63.95 Commerce 69.44 Comm&Mgmt False 1 55.87 Mkt&Fin 53.27 28975.0 False 2020-01-09 2020-09-24 12.0 157 17264 F 76.30 61.06 Commerce 78.72 Others False 1 50.00 Mkt&HR 52.16 28775.0 False NaT 2020-07-10 4.0 168 17264 F 41.69 52.70 Science 85.49 Comm&Mgmt False 0 89.38 Mkt&HR 55.09 26837.0 True NaT 2020-06-24 NaN 170 17264 M 74.82 47.89 Science 68.32 Comm&Mgmt False 1 55.87 Mkt&Fin 62.67 NaN True 2020-02-13 2020-11-07 NaN 173 17264 M 70.90 64.77 Commerce 72.81 Comm&Mgmt False 0 84.34 Mkt&Fin 72.67 29468.0 True 2020-06-30 NaT 3.0 184 17264 M 82.76 65.32 Science 71.50 Sci&Tech False 0 62.22 Mkt&Fin 62.43 NaN False NaT 2020-08-07 6.0 186 17264 F 72.41 64.39 Commerce 50.00 Sci&Tech True 0 53.94 Mkt&Fin 57.05 NaN False NaT NaT 3.0 191 17264 M 67.05 54.54 Science 78.11 Sci&Tech False 0 59.61 Mkt&HR 65.98 NaN True NaT NaT NaN 193 17264 M 53.45 95.71 Arts 84.86 Comm&Mgmt False 1 67.22 Mkt&Fin 52.58 NaN True 2020-03-22 2020-08-20 5.0 197 17264 F 73.23 55.26 Commerce 64.07 Sci&Tech True 0 89.31 Mkt&HR 54.13 NaN False 2019-12-18 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.
primary_key
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 82.80 81.53 Commerce 88.48 Comm&Mgmt False 0 98.00 Mkt&HR 60.02 26243.0 True 2020-02-22 2020-08-11 NaN 1 1 M 79.46 69.63 Commerce 75.58 Comm&Mgmt False 1 74.44 Mkt&HR 60.16 NaN True 2020-01-22 2020-08-24 3.0 2 2 F 51.45 73.54 Commerce 78.62 Comm&Mgmt False 1 95.83 Mkt&Fin 71.03 NaN True NaT 2020-08-15 NaN 3 3 F 42.79 68.72 Science 64.88 Comm&Mgmt False 0 98.00 Mkt&Fin 77.52 NaN True 2020-01-09 2020-03-28 5.0 4 4 F 50.17 68.14 Commerce 69.48 Comm&Mgmt False 0 97.18 Mkt&Fin 63.81 NaN True NaT NaT 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
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.
student_placements_pii
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.
address
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 530 Katrina Wall Suite 443\nJimmouth, WV 05020 M 69.28 88.60 Commerce 50.00 Comm&Mgmt False 0 60.66 Mkt&HR 64.97 29910.0 True NaT 2020-10-07 3.0 1 1 6175 Eugene Crossing\nCurryview, OH 86092 F 55.44 61.47 Commerce 60.91 Comm&Mgmt False 0 73.58 Mkt&Fin 56.54 NaN True NaT 2020-06-12 8.0 2 2 976 Li Lodge Apt. 715\nMichaelborough, KY 20573 F 46.48 69.19 Commerce 78.59 Comm&Mgmt True 0 50.00 Mkt&Fin 72.45 28421.0 True NaT 2020-10-30 NaN 3 3 022 Macias Path\nVeronicaberg, MT 54117 M 72.93 97.70 Arts 50.00 Comm&Mgmt False 0 58.29 Mkt&Fin 70.67 NaN False 2020-02-17 2020-07-20 6.0 4 4 201 Rhodes Isle\nPort Robertmouth, MS 27570 F 69.98 68.13 Commerce 56.61 Comm&Mgmt False 0 66.22 Mkt&HR 51.21 20000.0 True NaT 2020-07-24 6.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:
anonymize_fields
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={ ....: '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 99399 Peter Light\nSouth Patricia, AR 33255 F 49.65 75.27 Science 71.30 Comm&Mgmt False 0 67.47 Mkt&Fin 77.02 NaN False NaT NaT NaN 1 1 PSC 6062, Box 7848\nAPO AP 26378 M 79.03 97.70 Commerce 73.31 Comm&Mgmt False 0 83.44 Mkt&Fin 58.02 42954.0 False 2019-12-26 2020-08-11 6.0 2 2 453 Ashley Ford Apt. 963\nNorth Shannonfort, T... F 59.32 59.51 Science 72.14 Sci&Tech False 1 69.83 Mkt&Fin 73.84 NaN True 2020-03-17 NaT 5.0 3 3 PSC 8347, Box 9028\nAPO AP 08181 M 43.38 97.70 Science 55.89 Comm&Mgmt False 0 65.70 Mkt&HR 65.57 29376.0 False NaT 2021-02-16 NaN 4 4 1597 Jo Turnpike Apt. 458\nSouth Barbara, MN 9... M 72.18 82.24 Science 74.61 Comm&Mgmt False 0 88.78 Mkt&Fin 73.99 26991.0 True 2020-02-17 2020-08-03 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
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.
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.
epochs
300
500
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.
log_frequency
True
False
embedding_dim (int): Size of the random sample passed to the Generator. Defaults to 128.
embedding_dim
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).
generator_dim
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).
discriminator_dim
generator_lr (float): Learning rate for the generator. Defaults to 2e-4.
generator_lr
generator_decay (float): Generator weight decay for the Adam Optimizer. Defaults to 1e-6.
generator_decay
discriminator_lr (float): Learning rate for the discriminator. Defaults to 2e-4.
discriminator_lr
discriminator_decay (float): Discriminator weight decay for the Adam Optimizer. Defaults to 1e-6.
discriminator_decay
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.
discriminator_steps
verbose: Whether to print fit progress on stdout. Defaults to False.
verbose
cuda (bool or str): If True, use CUDA. If a str, use the indicated device. If False, do not use cuda at all.
cuda
str
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
sdv.evaluation.evaluate
In [31]: from sdv.evaluation import evaluate In [32]: evaluate(new_data, data) Out[32]: 0.8032608891520943
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.7237381941318953
As we can see, in this case these modifications changed the obtained results slightly, but they did neither introduce dramatic changes in the performance.
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.
sample_conditions
sdv.sampling.Condition
sample_remaining_columns
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 1 M 89.40 56.79 Commerce 91.00 Comm&Mgmt True 1 92.68 Mkt&HR 59.60 26647.0 True 2020-06-24 2021-04-13 4.0 1 3 M 80.35 37.00 Arts 66.53 Sci&Tech False 0 88.72 Mkt&HR 52.61 NaN False NaT 2020-10-03 NaN 2 9 M 89.40 70.46 Science 91.00 Sci&Tech True 1 80.72 Mkt&Fin 59.57 27176.0 True 2020-08-08 2020-06-18 NaN 3 10 M 74.10 51.14 Science 68.45 Sci&Tech False 1 76.26 Mkt&HR 64.93 NaN False NaT NaT NaN 4 11 M 62.21 52.84 Science 70.32 Comm&Mgmt True 0 98.00 Mkt&HR 56.89 38890.0 True 2020-07-31 2021-05-06 NaN
It’s also possible to condition on multiple columns, such as gender = M, 'experience_years': 0.
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 71.25 37.00 Science 50.00 Sci&Tech False 0 50.60 Mkt&Fin 74.68 NaN False 2020-03-25 NaT NaN 1 1 M 40.89 50.06 Science 50.00 Comm&Mgmt False 0 64.91 Mkt&HR 58.33 NaN False NaT NaT NaN 2 2 M 55.50 54.08 Science 50.00 Comm&Mgmt True 0 73.37 Mkt&Fin 52.15 NaN False NaT NaT NaN 3 3 M 89.40 41.09 Commerce 79.53 Comm&Mgmt True 0 72.69 Mkt&HR 51.22 NaN True 2020-08-16 NaT NaN 4 4 M 74.64 69.10 Commerce 76.38 Sci&Tech True 0 95.61 Mkt&HR 51.21 NaN True 2020-03-12 2020-10-07 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:
conditions
gender = M
gender = F
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 89.40 50.78 Science 69.30 Comm&Mgmt True 1 96.07 Mkt&Fin 63.77 25649.0 False 2020-07-30 2020-11-28 NaN 1 1 M 64.10 62.77 Commerce 59.52 Comm&Mgmt False 0 98.00 Mkt&HR 58.97 NaN False NaT NaT NaN 2 2 M 89.40 51.35 Arts 84.16 Comm&Mgmt True 1 74.08 Mkt&Fin 57.02 20000.0 True 2020-02-02 2020-09-08 4.0 3 3 F 89.40 60.54 Commerce 91.00 Comm&Mgmt True 0 92.57 Mkt&HR 53.05 21432.0 True 2020-05-22 2020-03-29 NaN 4 4 F 89.40 77.04 Commerce 86.11 Sci&Tech True 0 72.73 Mkt&HR 69.37 35881.0 True 2020-02-29 2020-07-14 7.0 5 5 F 49.48 42.35 Commerce 50.00 Sci&Tech False 1 50.00 Mkt&HR 54.49 NaN False NaT NaT 5.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 24 F 89.40 53.49 Commerce 70.0 Comm&Mgmt False 1 87.19 Mkt&HR 53.88 NaN False NaT NaT NaN 1 17 M 69.65 71.01 Commerce 70.0 Comm&Mgmt False 1 60.84 Mkt&Fin 77.89 25083.0 True NaT 2020-02-20 NaN 2 35 F 71.39 80.65 Science 70.0 Comm&Mgmt True 0 98.00 Mkt&Fin 60.97 NaN True 2020-03-04 2020-09-14 NaN 3 45 M 53.28 51.59 Commerce 70.0 Sci&Tech False 0 82.25 Mkt&HR 51.21 NaN False NaT 2021-03-16 6.0 4 21 M 72.95 42.66 Science 70.0 Others True 0 84.26 Mkt&HR 61.70 25483.0 True NaT 2020-04-25 NaN
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
max_tries_per_batch
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.
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.
experience_years
0
work_experience
Constraints
SDV
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/