GaussianCopula Model

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

  • Create an instance of a GaussianCopula.

  • Fit the instance to your data.

  • Generate synthetic versions of your data.

  • Use GaussianCopula to anonymize PII information.

  • Customize the data transformations to improve the learning process.

  • Specify the column distributions to improve the output quality.

What is GaussianCopula?

The sdv.tabular.GaussianCopula model is based on copula funtions.

In mathematical terms, a copula is a distribution over the unit cube \({\displaystyle [0,1]^{d}}\) which is constructed from a multivariate normal distribution over \({\displaystyle \mathbb {R} ^{d}}\) by using the probability integral transform. Intuitively, a copula is a mathematical function that allows us to describe the joint distribution of multiple random variables by analyzing the dependencies between their marginal distributions.

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 GaussianCopula model.

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.

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 where 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 the GaussianCopula to learn this data and then sample synthetic data about new students to see how well de model captures the characteristics indicated above. In order to do this you will need to:

  • Import the sdv.tabular.GaussianCopula 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 GaussianCopula

In [5]: model = GaussianCopula()

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 GaussianMultivariate model 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       17318      M    67.459231  65.363306  Commerce    69.221815    Sci&Tech            False                -1           88.318099  Mkt&Fin  55.142590  25312.729020    True 2020-03-19 2020-05-31      3.0
1       17336      M    57.673583  73.769039   Science    66.708695    Sci&Tech            False                 0           85.591060   Mkt&HR  64.612023           NaN   False        NaT        NaT      NaN
2       17354      M    71.681980  70.601270   Science    73.835648    Sci&Tech            False                 0           85.081901   Mkt&HR  57.454183  25266.125322    True 2020-01-10 2020-07-22      3.0
3       17275      F    69.000231  64.075265  Commerce    65.854598   Comm&Mgmt            False                 0           52.404010   Mkt&HR  63.436819           NaN   False        NaT        NaT      NaN
4       17409      F    69.481804  68.210630  Commerce    63.749937   Comm&Mgmt            False                 1           61.895119  Mkt&Fin  53.905013           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 send over to the system where the synthetic data will be generated. Once it is there, you can load it using the GaussianCopula.load method, and then you are ready to sample new data from the loaded instance:

In [10]: loaded = GaussianCopula.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 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 that 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.student_id.value_counts().max()
Out[13]: 5

In [14]: new_data[new_data.student_id == new_data.student_id.value_counts().index[0]]
Out[14]: 
     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
16        17359      M    79.619434  66.226971   Science    67.986712    Sci&Tech            False                -1           85.443593   Mkt&HR  58.242021  26896.458429    True 2020-02-08 2020-07-31      3.0
115       17359      M    76.305570  65.143614      Arts    62.494661      Others            False                 1           69.815086   Mkt&HR  65.939695  33265.060575    True 2020-02-13 2020-08-12      3.0
183       17359      M    69.434039  87.307529  Commerce    62.730293   Comm&Mgmt            False                 1           95.291322  Mkt&Fin  53.575568  20896.410321    True 2020-01-07 2020-09-07     12.0
184       17359      M    68.640793  65.518870   Science    57.740421   Comm&Mgmt            False                 1           92.279683   Mkt&HR  56.329927  30311.819960    True 2020-06-20 2020-12-31      3.0
193       17359      M    80.749196  65.087871   Science    59.466241    Sci&Tech            False                -1           56.692914  Mkt&Fin  60.181241           NaN   False        NaT        NaT      NaN

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 [15]: model = GaussianCopula(
   ....:     primary_key='student_id'
   ....: )
   ....: 

In [16]: model.fit(data)

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

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.head()
Out[18]: 
   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    65.769739  65.660682  Commerce    66.923137   Comm&Mgmt            False                 0           73.237954  Mkt&Fin  56.375117           NaN   False        NaT        NaT      NaN
1           1      M    79.045326  64.792590   Science    68.110822    Sci&Tech            False                 0           87.929210  Mkt&Fin  64.337442  38089.306364    True 2020-01-06 2020-07-01      3.0
2           2      M    87.970588  93.169796   Science    62.977060    Sci&Tech            False                 1           82.628143  Mkt&Fin  62.849870  27343.184263    True 2020-03-01 2020-07-03      3.0
3           3      F    59.705723  64.773057  Commerce    66.078467   Comm&Mgmt            False                 0           77.345172  Mkt&Fin  64.707108           NaN   False        NaT        NaT      NaN
4           4      M    66.405494  64.624800  Commerce    66.003635   Comm&Mgmt            False                 0           65.889526   Mkt&HR  52.926746           NaN   False        NaT        NaT      NaN

In [19]: new_data.student_id.value_counts().max()
Out[19]: 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 [20]: data_pii = load_tabular_demo('student_placements_pii')

In [21]: data_pii.head()
Out[21]: 
   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 [22]: model = GaussianCopula(
   ....:     primary_key='student_id',
   ....: )
   ....: 

In [23]: model.fit(data_pii)

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

In [25]: new_data_pii.head()
Out[25]: 
   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       51290 Escobar Place\nSouth Madison, WI 89087      F    85.872486  78.005584   Science    78.750209   Comm&Mgmt            False                 1           56.639883   Mkt&HR  66.232675  31977.260634    True 2020-01-18 2020-09-17      3.0
1           1  16569 Koch Throughway\nPort Christopher, NM 46073      F    41.609433  38.047520  Commerce    55.082567   Comm&Mgmt            False                 1           58.534410   Mkt&HR  60.243543           NaN   False        NaT        NaT      NaN
2           2                   PSC 7593, Box 4710\nAPO AA 62043      F    58.873829  70.304011  Commerce    69.751384   Comm&Mgmt            False                 0           82.117047  Mkt&Fin  64.127385  19738.986121   False 2020-01-02 2020-09-05      NaN
3           3  01921 Jackson Gardens Apt. 637\nDanielberg, OH...      M    52.992688  64.899634   Science    66.102530    Sci&Tech            False                 0           64.430379   Mkt&HR  52.806471           NaN   False        NaT        NaT      NaN
4           4  21119 Bailey Mall Apt. 215\nCameronbury, GA 31205      M    42.013406  53.713977  Commerce    58.294853   Comm&Mgmt            False                 1           65.756823   Mkt&HR  55.173724           NaN   False        NaT        NaT      NaN

In [26]: new_data_pii.address.isin(data_pii.address).sum()
Out[26]: 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 [27]: model = GaussianCopula(
   ....:     primary_key='student_id',
   ....:     anonymize_fields={
   ....:         'address': 'address'
   ....:     }
   ....: )
   ....: 

In [28]: model.fit(data_pii)

As a result, we can see how the real address values have been replaced by other fake addresses that were not taken from the real data that we learned.

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

In [30]: new_data_pii.head()
Out[30]: 
   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               20574 Clark Loop\nLambside, VA 69537      M    80.681042  67.758259   Science    63.728880   Comm&Mgmt            False                 0           84.322268  Mkt&Fin  56.842827  25309.888805    True 2020-01-08 2020-10-15     12.0
1           1  008 Villanueva Radial\nWest Stevenmouth, OH 37507      M    68.906144  71.699329   Science    65.097049   Comm&Mgmt            False                 0           85.519603   Mkt&HR  67.350349  34367.434126    True 2020-05-01 2020-10-09      3.0
2           2   1958 Donna Stravenue\nSouth Kathyshire, NM 05485      M    63.670652  62.329728   Science    69.668128    Sci&Tech            False                 1           65.640111  Mkt&Fin  57.449744  21414.278457    True 2020-01-27 2020-10-10      3.0
3           3                            USNV King\nFPO AA 69232      M    57.500631  49.887246   Science    61.399632   Comm&Mgmt            False                -1           65.430851  Mkt&Fin  53.379204  32104.657437    True 2020-01-20 2020-04-10      3.0
4           4         886 Grant Light\nPort Debbieport, WY 61384      M    55.893734  90.539365  Commerce    70.290758   Comm&Mgmt            False                -1           70.701578  Mkt&Fin  61.806672  29755.122881    True 2020-05-03 2020-10-22      3.0

In [31]: new_data_pii.address.isin(data_pii.address).sum()
Out[31]: 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 GaussianCopula Model in order to customize it to our needs.

How to set transforms to use?

One thing that you may have noticed when executing the previous steps is that the fitting process took much longer on the student_placements_pii dataset than it took on the previous version that did not contain the student address. This happens because the address field is interpreted as a categorical variable, which the GaussianCopula one-hot encoded generating 215 new columns that it had to learn afterwards.

This transformation, which in this case was very inefficient, happens because the Tabular Models apply Reversible Data Transforms under the hood to transform all the non-numerical variables, which the underlying models cannot handle, into numerical representations which they can properly work with. In the case of the GaussianCopula, the default transformation is a One-Hot encoding, which can work very well with variables that have a little number of different values, but which is very inefficient in cases where there is a large number of values.

For this reason, the Tabular Models have an additional argument called field_transformers that let you select which transformer to apply to each column. This field_transformers argument must be passed as a dict which contains the name of the fields for which we want to use a transformer different than the default, and the name of the transformer that we want to use.

Possible transformer names are:

  • integer: Uses a NumericalTransformer of dtype int.

  • float: Uses a NumericalTransformer of dtype float.

  • categorical: Uses a CategoricalTransformer without gaussian noise.

  • categorical_fuzzy: Uses a CategoricalTransformer adding gaussian noise.

  • one_hot_encoding: Uses a OneHotEncodingTransformer.

  • label_encoding: Uses a LabelEncodingTransformer.

  • boolean: Uses a BooleanTransformer.

  • datetime: Uses a DatetimeTransformer.

NOTE: For additional details about each one of the transformers, please visit RDT

Let’s now try to improve the previous fitting process by changing the transformer that we use for the address field to something other than the default. As an example, we will use the label_encoding transformer, which instead of generating one column for each possible value, it just replaces each value with a unique integer value.

In [32]: model = GaussianCopula(
   ....:     primary_key='student_id',
   ....:     anonymize_fields={
   ....:         'address': 'address'
   ....:     },
   ....:     field_transformers={
   ....:         'address': 'label_encoding'
   ....:     }
   ....: )
   ....: 

In [33]: model.fit(data_pii)

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

In [35]: new_data_pii.head()
Out[35]: 
   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                   Unit 8320 Box 0974\nDPO AA 46029      M    61.638703  50.037470  Commerce    58.012356    Sci&Tech            False                 1           90.650590  Mkt&Fin  63.713748           NaN   False        NaT        NaT      NaN
1           1           01232 Matthew Creek\nNew Brian, WA 31672      M    68.454324  65.829807  Commerce    73.995860   Comm&Mgmt            False                 0           56.693998  Mkt&Fin  52.447181  31265.741492    True 2020-01-13 2020-05-05      3.0
2           2  5838 Johnson Lane Apt. 641\nWalkerchester, NM ...      M    86.271561  79.116082   Science    65.535684    Sci&Tech            False                 1           94.951123  Mkt&Fin  69.351926  36748.016175    True 2020-01-18 2020-08-09      3.0
3           3        64485 Jones Island\nEast Samantha, RI 48952      M    79.923358  76.355261  Commerce    76.174380   Comm&Mgmt            False                 1           73.834702  Mkt&Fin  64.890534  24340.764918    True 2020-02-23 2020-04-14      3.0
4           4  712 Matthews Spring Suite 218\nLake Brandyview...      F    77.209967  64.890306  Commerce    73.290472   Comm&Mgmt            False                 0           87.373672  Mkt&Fin  68.413053           NaN   False        NaT        NaT      NaN

Exploring the Probability Distributions

During the previous steps, every time we fitted the GaussianCopula it performed the following operations:

  1. Learn the format and data types of the passed data

  2. Transform the non-numerical and null data using Reversible Data Transforms to obtain a fully numerical representation of the data from which we can learn the probability distributions.

  3. Learn the probability distribution of each column from the table

  4. Transform the values of each numerical column by converting them to their marginal distribution CDF values and then applying an inverse CDF transformation of a standard normal on them.

  5. Learn the correlations of the newly generated random variables.

After this, when we used the model to generate new data for our table using the sample method, it did:

  1. Sample from a Multivariate Standard Normal distribution with the learned correlations.

  2. Revert the sampled values by computing their standard normal CDF and then applyting the inverse CDF of their marginal distributions.

  3. Revert the RDT transformations to go back to the original data format.

As you can see, during these steps the Marginal Probability Distributions have a very important role, since the GaussianCopula had to learn and reproduce the individual distributions of each column in our table. We can explore the distributions which the GaussianCopula used to model each column using its get_distributions method:

In [36]: model = GaussianCopula(
   ....:     primary_key='student_id'
   ....: )
   ....: 

In [37]: model.fit(data)

In [38]: distributions = model.get_distributions()

This will return us a dict which contains the name of the distribution class used for each column:

In [39]: distributions
Out[39]: 
{'gender#0': 'copulas.univariate.gaussian.GaussianUnivariate',
 'gender#1': 'copulas.univariate.gaussian.GaussianUnivariate',
 'second_perc': 'copulas.univariate.truncated_gaussian.TruncatedGaussian',
 'high_perc': 'copulas.univariate.log_laplace.LogLaplace',
 'high_spec#0': 'copulas.univariate.gaussian.GaussianUnivariate',
 'high_spec#1': 'copulas.univariate.gamma.GammaUnivariate',
 'high_spec#2': 'copulas.univariate.gaussian.GaussianUnivariate',
 'degree_perc': 'copulas.univariate.student_t.StudentTUnivariate',
 'degree_type#0': 'copulas.univariate.student_t.StudentTUnivariate',
 'degree_type#1': 'copulas.univariate.gaussian.GaussianUnivariate',
 'degree_type#2': 'copulas.univariate.gaussian.GaussianUnivariate',
 'work_experience': 'copulas.univariate.student_t.StudentTUnivariate',
 'experience_years': 'copulas.univariate.gaussian.GaussianUnivariate',
 'employability_perc': 'copulas.univariate.truncated_gaussian.TruncatedGaussian',
 'mba_spec#0': 'copulas.univariate.gamma.GammaUnivariate',
 'mba_spec#1': 'copulas.univariate.gaussian.GaussianUnivariate',
 'mba_perc': 'copulas.univariate.gamma.GammaUnivariate',
 'salary#0': 'copulas.univariate.gamma.GammaUnivariate',
 'salary#1': 'copulas.univariate.gaussian.GaussianUnivariate',
 'placed': 'copulas.univariate.gamma.GammaUnivariate',
 'start_date#0': 'copulas.univariate.gamma.GammaUnivariate',
 'start_date#1': 'copulas.univariate.gaussian.GaussianUnivariate',
 'end_date#0': 'copulas.univariate.gamma.GammaUnivariate',
 'end_date#1': 'copulas.univariate.gaussian.GaussianUnivariate',
 'duration#0': 'copulas.univariate.gaussian.GaussianUnivariate',
 'duration#1': 'copulas.univariate.gaussian.GaussianUnivariate',
 'duration#2': 'copulas.univariate.student_t.StudentTUnivariate',
 'duration#3': 'copulas.univariate.gaussian.GaussianUnivariate'}

Note

In this list we will see multiple distributions for each one of the columns that we have in our data. This is because the RDT transformations used to encode the data numerically often use more than one column to represent each one of the input variables.

Let’s explore the individual distribution of one of the columns in our data to better understand how the GaussianCopula processed them and see if we can improve the results by manually specifying a different distribution. For example, let’s explore the experience_years column by looking at the frequency of its values within the original data:

In [40]: data.experience_years.value_counts()
Out[40]: 
0    141
1     65
2      8
3      1
Name: experience_years, dtype: int64

In [41]: data.experience_years.hist();
../../_images/experience_years_1.png

By observing the data we can see that the behavior of the values in this column is very similar to a Gamma or even some types of Beta distribution, where the majority of the values are 0 and the frequency decreases as the values increase.

Was the GaussianCopula able to capture this distribution on its own?

In [42]: distributions['experience_years']
Out[42]: 'copulas.univariate.gaussian.GaussianUnivariate'

It seems that the it was not, as it rather thought that the behavior was closer to a Gaussian distribution. And, as a result, we can see how the generated values now contain negative values which are invalid for this column:

In [43]: new_data.experience_years.value_counts()
Out[43]: 
 0    99
 1    77
-1    19
 2     5
Name: experience_years, dtype: int64

In [44]: new_data.experience_years.hist();
../../_images/experience_years_2.png

Let’s see how we can improve this situation by passing the GaussianCopula the exact distribution that we want it to use for this column.

Setting distributions for indvidual variables

The GaussianCopula class offers the possibility to indicate which distribution to use for each one of the columns in the table, in order to solve situations like the one that we just described. In order to do this, we need to pass a distributions argument with dict that indicates, the distribution that we want to use for each column.

Possible values for the distribution argument are:

  • univariate: Let copulas select the optimal univariate distribution. This may result in non-parametric models being used.

  • parametric: Let copulas select the optimal univariate distribution, but restrict the selection to parametric distributions only.

  • bounded: Let copulas select the optimal univariate distribution, but restrict the selection to bounded distributions only. This may result in non-parametric models being used.

  • semi_bounded: Let copulas select the optimal univariate distribution, but restrict the selection to semi-bounded distributions only. This may result in non-parametric models being used.

  • parametric_bounded: Let copulas select the optimal univariate distribution, but restrict the selection to parametric and bounded distributions only.

  • parametric_semi_bounded: Let copulas select the optimal univariate distribution, but restrict the selection to parametric and semi-bounded distributions only.

  • gaussian: Use a Gaussian distribution.

  • gamma: Use a Gamma distribution.

  • beta: Use a Beta distribution.

  • student_t: Use a Student T distribution.

  • gussian_kde: Use a GaussianKDE distribution. This model is non-parametric, so using this will make get_parameters unusable.

  • truncated_gaussian: Use a Truncated Gaussian distribution.

Let’s see what happens if we make the GaussianCopula use the gamma distribution for our column.

In [45]: from sdv.tabular import GaussianCopula

In [46]: model = GaussianCopula(
   ....:     primary_key='student_id',
   ....:     distribution={
   ....:         'experience_years': 'gamma'
   ....:     }
   ....: )
   ....: 

In [47]: model.fit(data)

After this, we can see how the GaussianCopula used the indicated distribution for the experience_years column

In [48]: model.get_distributions()['experience_years']
Out[48]: 'copulas.univariate.gamma.GammaUnivariate'

And, as a result, now we can see how the generated data now have a behavior which is closer to the original data and always stays within the valid values range.

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

In [50]: new_data.experience_years.value_counts()
Out[50]: 
0    198
1     16
6      1
Name: experience_years, dtype: int64

In [51]: new_data.experience_years.hist();
../../_images/experience_years_3.png

Note

Even though there are situations like the one show above where manually choosing a distribution seems to give better results, in most cases the GaussianCopula will be able to find the optimal distribution on its own, making this manual search of the marginal distributions necessary on very little occasions.

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 type of properties are what we call Constraints and can also be handled using SDV. For further details about them please visit the Handling 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 Evaluating Synthetic Data guide.