Overview
Before you model a table you need to know what is in each column. Profiling answers plain questions. How many different values does the column hold? How much of it is empty or zero? Does it match the types and ranges you were promised? The last question is the subtle one: does any single feature predict the target almost perfectly? That is usually target leakage, which means the feature contains information that would not exist at the moment you need to predict, such as a refund amount that is only filled in after a customer has left. The leakage screen here checks one feature at a time, so it finds blatant leaks and not ones spread over several features or hidden in time order.
A short history
Data profiling grew out of data quality work in databases and data warehouses in the 1990s, when teams loading many source systems needed to know column types, distinct counts and null rates before trusting a table. There is no single inventor. The leakage check is newer: Kaufman, Rosset and Perlich gave a formal treatment of target leakage in data mining in 2011, after several prediction contests were won by exploiting fields that would not exist at prediction time.
How it works
- Decide what counts as missing: None, NaN and the text tokens in missing_tokens such as an empty string or NA.
- Infer each column's stored type from its present values.
- Measure cardinality: the number of distinct values and its ratio to the number of present values. One distinct value means constant. A text column with a ratio above high_cardinality_ratio is identifier-like.
- Measure sparsity: the share of rows that are missing and the share that hold a numeric zero.
- Compare the table with an expected schema using check_schema, which lists every violation of type, nullability, range, allowed values or uniqueness.
- For each feature, predict the target by majority vote within each feature value and score how much accuracy that gains over always guessing the most common target.
- Flag features whose score reaches leakage_threshold, and skip identifier-like columns, which predict anything perfectly in sample without being a leak.
Watch out for
- A flag is a prompt to check how the column is produced, not proof of leakage. A legitimately strong feature can also score high.
- The screen looks at one feature at a time, so a leak that needs two columns combined, or one that comes from rows being ordered in time, passes unnoticed.
- Numeric features with many values are cut into n_bins equal-count bins first. A leak that lives in fine detail inside a bin can be blurred below the threshold.
- Missing values written as unusual text, such as a question mark or 999, are not in missing_tokens, so they are counted as real values and hide the true sparsity.
- A numeric identifier is not caught by the identifier rule, which applies only to text columns, so it is scored like any other feature.
Use cases
When to use it
When a dataset first arrives and again whenever its source changes: to drop constant and key columns, choose encodings by cardinality, catch schema drift, and question any feature that predicts the target suspiciously well.
In industry
- Banking
- Before a credit model is built, analysts profile the application table for missing income values, impossible dates and identifier columns that would let a model memorise customers.
- Data engineering
- Pipelines profile each new batch and compare null rates and distinct counts with the previous load, so a broken upstream export is caught before it reaches reports.
- Healthcare analytics
- A team predicting readmission checks for fields recorded after discharge, such as a follow up code, that would leak the outcome into the features.
Choosing it: what must hold
- A table you can read in full or sample fairly, with column names you can map to meanings.
- A stated target column if you want the leakage check to mean anything.
- Knowledge of when each field is recorded relative to the moment of prediction.
When to choose something else
| If | Use instead |
|---|---|
| You only need a quick overview of shape, types and basic statistics | Summary statistics |
| The schema is already validated and you want to study the shape of single columns | Distribution analysis |
| You need rules enforced on every future batch, not a one time look | A data validation step in the pipeline with explicit schema constraints |
Math foundations
Unique ratio
Close to 0 for a column with a few repeated categories and equal to 1 when every value is different. A text column with above the configured ratio is treated as a key, not a feature.
Base rate
The accuracy of always guessing the most common target value. Any feature must beat this to be informative at all.
Majority-vote accuracy
Within each feature value , guess the target value that occurs most often there. The sum counts the rows that guess gets right. This is the best a single feature can do on the data given.
Leakage score
The gain over the base rate, rescaled so that 0 means no better than guessing and 1 means the feature alone determines the target. For two numeric columns the template takes the larger of this and the absolute Pearson correlation.
Symbols
- unique ratio of a column
- number of rows where both the feature and the target are present
- number of those rows with target value t
- number of rows with feature value f and target value t
- base rate: accuracy of always guessing the most common target value
- accuracy of predicting the target from the feature by majority vote
- leakage score, from 0 to 1
Worked by hand
Five customers with a known plan. Plan and churned (1 means the customer left) are: free 0, pro 1, free 0, free 1, pro 1. So three customers churned and two did not.
The plan closes half the gap between guessing and perfect prediction. That is useful signal, and far below the 0.95 threshold, so it is not flagged.
Visual example
Loading the example.
Try this
- Click Leakage screen, then lower the leak slider from 1 to 0.5 and watch refund_issued fall back under the 0.95 line.
- Raise the share of missing plan values and click Sparsity, then Schema check, to see the same gap reported twice.
- Switch on the wrongly stored value and click Column types: one word turns a whole numeric column into text.
Code sample
from impl import DataProfiler
from config import DataProfilerConfig
table = {
"id": ["u1", "u2", "u3", "u4", "u5", "u6"],
"plan": ["free", "pro", "free", None, "free", "pro"],
"refund": [0.0, 25.0, 0.0, 0.0, 25.0, 25.0], # only paid out after a customer has churned
"churned": [0, 1, 0, 0, 1, 1],
}
profiler = DataProfiler(DataProfilerConfig(leakage_threshold=0.95))
print(profiler.profile(table)["plan"])
schema = {"id": "str", "plan": {"type": "str", "nullable": False}, "refund": "float", "churned": "int"}
print(profiler.check_schema(table, schema)) # ['plan: 1 missing values in a non-nullable column']
print(profiler.leakage(table, "churned")["flagged"]) # ['refund']; "id" is skipped as identifier-likeRead the implementation (206 lines)
"""Data profiling: cardinality, sparsity, schema checks and target leakage detection.
NumPy and the standard library only. A table is a dict {column name: sequence of values}, all of the same length.
Values may be numbers, text, booleans or missing (None, NaN, or one of config.missing_tokens).
"""
from __future__ import annotations
import math
from collections import Counter, defaultdict
import numpy as np
try:
from .config import DataProfilerConfig
except ImportError: # run from the template's own folder
from config import DataProfilerConfig
TYPES = ("bool", "int", "float", "str", "empty")
class DataProfiler:
"""Profiles the columns of a table held as a dict of sequences."""
def __init__(self, config: DataProfilerConfig | None = None) -> None:
self.config = config or DataProfilerConfig()
# ---- helpers -------------------------------------------------------------------------------------------
def is_missing(self, value) -> bool:
"""True for None, NaN and the text tokens listed in config.missing_tokens."""
if value is None:
return True
if isinstance(value, (float, np.floating)) and math.isnan(value):
return True
return isinstance(value, str) and value.strip() in self.config.missing_tokens
@staticmethod
def _plain(value):
return value.item() if isinstance(value, np.generic) else value
def _present(self, values) -> list:
return [self._plain(v) for v in values if not self.is_missing(v)]
@staticmethod
def _check_lengths(columns: dict) -> int:
lengths = {len(v) for v in columns.values()}
if len(lengths) != 1:
raise ValueError(f"columns must all have the same length, got lengths {sorted(lengths)}")
return lengths.pop()
def infer_type(self, values) -> str:
""""bool", "int", "float", "str" or "empty" (nothing but missing values), judged on the present values.
Whole-number floats count as "float": the stored type is reported, not what it could be narrowed to.
"""
present = self._present(values)
if not present:
return "empty"
if all(isinstance(v, bool) for v in present):
return "bool"
if all(isinstance(v, int) and not isinstance(v, bool) for v in present):
return "int"
if all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in present):
return "float"
return "str"
# ---- cardinality and sparsity --------------------------------------------------------------------------
def cardinality(self, columns: dict) -> dict:
"""Distinct-value profile of every column.
Returns {column: {"n_unique", "unique_ratio", "is_constant", "is_identifier_like"}}. unique_ratio is
n_unique divided by the number of present values. A non-numeric column with unique_ratio above
config.high_cardinality_ratio is identifier-like (a key, not a feature).
"""
self._check_lengths(columns)
out = {}
for name, values in columns.items():
present = self._present(values)
n_unique = len(set(present))
ratio = n_unique / len(present) if present else 0.0
textual = self.infer_type(values) == "str"
out[name] = {
"n_unique": n_unique,
"unique_ratio": ratio,
"is_constant": n_unique <= 1,
"is_identifier_like": bool(textual and len(present) > 1 and ratio > self.config.high_cardinality_ratio),
}
return out
def sparsity(self, columns: dict) -> dict:
"""Emptiness of every column.
Returns {column: {"missing_fraction", "zero_fraction"}}: the share of rows that are missing, and the
share of rows that hold a numeric zero.
"""
n = self._check_lengths(columns)
out = {}
for name, values in columns.items():
missing = sum(1 for v in values if self.is_missing(v))
zeros = sum(1 for v in self._present(values) if isinstance(v, (int, float)) and not isinstance(v, bool) and v == 0)
out[name] = {"missing_fraction": missing / n if n else 0.0, "zero_fraction": zeros / n if n else 0.0}
return out
# ---- schema --------------------------------------------------------------------------------------------
def check_schema(self, columns: dict, schema: dict) -> list[str]:
"""Compare a table with its expected schema and list every violation (an empty list means it conforms).
schema: {column: rule}; a rule is a type name ("bool", "int", "float", "str") or a dict with any of
"type", "nullable" (default True), "min", "max", "allowed" (collection of permitted values) and
"unique" (default False). An "int" column satisfies a "float" rule.
"""
self._check_lengths(columns)
problems = [f"missing column: {name}" for name in schema if name not in columns]
problems += [f"unexpected column: {name}" for name in columns if name not in schema]
for name, rule in schema.items():
if name not in columns:
continue
rule = {"type": rule} if isinstance(rule, str) else dict(rule)
present = self._present(columns[name])
found = self.infer_type(columns[name])
wanted = rule.get("type")
if wanted is not None and found != "empty" and found != wanted and not (wanted == "float" and found == "int"):
problems.append(f"{name}: expected type {wanted}, found {found}")
n_missing = len(columns[name]) - len(present)
if not rule.get("nullable", True) and n_missing:
problems.append(f"{name}: {n_missing} missing values in a non-nullable column")
numbers = [v for v in present if isinstance(v, (int, float)) and not isinstance(v, bool)]
if "min" in rule and any(v < rule["min"] for v in numbers):
problems.append(f"{name}: {sum(v < rule['min'] for v in numbers)} values below min {rule['min']}")
if "max" in rule and any(v > rule["max"] for v in numbers):
problems.append(f"{name}: {sum(v > rule['max'] for v in numbers)} values above max {rule['max']}")
if "allowed" in rule:
bad = sorted({str(v) for v in present if v not in rule["allowed"]})
if bad:
problems.append(f"{name}: values outside the allowed set: {bad}")
if rule.get("unique", False) and len(set(present)) != len(present):
problems.append(f"{name}: {len(present) - len(set(present))} duplicate values in a unique column")
return problems
# ---- target leakage ------------------------------------------------------------------------------------
def _as_categories(self, values) -> list:
"""One hashable category per row; None for missing. Numeric columns with many values are quantile-binned."""
plain = [None if self.is_missing(v) else self._plain(v) for v in values]
present = [v for v in plain if v is not None]
numeric = self.infer_type(values) in ("int", "float")
if not numeric or len(set(present)) <= self.config.n_bins:
return plain
edges = np.unique(np.quantile(np.array(present, dtype=float), np.linspace(0, 1, self.config.n_bins + 1)[1:-1]))
return [None if v is None else int(np.searchsorted(edges, v, side="right")) for v in plain]
def leakage_score(self, feature, target) -> float:
"""How completely a single feature gives the target away, from 0 (no better than guessing) to 1.
feature, target: sequences of length n. The score is the larger of
(a) the gain in accuracy when the target category is predicted from the feature category by majority
vote, scaled so the base rate is 0 and perfect prediction is 1, and
(b) for two numeric columns, the absolute Pearson correlation.
Numeric columns with more than config.n_bins distinct values are cut into equal-count bins for (a).
Rows where either side is missing are skipped.
"""
if len(feature) != len(target):
raise ValueError("feature and target must have the same length")
pairs = [(f, t) for f, t in zip(self._as_categories(feature), self._as_categories(target)) if f is not None and t is not None]
if not pairs:
return 0.0
target_counts = Counter(t for _, t in pairs)
base = max(target_counts.values()) / len(pairs)
if base >= 1.0:
raise ValueError("the target is constant, so nothing can leak it")
by_feature: dict = defaultdict(Counter)
for f, t in pairs:
by_feature[f][t] += 1
accuracy = sum(max(c.values()) for c in by_feature.values()) / len(pairs)
score = (accuracy - base) / (1.0 - base)
if self.infer_type(feature) in ("int", "float") and self.infer_type(target) in ("int", "float"):
rows = [(self._plain(f), self._plain(t)) for f, t in zip(feature, target) if not self.is_missing(f) and not self.is_missing(t)]
x, y = np.array(rows, dtype=float).T
if x.std() > 0 and y.std() > 0:
score = max(score, abs(float(np.corrcoef(x, y)[0, 1])))
return float(score)
def leakage(self, columns: dict, target: str) -> dict:
"""Screen every feature for target leakage.
Returns {"scores": {feature: score}, "flagged": [features with score >= config.leakage_threshold],
"skipped": [identifier-like features]}. Identifier-like columns are skipped because a unique key
"predicts" any target perfectly in sample without being a leak. A flag means "look at how this column
is produced", not proof: a feature recorded after the outcome is the usual cause.
"""
if target not in columns:
raise KeyError(f"target column {target!r} is not in the table")
cardinality = self.cardinality(columns)
scores, skipped = {}, []
for name, values in columns.items():
if name == target:
continue
if cardinality[name]["is_identifier_like"]:
skipped.append(name)
continue
scores[name] = self.leakage_score(values, columns[target])
flagged = sorted((n for n, s in scores.items() if s >= self.config.leakage_threshold), key=lambda n: -scores[n])
return {"scores": scores, "flagged": flagged, "skipped": skipped}
def profile(self, columns: dict) -> dict:
"""Everything about every column: {column: {"type", cardinality fields..., sparsity fields...}}."""
cardinality, sparsity = self.cardinality(columns), self.sparsity(columns)
return {name: {"type": self.infer_type(columns[name]), **cardinality[name], **sparsity[name]} for name in columns}- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 9, run with
python3 -m unittest -v
Practice
Build the six-row table from the template's README with the columns id, plan, refund and churned. Call DataProfiler().profile on it and read the cardinality and sparsity of each column. Then call leakage with churned as the target, confirm that refund is flagged and id is skipped, and work out the score of refund by hand.
Check on learning
- A unique id column predicts the target perfectly by majority vote. Why is that not leakage, and why would a model trained on it still fail?
A way to think about it
Each id appears once, so the vote within each value is trivially right. Ask what the model can do with an id it has never seen.
- The score divides by . What would go wrong if you compared raw accuracy across two targets, one balanced and one where 95 percent of rows share a value?
A way to think about it
Compute for a useless feature on each target. The rescaling exists so that useless always means 0.
- A feature scores 0.97 against the target. What questions about how and when the column is recorded would tell you whether it is a leak or a strong legitimate predictor?
A way to think about it
Think about the moment a prediction is needed. Would this value already exist then, for a brand new case, with the same meaning?
- Why is the leakage score computed on the data it is given optimistic, especially for a feature with many distinct values?
A way to think about it
The majority vote is fitted and scored on the same rows. Consider what happens to as the number of rows per feature value falls towards one.
- A column is 60 percent zeros and 0 percent missing. What different stories about the data could produce that, and how would you tell them apart?
A way to think about it
Zero can be a real measurement, a default written by the source system, or a stand-in for unknown. Look at whether the zeros line up with another column or a date.