TVAE Model

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

  • Create an instance of TVAE.

  • Fit the instance to your data.

  • Generate synthetic versions of your data.

  • Use TVAE to anonymize PII information.

  • Customize the data transformations to improve the learning process.

  • Specify hyperparameters to improve the output quality.

What is TVAE?

The sdv.tabular.TVAE model is based on the VAE-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 TVAE 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 tvae installed on your system. If you have not done it yet, please install tvae 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 TVAE 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.TVAE 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 TVAE

In [5]: model = TVAE()

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

In [7]: new_data = model.sample(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       17408      M        77.71      64.66  Commerce        69.69   Comm&Mgmt            False                 0               57.78  Mkt&Fin     54.97  23400.0    True 2020-01-17 2020-11-12       3.0
1       17382      M        51.11      76.69  Commerce        69.71   Comm&Mgmt            False                 0               56.63   Mkt&HR     51.21  22700.0    True 2020-01-24 2020-10-07       3.0
2       17394      M        60.15      55.45  Commerce        67.61   Comm&Mgmt             True                 0               66.31  Mkt&Fin     57.91  24100.0    True 2020-01-26 2020-11-13       3.0
3       17416      M        64.30      73.60  Commerce        68.85   Comm&Mgmt             True                 1               80.01  Mkt&Fin     53.32  23700.0    True 2020-07-09 2020-12-25       3.0
4       17411      M        44.01      61.97  Commerce        57.31   Comm&Mgmt            False                 0               59.78  Mkt&Fin     56.95      NaN   False        NaT        NaT       NaN

Note

You can control the number of rows by specifying the number of samples in the model.sample(<num_rows>). To test, try model.sample(10000). Note that the original table only had ~200 rows.

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 TVAE.load method, and then you are ready to sample new data from the loaded instance:

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

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

Warning

Notice that the system where the model is loaded needs to also have sdv and tvae 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
10        17478      F        69.44      57.98  Commerce        63.35   Comm&Mgmt            False                 0               65.83  Mkt&Fin     67.39      NaN   False        NaT        NaT       NaN
14        17478      M        66.79      48.25  Commerce        56.02   Comm&Mgmt            False                 0               56.55  Mkt&Fin     61.29      NaN   False        NaT        NaT       NaN
28        17478      M        72.59      68.32  Commerce        61.56   Comm&Mgmt             True                 0               72.73  Mkt&Fin     69.54  21100.0    True 2020-01-18 2020-07-21       6.0
116       17478      M        72.81      73.63   Science        70.05   Comm&Mgmt             True                 1               72.39  Mkt&Fin     63.79  20200.0    True 2020-01-18 2020-11-24       3.0
123       17478      M        52.01      66.38  Commerce        53.28   Comm&Mgmt            False                 0               61.89   Mkt&HR     55.64  25200.0    True 2020-01-19 2020-09-15       6.0
137       17478      M        75.21      78.88  Commerce        63.93   Comm&Mgmt            False                 0               55.38  Mkt&Fin     54.84  22000.0    True 2020-01-11 2020-08-28       6.0
196       17478      M        54.45      83.86  Commerce        79.02   Comm&Mgmt            False                 0               65.06  Mkt&Fin     53.52  28200.0    True 2020-01-09 2020-07-28       5.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 = TVAE(
   ....:     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        59.47      79.26  Commerce        65.72   Comm&Mgmt            False                 0               63.55  Mkt&Fin     62.11  24000.0    True 2020-01-13 2020-08-10       3.0
1           1      M        72.63      77.30  Commerce        71.96   Comm&Mgmt            False                 0               54.95  Mkt&Fin     74.51  24000.0    True 2020-01-21 2021-01-04       3.0
2           2      M        54.81      75.36  Commerce        56.23   Comm&Mgmt            False                 0               61.72  Mkt&Fin     58.00  24400.0    True 2020-01-18 2021-01-15       3.0
3           3      M        51.64      44.15  Commerce        52.86   Comm&Mgmt            False                 0               50.00   Mkt&HR     59.69      NaN   False        NaT        NaT       NaN
4           4      M        74.71      64.17  Commerce        61.55   Comm&Mgmt             True                 0               60.27  Mkt&Fin     71.67      NaN   False        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

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 = TVAE(
   ....:     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       54911 Gloria Island\nLake Veronica, WA 91035      F        76.69      61.60  Commerce        65.54   Comm&Mgmt            False                 0               59.85  Mkt&Fin     61.02  25100.0    True 2020-01-23 2020-04-18       3.0
1           1           82602 Wilcox Curve\nNew Angela, OR 84462      M        55.70      70.63  Commerce        67.81   Comm&Mgmt            False                 0               56.02   Mkt&HR     59.89      NaN   False        NaT        NaT       NaN
2           2  3953 Kristina Place Suite 635\nNew Juanville, ...      M        62.04      57.27  Commerce        65.44   Comm&Mgmt             True                 0               62.82  Mkt&Fin     55.00  30900.0    True 2020-01-08 2020-07-26       6.0
3           3   9976 James Crest Apt. 125\nStevenhaven, GA 30830      M        57.84      73.19  Commerce        77.88   Comm&Mgmt             True                 0               63.15  Mkt&Fin     52.16  27200.0    True 2020-01-17 2020-12-28       3.0
4           4      653 Mark Forge Suite 804\nBillyview, KS 58544      M        54.12      61.64  Commerce        58.52   Comm&Mgmt            False                 0               85.10  Mkt&Fin     65.88  29200.0    True 2020-01-07 2020-08-01       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:

  • 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 e-mail address, we will pass a dictionary indicating the category address

In [26]: model = TVAE(
   ....:     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    946 Paul Skyway Apt. 185\nWhitemouth, MO 42446      M        59.99      79.35  Commerce        69.39   Comm&Mgmt            False                 0               81.75   Mkt&HR     58.95  26600.0    True 2020-01-18 2020-10-22       3.0
1           1  57190 William Summit\nSouth Danieltown, WV 49920      M        60.03      60.52  Commerce        59.96   Comm&Mgmt            False                 0               62.29  Mkt&Fin     56.64  25700.0    True 2020-01-24 2020-10-29       3.0
2           2       19738 Wilson Coves\nKatherinefort, VA 70776      M        66.98      79.65  Commerce        70.18   Comm&Mgmt            False                 0               74.19  Mkt&Fin     60.30  24100.0    True 2020-01-17 2020-10-21       3.0
3           3   69193 Amy Wall Suite 952\nMichaelberg, NV 29082      M        50.60      77.87  Commerce        75.63   Comm&Mgmt            False                 0               62.92  Mkt&Fin     54.56  22200.0    True 2020-01-21 2020-09-27       6.0
4           4             9456 Sara Inlet\nEast Keith, NE 78873      M        59.88      59.49  Commerce        68.36   Comm&Mgmt            False                 0               59.69  Mkt&Fin     57.56  24800.0    True 2020-01-25 2020-07-29       6.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.

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 = TVAE(
   ....:     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  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        66.56      66.84  Commerce        60.94   Comm&Mgmt            False                 0               53.57  Mkt&Fin     60.81  23273.15    True 2020-01-12 2020-05-19      3.21
1           1      F        62.48      69.59  Commerce        67.97   Comm&Mgmt            False                 0               84.58  Mkt&Fin     67.30  28911.75    True 2020-01-16 2020-08-25      5.47
2           2      M        61.00      72.65  Commerce        71.26   Comm&Mgmt            False                 0               60.62   Mkt&HR     57.90  26508.47    True 2020-01-11 2020-10-03      2.96
3           3      M        61.58      70.49  Commerce        61.12   Comm&Mgmt            False                 0               56.32  Mkt&Fin     56.00  25207.27    True 2020-01-16 2020-10-25      3.18
4           4      M        60.40      63.95  Commerce        62.09   Comm&Mgmt            False                 0               57.98   Mkt&HR     57.85  23573.17    True 2020-01-16 2020-08-10      5.63
5           5      M        52.49      67.38  Commerce        59.71   Comm&Mgmt            False                 0               51.36   Mkt&HR     53.04  27502.46    True 2020-01-11 2020-08-18      3.06
6           6      M        50.45      55.06  Commerce        60.57   Comm&Mgmt            False                 0               64.11   Mkt&HR     67.66       NaN   False        NaT        NaT       NaN
7           7      M        45.67      77.90  Commerce        57.92   Comm&Mgmt            False                 0               56.77   Mkt&HR     55.27  27258.70   False 2020-03-05 2020-08-04      2.93
8           8      M        66.56      61.31  Commerce        58.21   Comm&Mgmt            False                 0               66.31  Mkt&Fin     61.58  21889.97    True 2020-01-16 2020-11-07      3.06
9           9      M        57.01      62.57  Commerce        66.47   Comm&Mgmt            False                 0               72.61   Mkt&HR     52.44  24744.55    True 2020-01-27 2020-03-13      2.99

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

How to modify the TVAE Hyperparameters?

A part from the common Tabular Model arguments, TVAE 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.

  • compress_dims (tuple or list of ints): Size of each hidden layer in the encoder. Defaults to (128, 128).

  • decompress_dims (tuple or list of ints): Size of each hidden layer in the decoder. Defaults to (128, 128).

  • l2scale (int): Regularization term. Defaults to 1e-5.

  • batch_size (int): Number of data samples to process in each step.

  • loss_factor (int): Multiplier for the reconstruction error. Defaults to 2.

  • 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 TVAE 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.3790899166455016

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

In [37]: model = TVAE(
   ....:     primary_key='student_id',
   ....:     epochs=500,
   ....:     compress_dims=(256, 256, 256),
   ....:     decompress_dims=(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.40904395295748786

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 TVAE model, which means we can generate only values that satisfy certain conditions. These conditional values can be passed to the conditions parameter in the sample method either as a dataframe or a dictionary.

In case a dictionary is passed, the model will generate as many rows as requested, all of which will satisfy the specified conditions, such as gender = M.

In [41]: conditions = {
   ....:     'gender': 'M'
   ....: }
   ....: 

In [42]: model.sample(5, conditions=conditions)
Out[42]: 
   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        69.63      74.90  Commerce        71.00   Comm&Mgmt             True                 0               50.00  Mkt&Fin     53.94  24100.0    True 2020-01-24 2021-01-07      12.0
1           1      M        45.61      73.87  Commerce        58.29   Comm&Mgmt            False                 0               68.31   Mkt&HR     58.57      NaN   False        NaT        NaT       NaN
2           2      M        78.35      79.11  Commerce        71.83   Comm&Mgmt             True                 0               79.67  Mkt&Fin     67.89  22800.0    True 2020-01-19 2021-01-05       3.0
3           3      M        61.18      55.70  Commerce        62.04   Comm&Mgmt             True                 0               65.87  Mkt&Fin     53.19  27100.0    True 2020-01-15 2020-12-14       3.0
4           4      M        71.92      55.79  Commerce        74.98   Comm&Mgmt            False                 0               98.00  Mkt&Fin     61.89  23600.0    True 2020-01-28 2020-03-23       3.0

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

In [43]: conditions = {
   ....:     'gender': 'M',
   ....:     'experience_years': 0
   ....: }
   ....: 

In [44]: model.sample(5, conditions=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        61.73      72.43  Commerce        62.88   Comm&Mgmt             True                 0               93.10  Mkt&Fin     65.30  24900.0    True 2020-01-05 2020-10-30      12.0
1           1      M        65.08      56.14  Commerce        66.58   Comm&Mgmt            False                 0               54.19   Mkt&HR     57.19      NaN   False        NaT        NaT       NaN
2           2      M        62.59      66.34  Commerce        54.98   Comm&Mgmt            False                 0               53.97   Mkt&HR     53.71      NaN   False        NaT        NaT       NaN
3           3      M        56.44      57.51  Commerce        60.57   Comm&Mgmt            False                 0               67.42   Mkt&HR     57.05      NaN   False        NaT        NaT       NaN
4           4      M        70.62      82.75  Commerce        62.96   Comm&Mgmt            False                 0               61.39  Mkt&Fin     55.07  25200.0    True 2020-01-12 2020-04-17       3.0

The conditions can also be 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 [45]: import pandas as pd

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

In [47]: model.sample(conditions=conditions)
Out[47]: 
   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        77.11      69.36  Commerce        60.70   Comm&Mgmt            False                 0               58.41  Mkt&Fin     55.17  20400.0    True 2020-01-23 2020-12-13       3.0
1           1      M        73.89      83.35  Commerce        72.76   Comm&Mgmt             True                 0               79.83  Mkt&Fin     68.15  24400.0    True 2020-01-12 2020-07-26       6.0
2           2      M        65.42      81.48  Commerce        64.38   Comm&Mgmt             True                 0               62.72  Mkt&Fin     53.62  20500.0    True 2019-12-31 2020-11-25      12.0
3           3      F        54.37      64.68  Commerce        62.15   Comm&Mgmt            False                 0               62.25   Mkt&HR     68.69      NaN   False        NaT        NaT       NaN
4           4      F        89.40      88.14  Commerce        72.76   Comm&Mgmt             True                 0               86.35  Mkt&Fin     67.92  23200.0    True 2020-01-13 2020-10-24      12.0
5           5      F        72.26      59.02  Commerce        63.06   Comm&Mgmt            False                 0               64.17   Mkt&HR     58.34      NaN   False        NaT        NaT       NaN

TVAE 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, TVAE will not be able to set this value to 1000.

In [48]: conditions = {
   ....:     'degree_perc': 70.0
   ....: }
   ....: 

In [49]: model.sample(5, conditions=conditions)
Out[49]: 
   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           3      M        82.94      76.85   Science         70.0   Comm&Mgmt             True                 0               95.07  Mkt&Fin     65.84  26000.0    True 2020-01-08 2020-04-08       3.0
1          11      M        67.16      82.80  Commerce         70.0   Comm&Mgmt             True                 0               90.70  Mkt&Fin     65.25  23000.0    True 2020-01-28 2020-03-26       3.0
2          22      M        72.75      67.09  Commerce         70.0   Comm&Mgmt             True                 0               92.51  Mkt&Fin     66.87  22500.0    True 2020-01-17 2020-07-22       6.0
3          26      M        81.49      97.70  Commerce         70.0   Comm&Mgmt            False                 0               80.53  Mkt&Fin     58.21  21600.0    True 2020-01-17 2020-04-22       3.0
4           1      M        63.08      58.75  Commerce         70.0   Comm&Mgmt            False                 0               50.56   Mkt&HR     53.89      NaN   False        NaT        NaT       NaN

Note

Currently, 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 running into a Could not get enough valid rows within x trials or simply wish to optimize the results, there are three parameters that can be fine-tuned: max_rows_multiplier, max_retries and float_rtol. More information about these parameters can be found in the API section.

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.

You can read more about this in the Synthetic Data Evaluation guide.