Algorithm Search⌘K

Algorithmresearch

HoloClean probabilistic repair

Also called HoloClean.

Repair data by compiling constraints, value statistics and external data into one probabilistic model, learning its weights on clean cells and inferring the most likely value of each noisy cell.

Time
O(n^2 a v q p + e n a v (a + q)) worst
Space
O(n a (a + v (a + q))) extra
Where
a = the number of attributes; e = the number of learning epochs; n = the number of rows; p = the largest number of predicates in a constraint; q = the number of denial constraints; v = the largest number of distinct values in an attribute
Properties
randomizednot exactnot in placeofflineiterative
Origin
Theodoros Rekatsinas, Xu Chu, Ihab F. Ilyas, Christopher Ré, 2017

HoloClean repairs a dirty table by treating each suspicious cell as a random variable and choosing its most likely value under a model learned from the table itself. It solves the same task as the minimal repairs of database repair, but it chooses differently. A minimal repair changes as little as it can to satisfy the constraints. HoloClean weighs the constraints together with how often values occur together and with outside data, so it can make a larger change when the statistics support it, and it may leave a violation in place. It is a heuristic: nothing guarantees that its repairs are the true values, and its quality is known only from measurements. The code on this page is a toy that keeps the main steps, not the HoloClean system.

In plain words

Some cells of a table break a rule, such as "one zip code has one city". These cells are the suspects. For each suspect, HoloClean lists a few likely values: the value it has now, and the values that often appear next to the other values of its row.

Each candidate value gets a score from a few signals: how often it appears with the rest of the row, how many rule breaks it would cause, and a bonus for being the value that is already there. HoloClean learns how much each signal counts from the cells that broke no rule, since their values are probably right. Then each suspect takes the candidate with the highest score.

The problem

The input is a table with nn rows and aa attributes, a set of denial constraints, and a threshold τ\tau. The table is a list of rows, so equal rows count separately. A cell is a pair of a row and an attribute. Each cell has an unknown true value and an observed value, and some observed values are wrong. The output is a value for each cell, together with a probability for each candidate value of each cell that the method changes.

There is no exact objective that the output is proved to optimize. The goal is measured accuracy: the fraction of changed cells that are now right (precision) and the fraction of wrong cells that are now right (recall).

The algorithm

  1. HOLOCLEAN(D, Sigma, tau)
  2. 1noisy <- the cells that take part in a violation of a constraint in Sigma
  3. 2for each cell c of D do
  4. 3dom(c) <- {v_c} together with each value v with Pr[v | v_c'] >= tau for another cell c' of the row
  5. 4for each cell c and each d in dom(c) do
  6. 5f(c, d) <- the co-occurrence statistics Pr[d | v_c'], and the relaxed violation count of each constraint
  7. 6w <- the weights that maximize the likelihood of the observed values of the clean cells
  8. 7for each noisy cell c do
  9. 8P(c, d) <- the softmax over d of w . f(c, d) + prior . [d = v_c]
  10. 9set c to the value d with the largest P(c, d)
  11. 10return the repaired table and the probabilities P
  12. GIBBS(D, model, sweeps)
  13. 11x <- the observed values of the noisy cells
  14. 12for s <- 1 to sweeps do
  15. 13for each noisy cell c do
  16. 14draw x_c with probability proportional to exp(unary(c, x_c) - the weights of the violated pair factors at c)
  17. 15after the burn-in, count the value of x_c
  18. 16return the frequency of each value of each cell

Line L1 is error detection. A pair of rows that violates a constraint makes every cell of the constraint's attributes in both rows noisy. Line L3 is domain pruning, Algorithm 2 of the paper: a value enters the domain only if it often appears together with some other value of the row. The threshold τ\tau trades the size of the model against the chance that the true value is missing.

Lines L4 and L5 build the features. In the paper the signals are compiled into a factor graph by DDlog rules. The co-occurrence features say how likely a value is given each other cell of the row. A denial constraint would give a factor on each pair of rows, which makes the graph huge. The paper's relaxation, Section 5.2, replaces it with a feature of one cell: the number of rows that would conflict with the candidate value if all other cells kept their observed values. After this relaxation the noisy cells are independent given the observed table, and line L8 is exact.

Line L6 is multinomial softmax regression with the observed values of the clean cells as labels. The prior term of line L8 is the minimality signal: it prefers the value a cell already has. Lines L11 to L16 are the Gibbs sampler for the model without the relaxation, in which the pair factors stay. The toy uses it to show the difference between the two models.

Example

The constraints say that a zip code fixes the city and the state. The table has 8 rows: (z1, Chicago, IL) three times, (z1, Chicgo, IL), (z4, Peoria, IL) twice and (z2, Boston, MA) twice. Row 3, counted from 0, holds the typo. The threshold is τ=0.3\tau = 0.3 and the prior is 1.

step result
L1 noisy: the zip and city cells of rows 0 to 3, which form violations of "zip fixes city"
L3 dom of the city of row 3: Chicago, Chicgo, Peoria; dom of each zip cell of rows 0 to 5: z1, z4
L5, city of row 3 Chicago: Pr[Chicago given z1] = 0.75, 0 conflicts; Chicgo: 0.25, 3 conflicts; Peoria: 0, 3 conflicts
L5, zip of row 3 z1: 3 conflicts with the Chicago rows; z4: 2 conflicts with the Peoria rows
L6 4 clean training cells, the zip and city cells of the Peoria rows; the learned weights are 0.87 for Pr[city given zip] and minus 1.39 per conflict
L8 city of row 3: Chicago 0.965, Chicgo 0.028, Peoria 0.008; zip of row 3: z1 0.432, z4 0.568
L9 the city of row 3 becomes Chicago, which is right; the zip of row 3 becomes z4, which is wrong

The wrong change comes from the relaxation. The zip cell is scored with the city fixed at the typo, and with that city every zip in its domain causes conflicts, z4 a little fewer. The joint model would see that fixing the city removes all conflicts of z1. The test file measures the same effect on synthetic data: over 8 random tables with 60 injected errors, the toy fixed all 60 and made 12 wrong changes, all of them zip cells next to a wrong state (a measurement).

Correctness

HoloClean has no correctness theorem in the sense of returning the true values. The proof file proves what the toy computes.

Theorem. Line L1 returns exactly the cells of the violating pairs. Line L8 returns the exact marginal of each noisy cell in the relaxed model, and line L9 its most likely value. Line L6 moves along the gradient of a strictly concave regularized log-likelihood. The sampler of lines L11 to L16 keeps the joint model as its stationary distribution, and with finite weights its frequencies converge with probability 1 to the marginals of that model.

The theorem says nothing about how fast the sampler converges. With large weights it may need far more sweeps than any run can afford, as the Pitfalls show.

Proof: What the toy HoloClean pipeline computes, and why its Gibbs sampler targets the joint modelfull

Scope. HoloClean is a heuristic: nothing proves that its repairs are the true values. This file proves what the toy pipeline of the page does compute. The detection step finds exactly the cells of the violating pairs. The probabilities of line L8 are the exact distribution of the learned model in which each noisy cell is inferred with the other cells fixed. Line L6 follows the gradient of a concave objective. The sampler of lines L11 to L16 has the joint model as its stationary distribution, and its frequencies converge to the marginals of that model. Set semantics is not needed here: the table is a list of rows, and two equal rows are two rows.

Setting. A table has nn rows and aa attributes. A cell is a pair (i,b)(i, b) of a row and an attribute. A denial constraint δ\delta is a list of at most pp predicates t1[b]  θ  t2[b′]t_1[b] \;\theta\; t_2[b'], and an ordered pair of different rows (r,s)(r, s) violates δ\delta if all its predicates hold with t1=rt_1 = r and t2=st_2 = s. There are qq constraints. For each cell cc with observed value oco_c, line L3 gives a finite domain dom(c)\text{dom}(c), line L5 gives a feature vector f(c,d)f(c, d) for each d∈dom(c)d \in \text{dom}(c), and the score is sw(c,d)=w⋅f(c,d)+λ[d=oc]s_w(c, d) = w \cdot f(c, d) + \lambda [d = o_c], where λ\lambda is the prior.

Lemma 1 (detection). Line L1 returns the set of cells (i,b)(i, b) such that, for some constraint δ\delta that mentions attribute bb, row ii is in some ordered pair of different rows that violates δ\delta.

Proof. The loop visits every constraint and every ordered pair (i,j)(i, j) with i≠ji \ne j, tests every predicate, and on a violation adds the cells of both rows for every attribute of the constraint. It adds nothing else. □\square

Lemma 2 (domains). For each cell cc, oc∈dom(c)o_c \in \text{dom}(c), and dom(c)\text{dom}(c) is a subset of the values that occur in the attribute of cc. A value v≠ocv \ne o_c is in dom(c)\text{dom}(c) exactly when some other cell (i,b′)(i, b') of the row has #{v,u}≥τ⋅#{u}\#\{v, u\} \ge \tau \cdot \#\{u\}, where uu is its value, #{u}\#\{u\} counts the rows with uu in attribute b′b', and #{v,u}\#\{v, u\} counts those that also have vv in the attribute of cc.

Proof. Line L3 starts the domain with oco_c, ranges vv over the values of the attribute, and adds vv under the stated test. □\square

Lemma 3 (the probabilities of line L8). Consider the model in which the noisy cells are independent and cell cc takes the value d∈dom(c)d \in \text{dom}(c) with probability proportional to exp⁡(sw(c,d))\exp(s_w(c, d)). The features f(c,d)f(c, d) depend only on dd and on the observed values of the other cells, so this is a well defined product distribution. Line L8 returns, for each noisy cell, its exact marginal in this model, and line L9 returns its most likely value, with ties broken in favour of oco_c.

Proof. In a product distribution, the marginal of cc is its own factor, normalized: P(d)=exp⁡(sw(c,d))/∑d′exp⁡(sw(c,d′))P(d) = \exp(s_w(c, d)) / \sum_{d'} \exp(s_w(c, d')). This is the softmax of line L8. Subtracting the largest score before taking exponentials multiplies numerator and denominator by one number, so it does not change the result. Line L9 takes the largest probability, and the key (P(d),[d=oc])(P(d), [d = o_c]) prefers oco_c among equal ones. The most likely joint assignment of a product distribution is the assignment of the most likely value to each cell. □\square

Lemma 4 (learning). Let EE be the set of clean cells with more than one candidate, and L(w)=1∣E∣∑c∈Elog⁡Pw(oc∣c)−μ2∥w∥2L(w) = \frac{1}{|E|} \sum_{c \in E} \log P_w(o_c \mid c) - \frac{\mu}{2} \|w\|^2, with PwP_w the softmax of Lemma 3 and μ\mu the parameter l2. Each epoch of line L6 adds η∇L(w)\eta \nabla L(w) to ww, and LL is strictly concave.

Proof. For one cell, log⁡Pw(oc∣c)=sw(c,oc)−log⁡∑dexp⁡(sw(c,d))\log P_w(o_c \mid c) = s_w(c, o_c) - \log \sum_d \exp(s_w(c, d)). Its gradient is f(c,oc)−∑dPw(d∣c)f(c,d)=∑d([d=oc]−Pw(d∣c))f(c,d)f(c, o_c) - \sum_d P_w(d \mid c) f(c, d) = \sum_d ([d = o_c] - P_w(d \mid c)) f(c, d), which is the sum that the code builds, with the label [d=oc][d = o_c]. The gradient of the penalty is −μw-\mu w. The function log⁡∑dexp⁡(⋅)\log \sum_d \exp(\cdot) of an affine map of ww is convex, so each log-likelihood term is concave, and the penalty with μ>0\mu > 0 makes LL strictly concave. □\square

A fixed number of steps with a fixed rate need not reach the maximum of LL. The proof claims only the direction of each step.

The joint model. For a set NN of noisy cells with domains and scores ϕ(c,d)\phi(c, d), and pair factors (δ,i,j,β)(\delta, i, j, \beta) with β≥0\beta \ge 0, let

π(x)∝exp⁡(∑c∈Nϕ(c,xc)−∑(δ,i,j,β)β⋅[rows i,j of x violate δ in some order])\pi(x) \propto \exp\Big(\sum_{c \in N} \phi(c, x_c) - \sum_{(\delta, i, j, \beta)} \beta \cdot [\text{rows } i, j \text{ of } x \text{ violate } \delta \text{ in some order}]\Big)

over the assignments xx of the noisy cells, where the other cells keep their observed values. The function log_weight computes the exponent.

Lemma 5 (one Gibbs step). For a cell c=(i,b)c = (i, b), line L14 draws xcx_c from π(xc∣x−c)\pi(x_c \mid x_{-c}), the conditional of π\pi given the current values of the other noisy cells.

Proof. As a function of xcx_c alone, the exponent of π\pi changes only in ϕ(c,xc)\phi(c, x_c) and in the factors whose rows include ii, since a factor on rows j,j′j, j' with i∉{j,j′}i \notin \{j, j'\} reads no value of row ii. The code scores each dd by ϕ(c,d)\phi(c, d) minus the weights of exactly these factors that are violated with xc=dx_c = d, and samples from the softmax of the scores by inverting the cumulative sum with a uniform number. The terms it leaves out are the same for every dd, so they cancel in the normalization. □\square

Theorem. The pipeline of lines L1 to L10 stops, and it returns the noisy cells of Lemma 1, the exact marginals of Lemma 3 for the learned weights, and the most likely value of each noisy cell in that model. The sampler of lines L11 to L16 stops after the given number of sweeps. If all factor weights are finite, then as the number of sweeps grows, the frequency of each value dd of each cell cc converges with probability 1 to the marginal π(xc=d)\pi(x_c = d).

Proof. Every loop of the pipeline is over finite sets, and line L6 runs a fixed number of epochs. The returned values are those of Lemmas 1 and 3.

For the sampler, let KcK_c be the kernel of the step at cell cc. By Lemma 5, KcK_c resamples xcx_c from π(xc∣x−c)\pi(x_c \mid x_{-c}), so ∑xπ(x)Kc(x,y)=π(y)\sum_x \pi(x) K_c(x, y) = \pi(y): the step keeps π\pi. A sweep applies the kernels in a fixed order, so the sweep kernel KK also keeps π\pi. With finite weights, every assignment has π(x)>0\pi(x) > 0, so every conditional is positive on the whole domain. Then K(x,y)>0K(x, y) > 0 for all x,yx, y, since one sweep can set each cell to its value in yy. So the chain on the finite state space is irreducible and aperiodic, and by the ergodic theorem for finite Markov chains, the fraction of sweeps after which xc=dx_c = d converges to π(xc=d)\pi(x_c = d) with probability 1. Counting cell cc right after its own update, rather than at the end of the sweep, looks at the same chain shifted within the sweep, whose kernel is a cyclic reordering of the same steps and also keeps π\pi with positive entries. The burn-in removes finitely many terms, which does not change the limit. ■\blacksquare

The theorem gives no rate. When some β\beta is large, K(x,y)K(x, y) is positive but tiny for yy far from xx, and the chain can stay near one mode for longer than any practical run. The test of the page shows this with β=20\beta = 20.

Running time. Let nn be the number of rows, aa the number of attributes, vv the largest number of distinct values in an attribute, qq the number of constraints, pp the largest number of predicates in one, and ee the number of epochs. Line L1 costs O(qn2p)O(q n^2 p). The counts cost O(na2)O(n a^2). Line L3 costs O(av)O(a v) dictionary lookups per cell, so O(na2v)O(n a^2 v). Line L5 builds O(a)O(a) statistics and at most qq relaxed counts of O(np)O(n p) each, for at most navn a v pairs of a cell and a value, so O(nav(a+qnp))O(n a v (a + q n p)). One epoch of line L6 touches each feature of each candidate of each example, so O(nav(a+q))O(n a v (a + q)), and line L8 costs the same once. The total is O(n2avqp+e nav(a+q))O(n^2 a v q p + e\, n a v (a + q)) time and O(na(a+v(a+q)))O(n a (a + v (a + q))) space. One sweep of the sampler costs O(∣N∣vFp)O(|N| v F p), where FF is the largest number of factors that touch one row.

Complexity

The bounds are theorems about the toy, proved in the proof file, in data complexity for a fixed constraint set, with the attributes and the constraints kept as variables.

  • Time. Detection compares all pairs of rows, O(n2qp)O(n^2 q p). Building the features costs O(nav(a+qnp))O(n a v (a + q n p)), since each relaxed count scans the table. Each of the ee epochs of learning costs O(nav(a+q))O(n a v (a + q)). The total is O(n2avqp+e nav(a+q))O(n^2 a v q p + e\, n a v (a + q)).
  • Space. O(na(a+v(a+q)))O(n a (a + v (a + q))) for the counts, the domains and the features.
  • Gibbs. One sweep costs O(∣N∣vFp)O(|N| v F p) for ∣N∣|N| noisy cells and at most FF pair factors per row.

The paper uses hashing and blocking for detection, and DeepDive for learning and inference.

Properties

  • Heuristic. The repairs are the most likely values of a learned model, not provably true values.
  • Probabilistic output. Each repair comes with a marginal probability, which can be used to send uncertain cells to a person.
  • Soft constraints. A denial constraint is a signal with a learned weight, so the output may still violate it.
  • Weakly supervised. The labels are the observed values of the clean cells, so no hand-labeled data is needed.
  • Deterministic pipeline. Lines L1 to L10 make no random choices. Only the sampler is randomized.

Variants and improvements

  • External data. The paper adds dictionaries and matching dependencies as further signals, which give a value a feature when it matches a trusted source.
  • Joint inference. Keeping the pair factors gives the joint model of lines L11 to L16. It is more faithful, but it has a factor for each pair of rows that share a noisy cell, which is why the paper relaxes it.
  • Constraint discovery. The denial constraints can be discovered from the data, in the style of the work of Chu, Ilyas and Papotti.

When to use it

Use it when a table has many errors that break known rules, the clean part of the table is large enough to learn from, and a probability per repair is useful. Do not use it when you need a repair with a guarantee, such as the smallest change that satisfies the constraints, or when the queries can be answered without changing the data, by consistent query answering.

Pitfalls

  • Pruning away the true value. If τ\tau in line L3 is too high, the true value never enters the domain. On the table (z1, Chicago, IL) twice, (z1, Chicgo, IL) and (z2, Boston, MA), Pr[Chicago given z1] is 2/3, so τ=0.7\tau = 0.7 leaves Chicgo as the only candidate of its cell, and nothing can fix it.
  • No training signal. If no clean cell has more than one candidate, line L6 learns zero weights and line L8 is decided by the prior alone. On the same table with τ=0.5\tau = 0.5, the typo stays, with probability 0.731.
  • Relaxation errors. Line L5 scores each cell with the other cells at their observed values. Two errors in one row can push each other into wrong repairs, as the zip cell of the example shows.
  • Near-hard factors trap the sampler. In line L14, a factor weight of 20 makes a move out of a consistent state almost impossible. In the test, two cells that must agree and have no preference have the exact marginal 0.5, but the sampler returns 0 or 1. With weight 1 it returns about 0.5.
  • Clean cells are not all clean. Line L6 trusts every cell outside a violation. Errors that break no constraint are learned as correct values.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

holoclean.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/holoclean/. The authors are listed in prov/DV1WKR.jsonl.

"""A small model of the HoloClean repair pipeline, for teaching and testing.

This is not the HoloClean system. It keeps its main steps: error detection
by denial constraints, domain pruning by co-occurrence, features from
co-occurrence statistics, a minimality prior and relaxed denial constraints,
weights learned on the clean cells, and inference of the most likely value of
each noisy cell. It also has a joint model with pairwise constraint factors
and a Gibbs sampler for it.

A table is a list of rows; each row is a tuple of strings, one per attribute.
A cell is a pair (row index, attribute index). A denial constraint is a list
of predicates (a, op, b), read as t1[a] op t2[b] for two different rows t1
and t2, and the constraint says that no pair of rows makes all predicates
true. op is one of "=", "!=", "<", ">".
"""

import math

OPS = {
    "=": lambda x, y: x == y,
    "!=": lambda x, y: x != y,
    "<": lambda x, y: x < y,
    ">": lambda x, y: x > y,
}


def violates(dc, r1, r2):
    """True if the ordered pair of rows (r1, r2) makes every predicate of dc true."""
    return all(OPS[op](r1[a], r2[b]) for a, op, b in dc)


def dc_attributes(dc):
    return sorted({a for a, _, _ in dc} | {b for _, _, b in dc})


def detect_errors(rows, dcs):
    """The noisy cells: the cells of the attributes of a constraint, in each pair of rows that violates it."""
    noisy = set()
    for dc in dcs:
        attrs = dc_attributes(dc)
        for i, r1 in enumerate(rows):
            for j, r2 in enumerate(rows):
                if i != j and violates(dc, r1, r2):
                    for a in attrs:
                        noisy.add((i, a))
                        noisy.add((j, a))
    return noisy


def cooccurrence(rows):
    """Counts of single values and of value pairs within a row."""
    single, pair = {}, {}
    for r in rows:
        for a, v in enumerate(r):
            single[(a, v)] = single.get((a, v), 0) + 1
            for b, u in enumerate(r):
                if a != b:
                    pair[(a, v, b, u)] = pair.get((a, v, b, u), 0) + 1
    return single, pair


def prune_domain(rows, cell, tau, stats):
    """The candidate values of a cell: its own value and each value v of its
    attribute with Pr[v | value of another cell of the row] >= tau."""
    single, pair = stats
    i, a = cell
    row = rows[i]
    values = sorted({r[a] for r in rows})
    dom = {row[a]}
    for v in values:
        for b, u in enumerate(row):
            if b != a and pair.get((a, v, b, u), 0) >= tau * single[(b, u)]:
                dom.add(v)
                break
    return sorted(dom)


def relaxed_violations(rows, cell, value, dc):
    """The number of other rows that form a violation of dc with row i when the
    cell takes value and every other cell keeps its observed value."""
    i, a = cell
    r = list(rows[i])
    r[a] = value
    count = 0
    for j, other in enumerate(rows):
        if j != i and (violates(dc, r, other) or violates(dc, other, r)):
            count += 1
    return count


def features(rows, cell, value, dcs, stats):
    """The learnable features of a candidate value: the co-occurrence statistic
    Pr[value | value of cell (i, b)] for each other attribute b, and the relaxed
    violation count of each constraint."""
    single, pair = stats
    i, a = cell
    f = {}
    for b, u in enumerate(rows[i]):
        if b != a:
            f[("co", a, b)] = pair.get((a, value, b, u), 0) / single[(b, u)]
    for k, dc in enumerate(dcs):
        if a in dc_attributes(dc):
            n = relaxed_violations(rows, cell, value, dc)
            if n:
                f[("dc", k)] = float(n)
    return f


def _softmax(scores):
    top = max(scores)
    ex = [math.exp(s - top) for s in scores]
    z = sum(ex)
    return [e / z for e in ex]


def _score(w, f, prior, is_init):
    return sum(w.get(k, 0.0) * x for k, x in f.items()) + (prior if is_init else 0.0)


def learn(examples, prior, epochs=60, rate=0.5, l2=0.01):
    """Full-batch gradient ascent on the regularized log-likelihood of the labels.

    Each example is a list of (features, is_initial_value, is_label), one entry
    per candidate value of a clean cell.
    """
    w = {}
    n = max(1, len(examples))
    for _ in range(epochs):
        grad = {}
        for cands in examples:
            probs = _softmax([_score(w, f, prior, init) for f, init, _ in cands])
            for (f, _, label), p in zip(cands, probs):
                for k, x in f.items():
                    grad[k] = grad.get(k, 0.0) + ((1.0 if label else 0.0) - p) * x
        for k in set(grad) | set(w):
            w[k] = w.get(k, 0.0) + rate * (grad.get(k, 0.0) / n - l2 * w.get(k, 0.0))
    return w


def holoclean(rows, dcs, tau=0.5, prior=1.0, epochs=60):
    """Repair the noisy cells. Returns (repaired rows, marginals, noisy cells).

    marginals maps each noisy cell to a dict from candidate value to probability.
    """
    noisy = detect_errors(rows, dcs)  # @line L1
    stats = cooccurrence(rows)
    ncols = len(rows[0]) if rows else 0
    cells = [(i, a) for i in range(len(rows)) for a in range(ncols)]
    dom = {}
    for c in cells:  # @line L2
        dom[c] = prune_domain(rows, c, tau, stats)  # @line L3
    feats = {}
    for c in cells:  # @line L4
        for d in dom[c]:
            feats[(c, d)] = features(rows, c, d, dcs, stats)  # @line L5
    examples = []
    for c in cells:
        if c not in noisy and len(dom[c]) > 1:
            init = rows[c[0]][c[1]]
            examples.append([(feats[(c, d)], d == init, d == init) for d in dom[c]])
    w = learn(examples, prior, epochs)  # @line L6
    repaired = [list(r) for r in rows]
    marginals = {}
    for c in sorted(noisy):  # @line L7
        init = rows[c[0]][c[1]]
        probs = _softmax([_score(w, feats[(c, d)], prior, d == init) for d in dom[c]])  # @line L8
        marginals[c] = dict(zip(dom[c], probs))
        best = max(range(len(probs)), key=lambda k: (probs[k], dom[c][k] == init))
        repaired[c[0]][c[1]] = dom[c][best]  # @line L9
    return [tuple(r) for r in repaired], marginals, noisy  # @line L10


def joint_model(rows, dcs, noisy, dom, unary, weight):
    """The pair factors of the joint model: for each constraint and each pair of
    rows that share a noisy cell of its attributes, one factor of the given weight.

    unary maps (cell, value) to a score. Returns (cells, dom, unary, factors).
    """
    cells = sorted(noisy)
    factors = []
    for k, dc in enumerate(dcs):
        attrs = dc_attributes(dc)
        for i in range(len(rows)):
            for j in range(i + 1, len(rows)):
                if any((i, a) in noisy or (j, a) in noisy for a in attrs):
                    factors.append((k, i, j, weight))
    return cells, dom, unary, factors


def _assignment_rows(rows, x):
    out = [list(r) for r in rows]
    for (i, a), v in x.items():
        out[i][a] = v
    return out


def log_weight(rows, dcs, model, x):
    """The unnormalized log-probability of a full assignment x of the noisy cells."""
    cells, dom, unary, factors = model
    cur = _assignment_rows(rows, x)
    s = sum(unary[(c, x[c])] for c in cells)
    for k, i, j, w in factors:
        if violates(dcs[k], cur[i], cur[j]) or violates(dcs[k], cur[j], cur[i]):
            s -= w
    return s


def gibbs(rows, dcs, model, sweeps, burn_in, rng):
    """Estimate the marginals of the noisy cells by Gibbs sampling."""
    cells, dom, unary, factors = model
    touching = {c: [f for f in factors if f[1] == c[0] or f[2] == c[0]] for c in cells}
    x = {c: rows[c[0]][c[1]] for c in cells}  # @line L11
    cur = _assignment_rows(rows, x)
    counts = {c: {d: 0 for d in dom[c]} for c in cells}
    for s in range(sweeps):  # @line L12
        for c in cells:  # @line L13
            i, a = c
            scores = []
            for d in dom[c]:
                cur[i][a] = d
                sc = unary[(c, d)]
                for k, p, q, w in touching[c]:
                    if violates(dcs[k], cur[p], cur[q]) or violates(dcs[k], cur[q], cur[p]):
                        sc -= w
                scores.append(sc)
            probs = _softmax(scores)
            u = rng.random()
            pick = len(probs) - 1
            acc = 0.0
            for k, p in enumerate(probs):
                acc += p
                if u < acc:
                    pick = k
                    break
            x[c] = dom[c][pick]  # @line L14
            cur[i][a] = x[c]
            if s >= burn_in:
                counts[c][x[c]] += 1  # @line L15
    n = sweeps - burn_in
    return {c: {d: counts[c][d] / n for d in dom[c]} for c in cells}  # @line L16
test_holoclean.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/holoclean/. The authors are listed in prov/DV1WKR.jsonl.

import itertools
import math
import random

from holoclean import (
    cooccurrence,
    detect_errors,
    gibbs,
    holoclean,
    joint_model,
    log_weight,
    prune_domain,
    relaxed_violations,
    violates,
)

# Zip -> City and Zip -> State as two denial constraints over attributes 0, 1, 2.
DCS = [[(0, "=", 0), (1, "!=", 1)], [(0, "=", 0), (2, "!=", 2)]]


def synthetic(seed, n=80, nzips=10, p=0.06):
    """Clean rows (zip, city, state) where zip fixes city and state, and a dirty copy."""
    rng = random.Random(seed)
    zips = {"z%d" % k: ("city%d" % (k % (nzips // 2)), "S%d" % (k % 3)) for k in range(nzips)}
    clean, dirty = [], []
    for _ in range(n):
        z = rng.choice(sorted(zips))
        city, state = zips[z]
        clean.append((z, city, state))
        d = [z, city, state]
        if rng.random() < p:
            d[1] = city + "x"
        if rng.random() < p / 2:
            d[2] = rng.choice(["S0", "S1", "S2"])
        dirty.append(tuple(d))
    return clean, dirty


def brute_noisy(rows, dcs):
    """Oracle: check every ordered pair of rows against every constraint."""
    out = set()
    for dc in dcs:
        attrs = {a for a, _, _ in dc} | {b for _, _, b in dc}
        for i, j in itertools.permutations(range(len(rows)), 2):
            if all({"=": rows[i][a] == rows[j][b], "!=": rows[i][a] != rows[j][b]}[op] for a, op, b in dc):
                out |= {(i, a) for a in attrs} | {(j, a) for a in attrs}
    return out


def test_detection_matches_pairs():
    rng = random.Random(3)
    for _ in range(30):
        _, dirty = synthetic(rng.randint(0, 10**6), n=rng.randint(2, 15), p=0.2)
        assert detect_errors(dirty, DCS) == brute_noisy(dirty, DCS)


def test_small_table():
    rows = [("z1", "Chicago", "IL"), ("z1", "Chicago", "IL"), ("z1", "Chicgo", "IL"), ("z2", "Boston", "MA")]
    noisy = detect_errors(rows, DCS)
    assert noisy == {(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)}
    stats = cooccurrence(rows)
    # Pr[Chicago | z1] = 2/3 and Pr[Chicgo | z1] = 1/3.
    assert prune_domain(rows, (2, 1), 0.5, stats) == ["Chicago", "Chicgo"]
    assert prune_domain(rows, (2, 1), 0.7, stats) == ["Chicgo"]
    assert relaxed_violations(rows, (2, 1), "Chicgo", DCS[0]) == 2
    assert relaxed_violations(rows, (2, 1), "Chicago", DCS[0]) == 0
    assert violates(DCS[0], rows[0], rows[2]) and not violates(DCS[0], rows[0], rows[1])


def test_repairs_on_synthetic_data():
    tp = fp = errors = 0
    for seed in range(8):
        clean, dirty = synthetic(seed)
        repaired, marginals, noisy = holoclean(dirty, DCS, tau=0.3, prior=1.0)
        for i, row in enumerate(dirty):
            for a in range(3):
                if row[a] != clean[i][a]:
                    errors += 1
                if repaired[i][a] != row[a]:
                    if repaired[i][a] == clean[i][a]:
                        tp += 1
                    else:
                        fp += 1
        for c, m in marginals.items():
            assert c in noisy
            assert abs(sum(m.values()) - 1.0) < 1e-9
    # Measured with these seeds: 60 of 60 errors fixed, 12 wrong changes.
    assert (tp, fp, errors) == (60, 12, 60)
    assert tp / (tp + fp) > 0.8 and tp / errors > 0.95


def test_clean_table_is_unchanged():
    clean, _ = synthetic(1)
    repaired, marginals, noisy = holoclean(clean, DCS, tau=0.3)
    assert repaired == clean and not marginals and not noisy


def exact_marginals(rows, dcs, model):
    cells, dom, _, _ = model
    totals = {c: {d: 0.0 for d in dom[c]} for c in cells}
    z = 0.0
    for combo in itertools.product(*[dom[c] for c in cells]):
        x = dict(zip(cells, combo))
        p = math.exp(log_weight(rows, dcs, model, x))
        z += p
        for c in cells:
            totals[c][x[c]] += p
    return {c: {d: v / z for d, v in totals[c].items()} for c in cells}


def test_gibbs_matches_exact_marginals():
    rng = random.Random(11)
    rows = [("z1", "A", "S1"), ("z1", "B", "S1"), ("z1", "A", "S2"), ("z2", "C", "S1")]
    noisy = detect_errors(rows, DCS)
    noisy = {c for c in noisy if c[1] != 0}
    dom = {c: sorted({r[c[1]] for r in rows}) for c in noisy}
    unary = {(c, d): rng.uniform(-1.0, 1.0) for c in noisy for d in dom[c]}
    model = joint_model(rows, DCS, noisy, dom, unary, 1.5)
    assert len(model[0]) == 6
    exact = exact_marginals(rows, DCS, model)
    est = gibbs(rows, DCS, model, sweeps=4000, burn_in=200, rng=random.Random(5))
    for c in exact:
        for d in exact[c]:
            assert abs(exact[c][d] - est[c][d]) < 0.04


def test_near_hard_constraint_traps_the_sampler():
    # Two cells that must agree, with no preference between A and B. The exact
    # marginal is 1/2, but with a weight of 20 one-cell moves almost never leave
    # the first consistent state, so the estimate is 0 or 1.
    rows = [("z1", "A", "S1"), ("z1", "B", "S1")]
    noisy = {(0, 1), (1, 1)}
    dom = {c: ["A", "B"] for c in noisy}
    unary = {(c, d): 0.0 for c in noisy for d in dom[c]}
    model = joint_model(rows, DCS, noisy, dom, unary, 20.0)
    exact = exact_marginals(rows, DCS, model)
    assert abs(exact[(0, 1)]["A"] - 0.5) < 1e-9
    assert log_weight(rows, DCS, model, {(0, 1): "A", (1, 1): "B"}) == -20.0
    est = gibbs(rows, DCS, model, sweeps=2000, burn_in=100, rng=random.Random(1))
    assert est[(0, 1)]["A"] in (0.0, 1.0)
    soft = joint_model(rows, DCS, noisy, dom, unary, 1.0)
    est = gibbs(rows, DCS, soft, sweeps=4000, burn_in=200, rng=random.Random(1))
    assert abs(est[(0, 1)]["A"] - 0.5) < 0.05

History

Chu, Ilyas and Papotti introduced holistic data cleaning with denial constraints at ICDE 2013 and studied the discovery of denial constraints in PVLDB the same year. Rekatsinas, Chu, Ilyas and Ré presented HoloClean in PVLDB in 2017. They compiled the signals into DDlog, the language of DeepDive, and ran learning and Gibbs sampling there. On four real data sets, the authors measured an average precision of about 90% and an average recall above 76%, better than the earlier methods they compared with (a measurement).

References

  1. Theodoros Rekatsinas, Xu Chu, Ihab F. Ilyas and Christopher Ré, HoloClean: holistic data repairs with probabilistic inference, PVLDB 10(11), 2017, pages 1190-1201: Section 3 (the signals and the factor graph), Section 4 (compilation to DDlog), Algorithm 2 (domain pruning), Section 5.2 (relaxed denial constraints), Section 6 (experiments)
  2. Xu Chu, Ihab F. Ilyas and Paolo Papotti, Holistic data cleaning: putting violations into context, ICDE 2013, pages 458-469, detection and repair with denial constraints
  3. Xu Chu, Ihab F. Ilyas and Paolo Papotti, Discovering denial constraints, PVLDB 6(13), 2013, pages 1498-1509, the language of denial constraints

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example