# CopulaGAN Model¶

In this guide we will go through a series of steps that will let you
discover functionalities of the `CopulaGAN`

model, including how to:

Create an instance of

`CopulaGAN`

.Fit the instance to your data.

Generate synthetic versions of your data.

Use

`CopulaGAN`

to anonymize PII information.Customize the data transformations to improve the learning process.

Specify the column distributions to improve the output quality.

Specify hyperparameters to improve the output quality.

## What is CopulaGAN?¶

The `sdv.tabular.CopulaGAN`

model is a variation of the CTGAN Model
which takes advantage of the CDF based transformation that the GaussianCopulas
apply to make the underlying CTGAN model task of learning the data easier.

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 `CopulaGAN`

class from SDV.

## Quick Usage¶

We will start by loading one of our demo datasets, the
`student_placements`

, which contains information about MBA students
that applied for placements during the year 2020.

Warning

In order to follow this guide you need to have `ctgan`

installed on
your system. If you have not done it yet, please install `ctgan`

now
by executing the command `pip install sdv`

in a terminal.

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

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

Their id and gender

Their grades and specializations

Their work experience

The salary that they were offered

The duration and dates of their placement

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

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

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

Let us use `CopulaGAN`

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.CopulaGAN`

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 CopulaGAN
In [5]: model = CopulaGAN()
In [6]: model.fit(data)
```

Note

Notice that the model `fitting`

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

### Generate synthetic data from the model¶

Once the modeling has finished you are ready to generate new synthetic
data by calling the `sample`

method from your model passing the number
of rows that we want to generate.

```
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 17465 M 80.04 84.29 Science 57.70 Comm&Mgmt False 0 92.66 Mkt&HR 62.82 NaN True 2020-01-15 NaT NaN
1 17384 M 51.66 58.15 Arts 68.52 Comm&Mgmt False 1 76.96 Mkt&HR 67.16 26700.0 True 2020-01-17 2020-07-27 6.0
2 17268 M 64.83 60.90 Commerce 60.28 Sci&Tech False 0 54.10 Mkt&Fin 75.69 NaN False 2020-03-16 2020-08-02 NaN
3 17470 F 49.41 79.62 Science 69.85 Comm&Mgmt False 0 83.38 Mkt&Fin 59.45 20000.0 True 2020-01-18 2020-07-29 6.0
4 17477 M 73.57 66.94 Science 60.09 Comm&Mgmt False 0 50.93 Mkt&Fin 60.80 NaN False NaT NaT 6.0
```

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.

#### 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 `CopulaGAN.load`

method, and then you are ready to sample new
data from the loaded instance:

```
In [10]: loaded = CopulaGAN.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 `ctgan`

installed, otherwise it will not be able to load
the model and use it.

### Specifying the Primary Key of the table¶

One of the first things that you may have noticed when looking at the demo
data is that there is a `student_id`

column which acts as the primary
key of the table, and which is supposed to have unique values. Indeed,
if we look at the number of times that each value appears, we see that
all of them appear at most once:

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

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

```
In [13]: new_data[new_data.student_id == new_data.student_id.value_counts().index[0]]
Out[13]:
student_id gender second_perc high_perc high_spec degree_perc degree_type work_experience experience_years employability_perc mba_spec mba_perc salary placed start_date end_date duration
3 17477 M 63.88 86.95 Commerce 50.00 Comm&Mgmt False 1 81.36 Mkt&Fin 51.68 NaN True 2020-01-19 NaT 6.0
7 17477 M 54.53 64.38 Science 75.77 Comm&Mgmt False 0 52.07 Mkt&HR 73.37 27300.0 True NaT NaT NaN
22 17477 M 42.07 97.70 Commerce 62.62 Sci&Tech False 0 84.65 Mkt&Fin 73.75 NaN True 2020-03-12 NaT 3.0
31 17477 M 73.34 85.82 Commerce 69.54 Comm&Mgmt False 1 62.39 Mkt&Fin 77.89 NaN False NaT NaT 6.0
34 17477 M 57.22 66.77 Commerce 65.59 Comm&Mgmt False 0 60.15 Mkt&Fin 57.94 20200.0 True NaT 2020-10-23 5.0
37 17477 F 69.70 61.73 Commerce 80.07 Comm&Mgmt False 1 56.98 Mkt&Fin 77.89 52000.0 False 2020-01-01 NaT 3.0
69 17477 M 72.38 73.59 Arts 52.43 Comm&Mgmt False 0 53.75 Mkt&Fin 73.43 30900.0 False 2020-03-11 2020-07-25 NaN
95 17477 M 84.22 72.36 Science 63.28 Comm&Mgmt False 0 57.97 Mkt&HR 67.87 NaN True NaT 2020-07-27 4.0
97 17477 M 70.13 97.70 Commerce 60.75 Comm&Mgmt False 0 62.28 Mkt&HR 73.98 NaN False NaT 2021-01-06 NaN
99 17477 M 73.31 88.23 Arts 57.24 Comm&Mgmt False 1 54.01 Mkt&Fin 66.06 29000.0 True 2020-05-18 2020-04-04 5.0
153 17477 M 45.70 69.35 Science 69.01 Sci&Tech False 0 55.20 Mkt&Fin 53.99 NaN True 2020-10-01 2020-04-29 6.0
191 17477 M 71.50 67.64 Commerce 66.44 Comm&Mgmt False 0 77.51 Mkt&Fin 67.38 28200.0 True 2020-01-19 NaT 7.0
195 17477 M 42.53 79.24 Commerce 58.78 Comm&Mgmt False 0 59.55 Mkt&Fin 54.39 30900.0 True 2020-03-12 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 [14]: model = CopulaGAN(
....: 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 83.50 59.53 Science 65.52 Sci&Tech False 0 55.01 Mkt&HR 62.27 40400.0 True 2020-09-11 NaT NaN
1 1 M 40.89 97.70 Science 61.45 Comm&Mgmt False 0 61.29 Mkt&Fin 64.42 NaN True 2020-03-29 2020-06-18 6.0
2 2 F 84.67 37.00 Science 77.96 Comm&Mgmt False 0 69.00 Mkt&HR 68.78 29200.0 True NaT 2020-03-31 3.0
3 3 F 74.44 73.18 Commerce 72.89 Comm&Mgmt False 0 73.94 Mkt&Fin 73.63 30300.0 True NaT 2020-07-01 NaN
4 4 M 66.29 84.24 Science 67.55 Comm&Mgmt False 0 52.83 Mkt&Fin 64.36 30700.0 True 2020-08-10 NaT 5.0
```

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 = CopulaGAN(
....: 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 6175 Eugene Crossing\nCurryview, OH 86092 M 75.70 61.86 Science 69.59 Others False 0 69.95 Mkt&HR 68.07 28000.0 False NaT NaT 6.0
1 1 9923 Colon Camp\nNew Amy, NH 42340 M 60.77 37.00 Commerce 69.22 Sci&Tech False 1 89.34 Mkt&HR 69.06 28300.0 True NaT NaT 7.0
2 2 6175 Eugene Crossing\nCurryview, OH 86092 M 41.00 78.12 Commerce 60.68 Others False 0 52.87 Mkt&HR 74.53 28600.0 True 2020-02-24 2021-04-01 3.0
3 3 038 Jennifer Estate Suite 567\nWilliamsfurt, S... M 74.16 61.15 Commerce 73.30 Comm&Mgmt False 0 56.10 Mkt&HR 51.21 23800.0 True NaT NaT NaN
4 4 13930 Todd Meadow Suite 105\nThompsonton, AZ 6... M 42.09 54.07 Commerce 69.79 Sci&Tech False 0 55.48 Mkt&Fin 51.21 NaN False NaT NaT NaN
```

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

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

In order to solve this, we can pass an additional argument
`anonymize_fields`

to our model when we create the instance. This
`anonymize_fields`

argument will need to be a dictionary that
contains:

The name of the field that we want to anonymize.

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

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

name

address

country

city

ssn

credit_card_number

credit_card_expire

credit_card_security_code

email

telephone

…

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

```
In [26]: model = CopulaGAN(
....: 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 that were not taken from the real data
that we learned.

```
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 230 Clark Underpass Suite 936\nAlexandraport, ... M 70.78 80.21 Science 69.69 Comm&Mgmt False 0 52.79 Mkt&Fin 68.87 30000.0 False NaT 2021-03-06 5.0
1 1 134 Hernandez Villages\nNew Sara, MO 48339 M 76.70 37.00 Commerce 80.57 Comm&Mgmt False 0 52.59 Mkt&Fin 71.57 30100.0 True NaT 2020-08-27 5.0
2 2 10577 Mayo Turnpike Apt. 470\nNorth Debra, NJ ... F 52.67 39.14 Science 66.28 Comm&Mgmt False 1 51.01 Mkt&HR 63.20 29600.0 True NaT 2020-06-01 NaN
3 3 Unit 1382 Box 1823\nDPO AA 28040 F 60.36 55.16 Science 64.20 Sci&Tech True 1 56.85 Mkt&HR 59.28 NaN False 2020-06-17 NaT 12.0
4 4 78120 Teresa Passage Suite 108\nDonnamouth, KY... M 59.43 44.31 Arts 58.38 Sci&Tech False 0 68.18 Mkt&Fin 59.13 NaN False NaT 2020-09-04 5.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 `CopulaGAN`

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 = CopulaGAN(
....: 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 46.10 80.16 Commerce 60.97 Sci&Tech False 1 54.21 Mkt&Fin 61.78 NaN True 2020-02-14 2021-04-18 4.51
1 1 M 71.57 71.14 Commerce 86.97 Comm&Mgmt False 0 80.16 Mkt&HR 63.46 57143.13 False 2020-02-15 2020-09-12 NaN
2 2 F 48.39 103.37 Commerce 45.42 Comm&Mgmt False 0 64.59 Mkt&HR 51.20 NaN True 2020-03-21 2020-08-12 5.27
3 3 F 42.13 63.52 Commerce 78.36 Comm&Mgmt True 1 55.90 Mkt&HR 58.54 22625.14 True 2020-02-19 NaT NaN
4 4 M 65.35 70.23 Commerce 61.73 Sci&Tech False 1 89.10 Mkt&Fin 66.03 NaN False 2020-02-21 2020-09-23 NaN
5 5 F 85.19 71.96 Science 73.82 Comm&Mgmt False 0 53.10 Mkt&Fin 61.13 26927.57 True 2020-03-16 NaT NaN
6 6 M 81.59 65.06 Commerce 81.76 Comm&Mgmt False 2 66.35 Mkt&Fin 60.15 NaN False 2020-01-14 2020-06-04 2.36
7 7 F 57.09 129.59 Commerce 74.69 Others False 0 50.66 Mkt&Fin 54.58 NaN False 2020-01-22 2020-09-06 5.89
8 8 F 49.67 93.44 Science 71.62 Comm&Mgmt True 1 68.71 Mkt&Fin 69.93 31628.29 True NaT NaT 3.08
9 9 F 83.16 71.61 Commerce 81.72 Comm&Mgmt False 1 66.40 Mkt&HR 68.55 29844.70 True 2020-02-22 NaT 2.79
```

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

### Exploring the Probability Distributions¶

During the previous steps, every time we fitted the `CopulaGAN`

it performed the following operations:

Learn the format and data types of the passed data

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.

Learn the probability distribution of each column from the table

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.

Fit a CTGAN model on the transformed data, which learns how each column is correlated to the others.

After this, when we used the model to generate new data for our table
using the `sample`

method, it did:

Sample rows from the CTGAN model.

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

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 `CopulaGAN`

had to learn and reproduce the individual distributions of each column
in our table. We can explore the distributions which the
`CopulaGAN`

used to model each column using its
`get_distributions`

method:

```
In [35]: model = CopulaGAN(
....: primary_key='student_id',
....: min_value=None,
....: max_value=None
....: )
....:
In [36]: model.fit(data)
In [37]: distributions = model.get_distributions()
```

This will return us a `dict`

which contains the name of the
distribution class used for each column:

```
In [38]: distributions
Out[38]:
{'second_perc.value': 'copulas.univariate.truncated_gaussian.TruncatedGaussian',
'high_perc.value': 'copulas.univariate.log_laplace.LogLaplace',
'degree_perc.value': 'copulas.univariate.student_t.StudentTUnivariate',
'work_experience.value': 'copulas.univariate.student_t.StudentTUnivariate',
'experience_years.value': 'copulas.univariate.gaussian.GaussianUnivariate',
'employability_perc.value': 'copulas.univariate.truncated_gaussian.TruncatedGaussian',
'mba_perc.value': 'copulas.univariate.gamma.GammaUnivariate',
'salary.value': 'copulas.univariate.gamma.GammaUnivariate',
'placed.value': 'copulas.univariate.gamma.GammaUnivariate',
'start_date.value': 'copulas.univariate.gamma.GammaUnivariate',
'end_date.value': 'copulas.univariate.gamma.GammaUnivariate',
'duration.value': 'copulas.univariate.student_t.StudentTUnivariate'}
```

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 `CopulaGAN`

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 [39]: data.experience_years.value_counts()
Out[39]:
0 141
1 65
2 8
3 1
Name: experience_years, dtype: int64
In [40]: data.experience_years.hist();
```

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 `CopulaGAN`

able to capture this distribution on its own?

```
In [41]: distributions['experience_years.value']
Out[41]: '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 [42]: new_data.experience_years.value_counts()
Out[42]:
0 157
1 39
3 4
Name: experience_years, dtype: int64
In [43]: new_data.experience_years.hist();
```

Let’s see how we can improve this situation by passing the
`CopulaGAN`

the exact distribution that we want it to use for
this column.

### Setting distributions for indvidual variables¶

The `CopulaGAN`

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 `field_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.`gaussian_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 `CopulaGAN`

use the
`gamma`

distribution for our column.

```
In [44]: model = CopulaGAN(
....: primary_key='student_id',
....: field_distributions={
....: 'experience_years': 'gamma'
....: },
....: min_value=None,
....: max_value=None
....: )
....:
In [45]: model.fit(data)
```

After this, we can see how the `CopulaGAN`

used the indicated
distribution for the `experience_years`

column

```
In [46]: model.get_distributions()['experience_years.value']
Out[46]: 'copulas.univariate.gaussian.GaussianUnivariate'
```

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 [47]: new_data = model.sample(len(data))
In [48]: new_data.experience_years.value_counts()
Out[48]:
0 153
1 62
Name: experience_years, dtype: int64
In [49]: new_data.experience_years.hist();
```

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
`CopulaGAN`

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 to modify the CopulaGAN Hyperparameters?¶

A part from the arguments explained above, `CopulaGAN`

has a number
of additional hyperparameters that control its learning behavior and can
impact on the performance of the model, both in terms of quality of the
generated data and computational time:

`epochs`

and`batch_size`

: these arguments control the number of iterations that the model will perform to optimize its parameters, as well as the number of samples used in each step. Its default values are`300`

and`500`

respectively, and`batch_size`

needs to always be a value which is multiple of`10`

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

`log_frequency`

: Whether to use log frequency of categorical levels in conditional sampling. It defaults to`True`

. This argument affects how the model processes the frequencies of the categorical values that are used to condition the rest of the values. In some cases, changing it to`False`

could lead to better performance.`embedding_dim`

(int): Size of the random sample passed to the Generator. Defaults to 128.`generator_dim`

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

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

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

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

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

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

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

: Whether to print fit progress on stdout. Defaults to`False`

.

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 `CopulaGAN`

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 [50]: from sdv.evaluation import evaluate
In [51]: evaluate(new_data, data)
Out[51]: 0.4184397418233871
```

Afterwards, we create a new instance of the `CopulaGAN`

model with the
hyperparameter values that we want to use

```
In [52]: model = CopulaGAN(
....: 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 [53]: model.fit(data)
```

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

```
In [54]: new_data = model.sample(len(data))
In [55]: evaluate(new_data, data)
Out[55]: 0.4707492771092919
```

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 `CopulaGAN`

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 [56]: conditions = {
....: 'gender': 'M'
....: }
....:
In [57]: model.sample(5, conditions=conditions)
Out[57]:
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.30 58.98 Commerce 53.81 Comm&Mgmt False 1 64.92 Mkt&HR 62.93 24300.0 True 2020-02-10 2020-03-07 7.0
1 1 M 77.55 49.78 Commerce 57.82 Comm&Mgmt True 0 74.01 Mkt&Fin 54.46 NaN False NaT NaT NaN
2 2 M 47.85 74.75 Arts 53.87 Sci&Tech False 1 78.30 Mkt&Fin 55.39 NaN True NaT 2020-08-25 NaN
3 3 M 84.99 64.08 Science 71.48 Sci&Tech False 1 59.83 Mkt&Fin 72.42 31500.0 True 2020-06-30 NaT 3.0
4 4 M 46.25 53.99 Commerce 54.31 Comm&Mgmt False 1 88.93 Mkt&HR 65.34 31800.0 False 2020-02-29 NaT NaN
```

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

.

```
In [58]: conditions = {
....: 'gender': 'M',
....: 'experience_years': 0
....: }
....:
In [59]: model.sample(5, conditions=conditions)
Out[59]:
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 83.37 62.25 Commerce 62.88 Comm&Mgmt False 0 91.97 Mkt&Fin 68.89 NaN True 2020-01-05 NaT 6.0
1 4 M 54.58 44.49 Commerce 59.48 Comm&Mgmt False 0 92.02 Mkt&Fin 75.47 29400.0 True NaT 2020-07-30 6.0
2 5 M 43.49 37.00 Science 56.25 Comm&Mgmt False 0 59.87 Mkt&HR 55.09 NaN True 2020-03-13 NaT NaN
3 6 M 58.50 59.52 Science 50.43 Sci&Tech False 0 75.75 Mkt&Fin 61.41 32900.0 False 2020-03-08 NaT 5.0
4 7 M 62.58 49.28 Commerce 69.15 Comm&Mgmt False 0 85.46 Mkt&Fin 68.09 28700.0 True 2020-02-22 2020-10-28 6.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 [60]: import pandas as pd
In [61]: conditions = pd.DataFrame({
....: 'gender': ['M', 'M', 'M', 'F', 'F', 'F'],
....: })
....:
In [62]: model.sample(conditions=conditions)
Out[62]:
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 2 M 86.49 56.32 Commerce 68.21 Sci&Tech False 0 98.00 Mkt&Fin 72.77 30200.0 True 2020-02-11 2020-07-30 4.0
1 5 M 42.48 65.80 Commerce 50.00 Comm&Mgmt False 0 55.73 Mkt&Fin 51.21 NaN False 2020-01-13 2020-11-22 NaN
2 7 M 55.61 60.75 Arts 52.68 Sci&Tech False 0 54.51 Mkt&Fin 58.37 NaN True NaT NaT NaN
3 1 F 41.05 66.18 Commerce 50.00 Comm&Mgmt False 0 71.94 Mkt&HR 61.74 NaN False NaT NaT NaN
4 3 F 87.49 64.10 Commerce 50.00 Others False 3 80.60 Mkt&HR 57.43 NaN True NaT 2020-09-07 NaN
5 0 F 61.35 60.61 Science 50.00 Comm&Mgmt False 1 79.14 Mkt&HR 64.11 NaN False NaT NaT NaN
```

`CopulaGAN`

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, `CopulaGAN`

will not be able to set this value to 1000.

```
In [63]: conditions = {
....: 'degree_perc': 70.0
....: }
....:
In [64]: model.sample(5, conditions=conditions)
Out[64]:
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 27 F 89.34 90.94 Arts 70.0 Comm&Mgmt False 0 81.18 Mkt&Fin 77.81 23100.0 True 2020-01-11 2020-01-29 12.0
1 41 F 89.36 77.76 Commerce 70.0 Comm&Mgmt False 1 89.08 Mkt&Fin 76.66 29500.0 True 2020-01-06 2020-07-15 3.0
2 38 M 80.72 63.80 Science 70.0 Comm&Mgmt False 0 80.72 Mkt&Fin 61.85 NaN False 2020-01-29 NaT 3.0
3 44 M 89.28 68.54 Science 70.0 Others False 1 73.91 Mkt&Fin 68.30 27600.0 True 2020-10-21 2020-08-19 12.0
4 19 F 45.13 71.85 Science 70.0 Comm&Mgmt False 1 53.94 Mkt&Fin 55.35 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.