SDMetrics

repository·main·Indexed 42 days ago

https://github.com/sdv-dev/sdmetrics

A model-agnostic library for evaluating synthetic data by comparing it against real data. It provides metrics for assessing data quality and privacy across single columns, single tables, multi-table datasets, and time series, including high-level reports like QualityReport for visualization and insight generation.

Tokens
6.1K
Snippets
22
Records
30
Agent score
52%

What's inside SDMetrics

  1. Overview of Single Table Metrics

    main

    Single Table Metrics in sdmetrics operate on individual tables by comparing two pandas.DataFrame objects: the real_data and the synthetic_data. These metrics are categorized into several functional groups:

    • BayesianNetwork Metrics: Evaluates the likelihood of synthetic data being sampled from a distribution fitted to real data (e.g., BNLikelihood, BNLogLikelihood).
    • GaussianMixture Metrics: Uses Gaussian Mixture Models to evaluate likelihood (e.g., GMLogLikelihood).
    • Detection Metrics: Uses ML classifiers to distinguish between real and synthetic data; the score is the complement of the classifier's cross-validated score (e.g., LogisticDetection, SVCDetection).
    • ML Efficacy Metrics: Evaluates how well an ML model trained on synthetic data performs on real data. Warning: These require datasets representing ML problems and scores depend on problem difficulty (e.g., LinearRegression, MulticlassMLPClassifier, and the generic MLEfficacy).
    • Privacy Metrics: Evaluates the accuracy of an adversarial attacker model attempting to identify real data from synthetic data (e.g., CategoricalCAP, NumericalMLP, CategoricalEnsemble).
    • MultiSingleColumn Metrics: Applies a single-column metric to all compatible columns and returns the average (e.g., CSTest for categorical, KSComplement for numerical).
    • MultiColumnPairs Metrics: Applies a column-pair metric to all compatible pairs and returns the average (e.g., ContinuousKLDivergence, DiscreteKLDivergence).
  2. Use Multi Table Metrics to evaluate multi-table datasets

    main

    Multi Table Metrics in sdmetrics are designed to evaluate datasets consisting of multiple related tables. These metrics operate on two Python dictionaries, real_data and synthetic_data, where each dictionary maps table names to pandas.DataFrame objects.

    There are two main categories of multi-table metrics:

    1. Parent-Child Detection metrics: These de-normalize parent-child relationships in the dataset and then execute a Single Table Detection Metric on the resulting tables. Examples include LogisticParentChildDetection and SVCParentChildDetection.
    2. Multi Single Table Metrics: These execute a Single Table Metric on every table in the dataset and return the average score. Examples include CSTest, KSComplement, LogisticDetection, SVCDetection, BNLikelihood, and BNLogLikelihood.
  3. Use Time Series Metrics

    main

    Time series metrics in sdmetrics operate on individual tables representing sequential data. They are used to evaluate synthetic time series data by comparing it against real data.

    There are two main categories of implemented metrics:

    1. Detection Metrics: These train a Machine Learning Classifier (e.g., LSTMDetection using PyTorch) to distinguish between real and synthetic data. The score is the complement of the classifier's cross-validated score.
    2. ML Efficacy Metrics: These compare the performance of a model trained on synthetic data versus one trained on real data (e.g., LSTMClassifierEfficacy). The output is the ratio of the synthetic-trained model's score to the real-trained model's score.

    Warning: ML Efficacy metrics are only meaningful for datasets representing relatively easy machine learning problems. If real-data model performance is too low, the output may be meaningless.

  4. Understand Single Column Metrics

    main

    Single Column Metrics in sdmetrics operate on individual columns (univariate random variables). They compare two 1-dimensional arrays: one from the real dataset and one from the synthetic dataset.

    Currently implemented metrics include:

    • Statistical Metrics:
      • CSTest: A Chi-Squared test used to compare the distributions of two categorical columns.
      • KSComplement: The complement to the Kolmogorov-Smirnov statistic, used to compare the distributions of two numerical columns using their empirical CDF.
  5. Use Metadata to simplify Multi Table Metric computation

    main

    Instead of manually specifying foreign_keys, you can pass a metadata dictionary (following the SDV Metadata JSON schema) to the .compute() method.

    Using metadata is recommended because:

    1. It automatically provides relationship information (like foreign keys).
    2. It ensures column types are interpreted correctly (e.g., preventing categorical columns with integer values from being treated as numerical).
    3. It helps the metric identify compatible columns for evaluation.
    from sdmetrics.multi_table import LogisticParentChildDetection
    
    # metadata contains schema and relationship information
    score = LogisticParentChildDetection.compute(real_data, synthetic_data, metadata)
    print(score)
  6. Compute Time Series Metrics using Metadata

    main

    Instead of passing individual arguments like sequence_key or context_columns, you can pass a metadata dictionary. This dictionary must follow the SDV Metadata JSON schema.

    Using metadata is preferred because:

    1. It allows the metric to accurately identify column types (e.g., distinguishing categorical columns from numerical ones).
    2. It can automatically provide required information like the sequence_key.

    If metadata is not provided, it will be inferred from the real_data, but this may lead to inaccuracies in column type detection.

    from sdmetrics.timeseries import LSTMDetection
    from sdmetrics.demos import load_timeseries_demo
    
    real_data, synthetic_data, metadata = load_timeseries_demo()
    
    # Update metadata with the sequence key
    metadata['sequence_key'] = 'store_id'
    
    # Compute the metric using the metadata argument
    score = LSTMDetection.compute(real_data, synthetic_data, metadata=metadata)
    print(score)
  7. Get started with SDMetrics Reports

    main

    SDMetrics Reports allow you to generate insights, visualize data, and share results with your team. You can use the QualityReport for single-table data.

    To use the report:

    1. Load your real data, synthetic data, and metadata.
    2. Initialize a QualityReport.
    3. Call .generate(real_data, synthetic_data, metadata) to compute the report.

    Example using demo data:

    from sdmetrics import load_demo
    from sdmetrics.reports.single_table import QualityReport
    
    real_data, synthetic_data, metadata = load_demo(modality='single_table')
    
    my_report = QualityReport()
    my_report.generate(real_data, synthetic_data, metadata)
  8. Install SDMetrics from source

    main

    To install from source on Unix-based systems (GNU/Linux or macOS), clone the repository and run make install from the stable branch.

    git clone https://github.com/sdv-dev/SDMetrics
    cd SDMetrics
    git checkout stable
    make install
  9. Install SDMetrics for development

    main

    If you are contributing to the project or modifying the source code, install the package in development mode. It is recommended to create a new branch from main before running make install-develp.

    git clone git@github.com:sdv-dev/SDMetrics
    cd SDMetrics
    git checkout main
    git checkout -b <your-branch-name>
    make install-develp
  10. Compute a Single Table Metric

    main

    To compute a metric, call the .compute() method on the specific metric class. At a minimum, you must provide real_data and synthetic_data as pandas.DataFrame objects.

    Some metrics require additional arguments:

    • target: A string specifying the target column (required for ML Efficacy metrics).
    • metadata: A dictionary following the SDV Metadata JSON schema. While optional (it can be inferred from the data), providing it ensures correct type detection (e.g., distinguishing categorical integers from numerical ones) and allows passing extra info like the target column.
    from sdmetrics.single_table import LogisticDetection
    from sdmetrics import load_demo
    
    # Setup data
    real_data, synthetic_data, metadata = load_demo()
    real_table = real_data['users']
    synthetic_table = synthetic_data['users']
    
    # Basic usage
    score = LogisticDetection.compute(real_table, synthetic_table)
    
    # Usage with target and metadata for ML Efficacy
    from sdmetrics.single_table import MulticlassDecisionTreeClassifier
    
    # Option 1: Passing target directly
    score = MulticlassDecisionTreeClassifier.compute(real_table, synthetic_table, target='country')
    
    # Option 2: Passing target via metadata
    users_metadata = metadata['tables']['users'].copy()
    users_metadata['target'] = 'country'
    score = MulticlassDecisionTreeClassifier.compute(
        real_table, 
        synthetic_table, 
        metadata=users_metadata
    )