Faker Synthesizer
ydata.synthesizers.FakerSynthesizer
A synthesizer for generating synthetic data based on user-defined configurations.
The FakerSynthesizer allows users to create synthetic tabular data without needing
an existing dataset. Instead, it generates data based on user-provided metadata
or manually defined column configurations. This approach is useful for:
- Creating mock datasets for testing and development.
- Generating data prototypes before real data is available.
- Ensuring privacy-preserving synthetic data without reference to actual records.
Key Features:
- Metadata-Driven Generation: Generates synthetic data based on predefined Metadata.
- Customizable Column Types: Supports user-defined column structures.
- Multi-Language Support: Uses locale settings to generate realistic names, addresses, etc.
Example Usage:
from ydata.synthesizers import FakerSynthesizer
# Initialize the synthesizer with a specific locale
faker_synth = FakerSynthesizer(locale="en") # English data generation
faker_synth.fit(metadata)
# Generate synthetic data
synthetic_data = faker_synth.sample(n_samples=1000)
fit(metadata=None, calculated_features=None, scaffold=None, reference_data=None, distributions=None, conditions=None, sequence=None, totals=None, derived_tables=None, table_name='data', errors=None, timeseries=None, *, tables=None, existing_data=None, anchor_tables=None, pool_size=5000)
Configure the FakerSynthesizer using provided metadata.
This method sets up the synthesizer by defining the structure of the synthetic
dataset based on the given Metadata. The metadata can either be:
- Computed: Automatically extracted from an existing dataset.
- User-Defined: Manually constructed to specify custom column types and distributions.
Once fit() is called, the synthesizer will use this metadata to generate
structured synthetic data that adheres to the defined schema.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
Metadata | None
|
A metadata object describing the structure of the synthetic dataset, including: - Column names and data types. - Faker-based data generators (e.g., names, addresses, emails). - Value constraints (e.g., numeric ranges, categorical options). |
None
|
calculated_features
|
list[dict] | None
|
Optional. Columns computed deterministically from other
columns AFTER sampling — exact identities, sign rules, derived flags.
Same single-table convention as :class: Features are applied in list order (later features may consume earlier
outputs) and are excluded from generation. Cross-table |
None
|
scaffold
|
dict | ScaffoldConfig | None
|
Optional. A declarative structural grid
(:class: |
None
|
reference_data
|
dict[str, DataFrame] | None
|
Optional. Named DataFrames backing the scaffold's
|
None
|
distributions
|
dict[str, dict] | None
|
Optional. Per-column distribution overrides for numerical columns (default: uniform within the declared domain). Pure data, so it can also live in the YAML configuration:: Supported: uniform, normal, lognormal, exponential, poisson,
triangular, beta. |
None
|
conditions
|
list[dict] | None
|
Optional. Conditional generation rules: a column's values are
sampled per segment defined by
|
None
|
sequence
|
dict | None
|
Optional. Declares row ordering for temporal semantics:: The output is stably sorted by |
None
|
totals
|
list[dict] | None
|
Optional. Per-group figures the generated data must meet — a
ceiling ( Applied after calculated features and before derived tables, so aggregates reconcile to the adjusted detail. List every column of a co-dependent family together so their identities survive the rescale. |
None
|
derived_tables
|
list[dict] | None
|
Optional. Additional tables computed deterministically FROM the generated table after everything else — aggregates reconcile to the detail by construction:: Supported aggregations: sum, mean, min, max, count, nunique,
first, last (first/last require a |
None
|
table_name
|
str
|
Name of the base generated table in the |
'data'
|
errors
|
dict | None
|
Optional. Deterministic error injection, applied as the VERY
LAST stage — after calculated features and derived tables, so
identities and aggregates are computed on clean data and the
errors land only in the delivered output. Keyed by table name
(base table under Column operators: |
None
|
timeseries
|
dict | TimeSeriesConfig | None
|
Optional. How columns move through time; requires a
In a schema, |
None
|
Schema mode — keyword-only arguments:
tables: a :class:~ydata.synthesizers.faker.schema.FakerSchema, or a
YAML path / dict that :func:~ydata.synthesizers.faker.config.load_faker_schema
reads: a database under a top-level tables: key, or a single
table (columns plus its blocks). Each table declares its
single-table blocks (columns, scaffold, distributions,
conditions, sequence, totals, derived_tables,
errors) and, when relational, primary_key, key_format,
foreign_keys (cardinality, where, unique,
context_columns) and table_errors. Mutually exclusive with
metadata and with the single-table keyword arguments above,
except reference_data for a single table's scaffold. A plain
single table is generated exactly as with metadata, and its
calculated features may name columns bare; otherwise they use
table.column addressing, and cross-table features declare
reference_keys. One table -> sample() returns a Dataset (a
dict when it has derived tables); several -> a MultiDataset.
existing_data: supplied tables (rows kept, keys never rewritten; missing
schema columns are generated). Parents they reference are seeded
from their foreign key values.
anchor_tables: supplied tables that must carry a unique primary key.
pool_size: provider/characteristic/regex string columns are drawn from a
pool of this many generated values (fast at volume). A positive
integer, or None to generate every value individually.
load(path)
classmethod
Load a FakerSynthesizer previously saved with save().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str
|
Path to the file written by |
required |
Returns:
| Name | Type | Description |
|---|---|---|
FakerSynthesizer |
The restored synthesizer, ready to call |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If the file does not contain a FakerSynthesizer. |
sample(sample_size=1000, random_state=None)
Generate a synthetic dataset based on the configured metadata.
This method produces synthetic data according to the schema defined in the
fit() step. The generated data adheres to the column types, constraints,
and distributions specified in the provided Metadata.
When a scaffold was configured in fit(), the scaffold grid defines
both the structural columns (emitted verbatim) and the row count —
sample_size is then ignored. Calculated features configured in fit()
are computed after sampling, in list order, and are never generated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_size
|
int | dict[str, int]
|
The number of synthetic records/rows to
generate. Defaults to |
1000
|
random_state
|
int | None
|
Seed for reproducible sampling. Seeds NumPy,
Python's |
None
|
Sets error_labels_: one row per error injected by this sample
(schema mode: table, row, pk_value, column, error_type, original_value,
injected_value; single-table mode: the same without pk_value), or None
when no errors are configured. Reset by every fit().
Returns:
| Type | Description |
|---|---|
Dataset | MultiDataset
|
Dataset | MultiDataset: a Dataset when one table is generated, a
MultiDataset when several are (several schema tables, or derived
tables — the base table under |
save(path)
Saves the SYNTHESIZER and the model fitted per variable.
Schema
ydata.synthesizers.faker.config.load_faker_schema(source, table_name=DEFAULT_TABLE_NAME)
Load a FakerSynthesizer configuration from a YAML file or a dict.
Accepted forms
- a database: a top-level
tables:key mapping table names to table blocks (or that mapping directly, every value with acolumnskey); - a single table:
columnsplus the optional blocksscaffold,distributions,conditions,sequence,totals,derived_tablesanderrors. Without acolumnskey, every top-level entry is a column (flat form). It loads as a one-table schema namedtable_name.
Deep validation (column configurations, conditions, ...) happens at fit().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | dict
|
path to a YAML file, or an already-loaded configuration dict. |
required |
table_name
|
str
|
name of the table when the configuration is a single table.
Default |
DEFAULT_TABLE_NAME
|
Returns:
| Name | Type | Description |
|---|---|---|
FakerSchema |
FakerSchema
|
pass it to |
Raises:
| Type | Description |
|---|---|
SynthesizerValueError
|
if the file cannot be parsed or the configuration is invalid. |
ydata.synthesizers.faker.config.faker_schema_from_llm(tables)
Start a Faker configuration from an LLM synthesizer schema.
For the Faker use case when there is only the idea of a schema: an LLM schema
(LLMSynthesizer.fit's tables, or generate_schema's output from a
plain-English description) describes tables, keys and columns in prose; this
turns it into a :class:FakerSchema skeleton to start the Faker configuration
from. Tables, primary
keys, foreign keys, scaffolds and table errors are copied; dtypes become
datatype/vartype; values become uniform categories; prompts
become description.
What the LLM schema cannot say — numerical ranges, date ranges and formats —
is left for you: :meth:FakerSchema.gaps lists it per column. Fill it in
(typically on the YAML from :meth:FakerSchema.to_yaml, adding distributions,
conditions or cardinalities as needed), then fit(tables=...)::
schema = faker_schema_from_llm(llm_tables)
schema.gaps() # {"customers": {"age": ["min", "max"]}}
schema.to_yaml("customers.yaml")
# ... edit customers.yaml ...
FakerSynthesizer().fit(tables="customers.yaml")
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tables
|
dict
|
the LLM schema, table name -> |
required |
Returns:
| Name | Type | Description |
|---|---|---|
FakerSchema |
FakerSchema
|
the skeleton; |
Raises:
| Type | Description |
|---|---|
SynthesizerValueError
|
if the LLM schema cannot be converted. |
ydata.synthesizers.faker.schema.FakerSchema
Bases: RootModel[dict[str, FakerTableSchema]]
A multi-table Faker schema: table name -> :class:FakerTableSchema.
is_single_table
property
One table and nothing relational (keys, key format, foreign keys, table errors, Faker providers, helper columns): exactly what a single-table FakerSynthesizer generates, and generated by it.
context_path(table, fk_column, path)
Resolve a context path requested on table.fk_column.
Returns the lookups, in order, as (table, column): the column is read from that table by its primary key. All but the last are foreign keys.
from_any(source, table_name='data')
classmethod
Build from a FakerSchema, or anything :func:load_faker_schema reads: a
YAML path or a dict, for a database (tables:) or a single table (a
one-table schema named table_name).
from_llm_schema(tables)
classmethod
Convert an LLMSynthesizer schema into a Faker schema skeleton.
Tables, primary keys, foreign keys, scaffolds and table errors are copied;
dtypes are mapped; values become uniform categories; prompts move to
description. Columns that still need configuration (numerical
min/max, date ranges) are returned as gaps — fill them in before
fit(), which validates every non-key column.
Prefer :func:~ydata.synthesizers.faker.config.faker_schema_from_llm, which
returns the schema alone; :meth:gaps then says which options each
column still needs.
Returns:
| Type | Description |
|---|---|
(schema, gaps)
|
gaps maps table name to the columns needing configuration
(the keys of :meth: |
gaps()
The generation options each column still needs before fit().
Per datatype: numerical min/max (not with a characteristic),
date min/max/format, categorical categories, longtext
text_length. Primary and foreign key columns and scaffold columns are
structural and never listed. Useful on a skeleton (see
:func:~ydata.synthesizers.faker.config.faker_schema_from_llm) and after
editing a configuration.
Returns:
| Type | Description |
|---|---|
dict[str, dict[str, list[str]]]
|
|
to_dict()
This schema as the configuration :func:load_faker_schema reads.
Always the database form ({"tables": {...}}), so table names are
kept; a one-table schema loads back as the same single table. Values keep
their Python types (integer or boolean category keys stay integers or
booleans), so the dict round-trips exactly; the seasonality key on,
which YAML 1.1 reads as True, is written back as "on".
to_yaml(path=None)
This schema as a YAML configuration (see :meth:to_dict).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | None
|
optional file to write; the YAML text is returned either way. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
the YAML text, loadable with :func: |
ydata.synthesizers.faker.schema.FakerTableSchema
Bases: BaseModel
One table of a multi-table Faker schema.
key_columns
property
The primary key as a list of columns (empty without a key).
single_key
property
The primary key when it is one column, else None.
context_aliases()
Aliases under which the requested parent context is available.
Every context_columns entry (a path, see the module docstring) is
available as <fk column>.<path>. A one-hop entry is also available as
<Parent>.<column> when it is the only foreign key to that parent
requesting the column.
Returns:
| Type | Description |
|---|---|
(aliases, ambiguous)
|
alias -> (fk column, path); and each short |
dict[str, list[str]]
|
|
tuple[dict[str, tuple[str, str]], dict[str, list[str]]]
|
foreign keys (not provided: it does not say which one is meant). |
timeseries()
The table's time behaviour, shape-validated; checked against the table's columns when the synthesizer is fitted.