# ❖ XGCSynthesizer

{% hint style="info" %}
❖ **SDV Enterprise Bundle**. This feature is available as part of the **XSynthesizers Bundle**, an optional add-on to SDV Enterprise. For more information, please visit the [XSynthesizers Bundle](https://docs.sdv.dev/sdv/explore/sdv-bundles/xsynthesizers) page.
{% endhint %}

The XGCSynthesizer stands for *eXtraGaussianCopula.* It uses classic, statistical methods to train a model and generate synthetic data similar to the [GaussianCopulaSynthesizer](#gaussiancopulasynthesizer.load). However, it contains some additional features for higher quality modeling.

```python
from sdv.single_table import XGCSynthesizer

synthesizer = XGCSynthesizer(metadata)
synthesizer.fit(data)

synthetic_data = synthesizer.sample(num_rows=10)
```

## Creating a synthesizer

When creating your synthesizer, you are required to pass in a [Metadata](https://docs.sdv.dev/sdv/single-table-data/data-preparation/creating-metadata) object as the first argument. All other parameters are optional. You can include them to customize the synthesizer.

```python
synthesizer = XGCSynthesizer(
    metadata, # required
    enforce_min_max_values=True,
    enforce_rounding=False,
    numerical_distributions={
        'amenities_fee': 'beta',
        'checkin_date': 'scipy.stats.dweibull'
    },
    default_distribution='norm'
)
```

### Parameter Reference

**`enforce_min_max_values`**: Control whether the synthetic data should adhere to the same min/max boundaries set by the real data

<table data-header-hidden><thead><tr><th width="179"></th><th></th></tr></thead><tbody><tr><td>(default) <code>True</code></td><td>The synthetic data will contain numerical values that are within the ranges of the real data.</td></tr><tr><td><code>False</code></td><td>The synthetic data may contain numerical values that are less than or greater than the real data. </td></tr></tbody></table>

**`enforce_rounding`**: Control whether the synthetic data should have the same number of decimal digits as the real data

<table data-header-hidden><thead><tr><th width="179"></th><th></th></tr></thead><tbody><tr><td>(default) <code>True</code></td><td>The synthetic data will be rounded to the same number of decimal digits that were observed in the real data</td></tr><tr><td><code>False</code></td><td>The synthetic data may contain more decimal digits than were observed in the real data</td></tr></tbody></table>

**`locales`**: A list of locale strings. Any PII columns will correspond to the locales that you provide.

<table data-header-hidden><thead><tr><th width="218"></th><th></th></tr></thead><tbody><tr><td>(default) <code>['en_US']</code></td><td>Generate PII values in English corresponding to US-based concepts (eg. addresses, phone numbers, etc.)</td></tr><tr><td><code>&#x3C;list></code></td><td><p>Create data from the list of locales. Each locale string consists of a 2-character code for the language and 2-character code for the country, separated by an underscore.</p><p></p><p>For example <code>[</code><a href="https://faker.readthedocs.io/en/master/locales/en_US.html"><code>"en_US"</code></a><code>,</code> <a href="https://faker.readthedocs.io/en/master/locales/fr_CA.html"><code>"fr_CA"</code></a><code>]</code>. </p><p>For all options, see the <a href="https://faker.readthedocs.io/en/master/locales.html">Faker docs</a>.</p></td></tr></tbody></table>

**`numerical_distributions`**: Set the distribution shape of any numerical columns that appear in your table. Input this as a dictionary, where the key is the name of the numerical column and the values is a numerical distribution.

```python
numerical_distributions = {
    <column name>: 'norm',
    <column name>: 'uniform', 
    ...
}
```

<table data-header-hidden><thead><tr><th width="218"></th><th></th></tr></thead><tbody><tr><td>(default) <code>None</code></td><td>Use the default distribution for the column name.</td></tr><tr><td><code>&#x3C;dictionary></code></td><td>Apply the given distribution to each column name. The distribution name should be one of: <code>'norm'</code> <code>'beta'</code>, <code>'truncnorm'</code>, <code>'uniform'</code>, <code>'gamma'</code> or <code>'gaussian_kde'</code> </td></tr><tr><td><code>'scipy.stats'.&#x3C;distribution_name></code></td><td>Use a continuous distribution from the <a href="https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions">scipy library</a>. Make sure to provide the full path, including the prefix <code>scipy.stats.</code> — for example <code>'scipy.stats.dweibull'</code>  to refer to <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.dweibull.html#scipy.stats.dweibull">scipy's dweibull distribution</a>. </td></tr></tbody></table>

**`default_distribution`**: Set the distribution shape to use by default for all columns. Input this as a single string.

<table data-header-hidden><thead><tr><th width="204.0625"></th><th></th></tr></thead><tbody><tr><td>(default) <code>'beta'</code></td><td>Model the column as a beta distribution</td></tr><tr><td><code>&#x3C;distribution_name></code></td><td>Model the column as the given distribution. The distribution name should be one of: <code>'norm'</code> <code>'beta'</code>, <code>'truncnorm'</code>, <code>'uniform'</code>, <code>'gamma'</code> or <code>'gaussian_kde'</code> </td></tr><tr><td><code>'scipy.stats'.&#x3C;distribution_name></code></td><td>Use a continuous distribution from the <a href="https://docs.scipy.org/doc/scipy/reference/stats.html#continuous-distributions">scipy library</a>. Make sure to provide the full path, including the prefix <code>scipy.stats.</code> — for example <code>'scipy.stats.dweibull'</code>  to refer to <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.dweibull.html#scipy.stats.dweibull">scipy's dweibull distribution</a>. </td></tr></tbody></table>

{% hint style="warning" %}
Setting the distribution to `'gaussian_kde'` increases the time it takes to train your synthesizer.
{% endhint %}

### get\_parameters

Use this function to access the all parameters your synthesizer uses -- those you have provided as well as the default ones.

**Parameters** None

**Output** A dictionary with the parameter names and the values

```python
synthesizer.get_parameters()
```

```python
{
    'enforce_min_max_values': True,
    'enforce_rounding': False
    'default_distribution': 'beta',
    'numerical_distributions': {
        'amenities_fee': 'beta',
        'checkin_date': 'scipy.stats.dweibull'
    },
    ...
}
```

{% hint style="info" %}
The returned parameters are a copy. Changing them will not affect the synthesizer.
{% endhint %}

### get\_metadata

Use this function to access the metadata object that you have included for the synthesizer

**Parameters** None

**Output** A [Metadata](https://docs.sdv.dev/sdv/concepts/metadata) object

```python
metadata = synthesizer.get_metadata()
```

{% hint style="info" %}
The returned metadata is a copy. Changing it will not affect the synthesizer.
{% endhint %}

## Learning from your data

To learn a machine learning model based on your real data, use the `fit` method.

### fit

**Parameters**

* (required) `data`: A [pandas DataFrame](https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) object containing the real data that the machine learning model will learn from

**Output** (None)

```python
synthesizer.fit(data)
```

{% hint style="info" %}
**Technical Details:** This synthesizer uses Gaussian Copulas to learn the overall distribution of the real data. This happens in two stages:

1. Learning the distribution of each individual column, also known as the marginal distribution. For example a beta distribution with α=2 and β=5. The synthesizer uses the learned distribution to normalize the values, creating normal curves with µ=0 and σ=1.&#x20;
2. Learning the covariance of each pair of normalized columns. This is stored as an *n* x *n* matrix, where *n* is the number of columns in the table.

The [Synthetic Data Vault paper](https://dai.lids.mit.edu/wp-content/uploads/2018/03/SDV.pdf) has more information about the Gaussian normalization process and the Copula estimations.
{% endhint %}

### get\_learned\_distributions

After fitting this synthesizer, you can access the marginal distributions that were learned to estimate the shape of each column.

**Parameters** None

**Output** A dictionary that maps the name of each learned column to the distribution that estimates its shape

```python
synthesizer.get_learned_distributions()
```

```
{
    'amenities_fee': {
        'distribution': 'beta',
        'learned_parameters': { 'a': 2.22, 'b': 3.17, 'loc': 0.07, 'scale': 48.5 }
    },
    'checkin_date': { 
        'distribution': 'scipy.stats.dweibull',
        'learned_parameters': {...}
    },
    ...
}
```

For more information about the distributions and their parameters, visit the[ Copulas library](https://sdv.dev/Copulas/).

{% hint style="info" %}
Learned parameters are only available for parametric distributions. For eg. you will not be able to access learned distributions for the `'gaussian_kde'` technique.

In some cases, the synthesizer may not be able to fit the exact distribution shape you requested, so you may see another distribution shape as a fallback (eg. `'truncnorm'` instead of `'beta'`).
{% endhint %}

## Saving your synthesizer

Save your trained synthesizer for future use.

### save

Use this function to save your trained synthesizer as a Python pickle file.

**Parameters**

* (required) `filepath`: A string describing the filepath where you want to save your synthesizer. Make sure this ends in `.pkl`&#x20;

**Output** (None) The file will be saved at the desired location

```python
synthesizer.save(
    filepath='my_synthesizer.pkl'
)
```

### load (utility function)

Use this utility function to load a trained synthesizer from a Python pickle file. After loading your synthesizer, you'll be able to sample synthetic data from it.

**Parameters**

* (required) `filepath`: A string describing the filepath of your saved synthesizer

**Output** Your synthesizer object

```python
from sdv.utils import load_synthesizer

synthesizer = load_synthesizer(
    filepath='my_synthesizer.pkl'
)
```

*This utility function works for any SDV synthesizer.*

## What's next?

After training your synthesizer, you can now sample synthetic data. See the [Sampling](https://docs.sdv.dev/sdv/single-table-data/sampling) section for more details.

```python
synthetic_data = synthesizer.sample(num_rows=10)
```

{% hint style="info" %}
**Want to improve your synthesizer?** Input logical rules in the form of constraints, and customize the transformations used for pre- and post-processing the data.

For more details, see [Customizations](https://docs.sdv.dev/sdv/single-table-data/modeling/customizations).
{% endhint %}

## FAQs

<details>

<summary>What happens if columns don't contain numerical data?</summary>

This synthesizer models non-numerical columns, including columns with missing values.

Although the Gaussian Copula algorithm is designed for only numerical data, this synthesizer converts other data types using Reversible Data Transforms (RDTs). To access and modify the transformations, see [Advanced Features](https://docs.sdv.dev/sdv/single-table-data/modeling/customizations).

</details>

<details>

<summary>Why is <code>'beta'</code> the default distribution &#x26; when should I change it?</summary>

To create high quality synthetic data, the synthesizer should be able to match the shape of data for some optimal set of parameters. (The synthesizer learns and optimizes the parameters.)

We chose `'beta'` as the default distribution because it's capable of matching a variety of different shapes. It's also time efficient compared to other distributions like `'gaussian_kde'`.

**This default is not guaranteed to work on every dataset.** Consider changing the default distribution if all your columns have specific characteristics that you want to capture. If you have only a few columns that are highly important to match, then you can set those shapes specifically using the `numerical_distributions` parameter.

</details>

<details>

<summary>Can I call <code>fit</code> again even if I've previously fit some data?</summary>

Yes, even if you're previously fit data, you should be able to call the `fit` method again.

If you do this, the synthesizer will **start over from scratch** and fit the new data that you provide it. This is the equivalent of creating a new synthesizer and fitting it with new data.

</details>
