Examples

Missing values#

Open in Colab Download this notebook

A method that reads only the rows where a test’s variables are observed is sound when values go missing at random of everything. When whether a value is missing depends on another variable, those rows are a selected sample and the method can keep edges the data do not support. Here we remove values from simulated data in a known way, fit PC with its default handling and with missing="mvpc", fit GES with missing="em", and compare each graph with the true one.

Start#

Choose a CPU runtime and run this cell first. In Colab it installs andrey-core==0.18.0 from PyPI; local kernels use the installed environment.

import os
import sys

IN_COLAB = "google.colab" in sys.modules

if IN_COLAB:
    os.environ["ANDREY_DEVICE"] = "cpu"
    !pip install --quiet "andrey-core[viz]==0.18.0" pandas
import numpy as np
import pandas as pd

import andrey
import andrey.viz
from andrey import data
from andrey.data import missingness
from andrey.metrics import shd, to_cpdag

Data with a known graph#

data.sample_scm draws 2,000 rows of ten variables from a linear-Gaussian model whose graph we know. PC and GES can recover that graph only up to its Markov equivalence class, so we score each result against the true CPDAG.

complete = data.sample_scm(d=10, n=2000, seed=9, density=2)
truth = to_cpdag(complete.graph)
andrey.viz.draw(complete.graph)
0123456789

Remove values#

missingness.mar(0.3, form="quantile") is missing at random given the observed variables: a variable that can go missing has one parent among the variables that never do, and its value is missing with probability 0.9 when the parent is below a quantile of its values and 0.01 otherwise. missingness.draw applies the rule to the complete data and returns the mask and each indicator’s parents.

rule = missingness.mar(0.3, form="quantile")
mask = missingness.draw(complete.data, rule, seed=9)
gappy = np.where(mask.mask, np.nan, complete.data)
print("share missing, by column:", np.round(mask.mask.mean(axis=0), 2).tolist())
print("parent of each missingness indicator:", mask.parents)
share missing, by column: [0.29, 0.0, 0.0, 0.3, 0.0, 0.3, 0.3, 0.3, 0.3, 0.3]
parent of each missingness indicator: {0: [2], 3: [4], 5: [1], 6: [2], 7: [4], 8: [1], 9: [2]}

PC with its default handling#

The default, missing=None, is test-wise deletion for PC: each test reads the rows where its variables are observed, and metadata["rows_tested"] gives the fewest rows and the median number of rows a test read. The rows a test keeps are a selected sample, as they depend on the variables through the parents above.

default = andrey.pc(gappy)
print("rows read by a test:", default.metadata["rows_tested"])
print("errors against the true CPDAG:", shd(default, truth))
rows read by a test: {'min': 645, 'median': 950.0}
errors against the true CPDAG: 5

PC with missing="mvpc"#

Missing-Value PC finds the variables each missingness indicator depends on, then tests again the edges such an indicator could have kept, on data rebuilt from the rows where those variables are observed.

mvpc = andrey.pc(gappy, missing="mvpc")
print("parents of the indicators it found:", mvpc.metadata["missingness_parents"])
print("edges it tested again and removed:", mvpc.metadata["corrected_edges"]["removed"])
print("errors against the true CPDAG:", shd(mvpc, truth))
parents of the indicators it found: {0: [2], 3: [4], 5: [0, 1], 6: [2], 7: [4], 8: [1], 9: [2]}
edges it tested again and removed: [[3, 9]]
errors against the true CPDAG: 1

A score search with missing="em"#

A search that reads the data only through their covariance cannot delete rows per test, so it takes missing="em": structural EM replaces each row’s missing values by their expected values under the model of the current graph and adds their uncertainty, which gives the expected covariance of the data, and the search runs on that covariance over every row.

em = andrey.ges(gappy, missing="em")
print("errors against the true CPDAG:", shd(em, truth))
errors against the true CPDAG: 0

Compare#

PC and GES on the complete data show what each method makes of these data when nothing is missing.

outputs = {
    "PC, complete data": andrey.pc(complete.data),
    "GES, complete data": andrey.ges(complete.data),
    "PC, default": default,
    'PC, missing="mvpc"': mvpc,
    'GES, missing="em"': em,
}
pd.Series({name: shd(out, truth) for name, out in outputs.items()}, name="errors (SHD)").to_frame()
errors (SHD)
PC, complete data 1
GES, complete data 0
PC, default 5
PC, missing="mvpc" 1
GES, missing="em" 0

Ten datasets#

One draw can differ from the next. The same comparison on ten datasets, each with its own graph and its own missing values:

rows = []
for seed in range(10):
    full = data.sample_scm(d=10, n=2000, seed=seed, density=2)
    gaps = missingness.draw(full.data, rule, seed=seed)
    x = np.where(gaps.mask, np.nan, full.data)
    true = to_cpdag(full.graph)
    rows.append(
        {
            "PC, complete data": shd(andrey.pc(full.data), true),
            "GES, complete data": shd(andrey.ges(full.data), true),
            "PC, default": shd(andrey.pc(x), true),
            'PC, missing="mvpc"': shd(andrey.pc(x, missing="mvpc"), true),
            'GES, missing="em"': shd(andrey.ges(x, missing="em"), true),
        }
    )
pd.DataFrame(rows).mean().round(1).to_frame("mean errors (SHD)")
mean errors (SHD)
PC, complete data 1.8
GES, complete data 1.5
PC, default 4.8
PC, missing="mvpc" 3.6
GES, missing="em" 1.1

On this dataset, PC’s default handling makes 5 errors where PC on the complete data makes 1; missing="mvpc" removes the edge it traces to the missingness parents and is back to 1, and GES with missing="em" makes none, as it does on the complete data. Over ten datasets PC makes 4.8 errors by default and 3.6 with MVPC against 1.8 on the complete data, so MVPC closes part of the gap, while GES with EM makes 1.1 against 1.5 on the complete data. The two searches differ in more than how they treat gaps, so read each against its own fit on the complete data; the Missing values guide and the 0.16.0 release card give what we measured against reference implementations.