skip to content

Data Validation Libraries

TFDV checks serving statistics against an inferred schema and training data, Deequ runs constraints on Spark, and a GX checkpoint can gate a retrain. Interviewers ask which check stops bad data first.

on this pageshow

explore

questions

6

With TensorFlow Data Validation (TFDV), what do `generate_statistics_from_tfrecord`, `infer_schema` and `validate_statistics` each produce when you check a training batch?

level: juniorimportance: must knowfreq 12%

answer

  1. three steps, three protocol buffers
  2. summaries, not rows
  3. the schema is a draft to review
  4. a map keyed by feature name
  5. returned, never raised

basics

~10 s

generate_statistics_from_tfrecord returns a DatasetFeatureStatisticsList summarising each feature; infer_schema turns those statistics into a draft Schema you review; validate_statistics checks a later batch's statistics against it and returns an Anomalies proto, empty when clean.

solid answer

~40 s

TFDV works on summaries, not rows. `tfdv.generate_statistics_from_tfrecord(data_location=...)` (or the `_from_csv` and `_from_dataframe` variants) runs an Apache Beam pipeline and returns a `DatasetFeatureStatisticsList`: per-feature counts, missing values, value counts and histograms. `tfdv.infer_schema(stats)` derives a `Schema` proto from them (expected features, types, presence, value counts, string domains), and the TFDV docs tell you to review and refine it because the inference is heuristic. `tfdv.validate_statistics(statistics=new_stats, schema=schema)` compares a later batch's statistics with that schema and returns an `Anomalies` proto whose `anomaly_info` map is keyed by feature; an empty map means nothing disagreed. It returns rather than raises, so the pipeline step has to inspect the result and fail itself.

go deeper

for a junior

Recall the three calls in order and the object each returns: statistics, schema, anomalies. Say that an empty anomalies result means the batch matched the schema.

for a middle

Explain that validation runs on aggregate statistics, that inference uses heuristics such as the 100-value string-domain limit, and that the step must check the returned Anomalies itself.

for a senior

Show you would review and version the schema, wire the anomaly check so it fails the pipeline step, and reach for per-example validation only when you need the offending rows.

for a principal

Frame the schema as the team's written agreement on what correct input is: who may change it, how changes are reviewed, and how many pipelines share one copy.

## What TFDV works on TensorFlow Data Validation (**TFDV**) does not check a training batch row by row unless you ask it to. It first reduces the data to **statistics**, then compares those statistics with a **schema** (a description of what correct data looks like) and reports **anomalies**. Each step has its own call and its own protocol-buffer result, and keeping the three apart is most of what this question probes. | Step | Call | Returns | Holds | |---|---|---|---| | Summarise | `tfdv.generate_statistics_from_tfrecord(data_location=...)` | `DatasetFeatureStatisticsList` | per-feature counts, missing values, value counts, histograms | | Describe | `tfdv.infer_schema(statistics)` | `Schema` | expected features, types, presence, value counts, domains | | Check | `tfdv.validate_statistics(statistics=..., schema=...)` | `Anomalies` | an entry for each feature that disagrees with the schema | ## Computing statistics - `generate_statistics_from_tfrecord` reads `TFRecord` files of `tf.train.Example` records; `generate_statistics_from_csv` reads CSV; `generate_statistics_from_dataframe` takes an in-memory pandas DataFrame. - Underneath, TFDV runs an **Apache Beam** pipeline, so the same call scales from a laptop to a distributed Beam runner. The docs note that a remote run must be given an `output_path` for the statistics. - The result is a compact summary, not the rows. It can be visualised with `tfdv.visualize_statistics`, saved, and compared with another day's statistics later. ## Inferring the schema: a draft, not a verdict `tfdv.infer_schema(stats)` reads the statistics and writes a `Schema` proto: which features should be present, their type, how many values each example carries, how often a feature must be present, and the domain of string features. Two defaults matter: - `infer_feature_shape=True`: a required feature whose minimum and maximum value counts are equal is given a fixed shape; - `max_string_domain_size=100`: the largest number of distinct values a string feature may have and still be treated as categorical. The TFDV guide describes its inference as **conservative heuristics** and strongly advises you to **review the inferred schema and refine it**, adding the domain knowledge the heuristics missed. The schema is an ordinary protobuf, so you edit it directly, for example `tfdv.get_feature(schema, 'ad_slot').presence.min_fraction = 0.99`, store it as text with `tfdv.write_schema_text(schema, output_path)`, and load it back with `tfdv.load_schema_text(input_path)`. ## Validating a new batch A later batch is checked by computing its statistics and passing them with the schema: ```python import tensorflow_data_validation as tfdv schema = tfdv.load_schema_text(schema_path) new_stats = tfdv.generate_statistics_from_tfrecord(data_location=batch_path) anomalies = tfdv.validate_statistics(statistics=new_stats, schema=schema) if anomalies.anomaly_info or anomalies.HasField("dataset_anomaly_info"): tfdv.display_anomalies(anomalies) raise RuntimeError("TFDV found anomalies; stopping this step") ``` - The returned `Anomalies` proto carries an `anomaly_info` map keyed by feature, each entry with a short and a long description: "Unexpected string values", for instance, when a categorical feature holds a value missing from its domain. A separate `dataset_anomaly_info` field exists for findings about the dataset as a whole. - An **empty** result means the statistics agreed with the schema, nothing more: it says the batch fits the description, not that the description is right. - When an anomaly reflects a legitimate change, you update the schema (for a new category, `tfdv.get_domain(schema, 'ad_slot').value.append(...)`). When it reflects a data error, the docs say to fix the data before training. ## Reading the anomalies you will meet first Each anomaly names a type, and a handful account for most first encounters in a training pipeline: | Anomaly type | What it means | |---|---| | `SCHEMA_NEW_COLUMN` | a feature is in the statistics but not in the schema | | `SCHEMA_MISSING_COLUMN` | a feature the schema requires is absent from the statistics | | `FEATURE_TYPE_LOW_FRACTION_PRESENT` | a feature is filled in fewer examples than `presence.min_fraction` requires | | `ENUM_TYPE_UNEXPECTED_STRING_VALUES` | a categorical feature holds values outside its domain | | `FLOAT_TYPE_HAS_NAN` | a float feature contains NaN while its domain sets `disallow_nan` | Each entry says which schema field the statistics broke, so the fix is either that field or the data. ## Three things it does not do on its own 1. **It does not raise on bad data.** `validate_statistics` returns the anomalies; it raises only for malformed inputs such as the wrong argument types. The pipeline step has to inspect the result and fail, as the snippet does. 2. **It does not compare two datasets' distributions** unless you pass `previous_statistics` or `serving_statistics` and configure comparators on the features in the schema. 3. **It does not name the bad rows.** For that, `tfdv.validate_examples_in_tfrecord(data_location=..., stats_options=tfdv.StatsOptions(schema=schema))` validates example by example and returns statistics over the anomalous examples, grouped by the anomaly they show. Remembering the three objects (statistics, schema, anomalies) and which call turns one into the next is enough to read any TFDV pipeline step and see where a check would go wrong.

  • Why does TFDV validate statistics rather than every row by default?
    One Beam pass reduces the dataset to a compact `DatasetFeatureStatisticsList`, and checking that summary against the schema is cheap however large the data was. The same statistics can be visualised and compared with another day's. When you need the offending examples, `tfdv.validate_examples_in_tfrecord` with `tfdv.StatsOptions(schema=schema)` validates per example and returns statistics over the anomalous ones.
  • An anomaly reports a categorical value that is missing from the schema's domain. What are your two options?
    If the value is legitimate, extend the domain, for example `tfdv.get_domain(schema, 'ad_slot').value.append('native_feed')`, save the schema and re-run. If it is a data error, fix the data before training. The TFDV guide gives both paths; which one applies is a judgement about the data, not something the library decides.
  • How do you keep the reviewed schema between pipeline runs?
    Write it as text with `tfdv.write_schema_text(schema, output_path)`, keep the file with the pipeline code, and load it in each run with `tfdv.load_schema_text(input_path)`. Storing it as text means a schema change shows up as a readable diff in review.

  • validate_statistics raises an exception as soon as a batch breaks the schema
  • TFDV checks every row against the schema by default
  • The schema infer_schema returns is final and needs no review
  • infer_schema reads the raw TFRecord files rather than computed statistics
  • An empty Anomalies result proves the data is good enough to train on
open as a page

In Deequ, how do a `VerificationSuite`'s Error-level and Warning-level checks decide the run's status, and does `run()` fail the Spark job?

level: middleimportance: should knowfreq 10%

basics

~20 s

A failing Check reports Error or Warning according to its CheckLevel, and the VerificationResult status is the worst status across checks. run() only returns that result, so the job must test the status and fail itself.

open as a page

In TFDV, when is a feature's `skew_comparator` evaluated versus its `drift_comparator`, and why can an `infinity_norm` threshold miss a numeric feature?

level: middleimportance: should knowfreq 8%

basics

~20 s

The skew_comparator runs only when validate_statistics receives serving_statistics (training against serving); the drift_comparator only when it receives previous_statistics (current against an earlier batch). An infinity_norm threshold reads categorical value counts, so numeric features need jensen_shannon_divergence.

open as a page

How would you choose between TFDV, Deequ and a Great Expectations checkpoint to gate a daily click-through retrain fed by TFRecords and a PySpark feature job?

level: seniorimportance: should knowfreq 7%

basics

~20 s

Match each input to the library that already fits its engine and owner: TFDV beside the TFRecord trainer, Deequ inside the Spark feature job, a GX checkpoint where expectation suites exist. Whichever runs, the step must test its result and fail.

open as a page

A daily click-through model's TFDV step re-infers the schema from each day's data before validating; after a tracking change emptied one feature, why did nothing fire?

level: seniorimportance: should knowfreq 6%

basics

~20 s

Re-inferring makes the schema describe the broken batch itself, so validation compares the data with a copy of its own shape. Freeze a reviewed schema under version control, load it each run, and change it only through review.

open as a page

A PySpark feature job adds a Deequ anomaly check on a feature's `Completeness`, yet a sharp completeness drop never stopped training; what is the likely cause?

level: seniorimportance: nice to knowfreq 4%

basics

~20 s

Deequ's addAnomalyCheck defaults to CheckLevel.Warning, so a detected drop only makes the run's status Warning, which a gate failing on Error ignores. PyDeequ 1.7.0 cannot pass an AnomalyCheckConfig, so the gate must treat that check's Warning as blocking.

open as a page