# Censored Data Models¶

```
[1]:
```

```
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pymc3 as pm
import seaborn as sns
import theano.tensor as tt
print(f"Running on PyMC3 v{pm.__version__}")
```

```
Running on PyMC3 v3.9.0
```

```
[2]:
```

```
%config InlineBackend.figure_format = 'retina'
az.style.use("arviz-darkgrid")
```

This example notebook on Bayesian survival analysis touches on the point of censored data. *Censoring* is a form of missing-data problem, in which observations greater than a certain threshold are clipped down to that threshold, or observations less than a certain threshold are clipped up to that threshold, or both. These are called right, left and interval censoring, respectively. In this example notebook we consider interval censoring.

Censored data arises in many modelling problems. Two common examples are:

*Survival analysis:*when studying the effect of a certain medical treatment on survival times, it is impossible to prolong the study until all subjects have died. At the end of the study, the only data collected for many patients is that they were still alive for a time period \(T\) after the treatment was administered: in reality, their true survival times are greater than \(T\).*Sensor saturation:*a sensor might have a limited range and the upper and lower limits would simply be the highest and lowest values a sensor can report. For instance, many mercury thermometers only report a very narrow range of temperatures.

This example notebook presents two different ways of dealing with censored data in PyMC3:

An imputed censored model, which represents censored data as parameters and makes up plausible values for all censored values. As a result of this imputation, this model is capable of generating plausible sets of made-up values that would have been censored. Each censored element introduces a random variable.

An unimputed censored model, where the censored data are integrated out and accounted for only through the log-likelihood. This method deals more adequately with large amounts of censored data and converges more quickly.

To establish a baseline we compare to an uncensored model of the uncensored data.

```
[3]:
```

```
# Produce normally distributed samples
np.random.seed(1618)
size = 500
mu = 13.0
sigma = 5.0
samples = np.random.normal(mu, sigma, size)
# Set censoring limits
high = 16.0
low = -1.0
# Censor samples
censored = samples[(samples > low) & (samples < high)]
```

```
[4]:
```

```
# Visualize uncensored and censored data
_, axarr = plt.subplots(ncols=2, figsize=[16, 4], sharex=True, sharey=True)
for i, data in enumerate([samples, censored]):
sns.distplot(data, ax=axarr[i])
axarr[0].set_title("Uncensored")
axarr[1].set_title("Censored")
plt.show()
```

## Baseline - Uncensored Model of Uncensored Data¶

```
[5]:
```

```
# Uncensored model
with pm.Model() as uncensored_model:
mu = pm.Normal("mu", mu=0.0, sigma=(high - low) / 2.0)
sigma = pm.HalfNormal("sigma", sigma=(high - low) / 2.0)
observed = pm.Normal("observed", mu=mu, sigma=sigma, observed=samples)
```

## Model 1 - Imputed Censored Model of Censored Data¶

In this model, we impute the censored values from the same distribution as the uncensored data. Sampling from the posterior generates possible uncensored data sets.

This model makes use of PyMC3’s bounded variables.

```
[6]:
```

```
# Imputed censored model
n_right_censored = len(samples[samples >= high])
n_left_censored = len(samples[samples <= low])
n_observed = len(samples) - n_right_censored - n_left_censored
with pm.Model() as imputed_censored_model:
mu = pm.Normal("mu", mu=0.0, sigma=(high - low) / 2.0)
sigma = pm.HalfNormal("sigma", sigma=(high - low) / 2.0)
right_censored = pm.Bound(pm.Normal, lower=high)(
"right_censored", mu=mu, sigma=sigma, shape=n_right_censored
)
left_censored = pm.Bound(pm.Normal, upper=low)(
"left_censored", mu=mu, sigma=sigma, shape=n_left_censored
)
observed = pm.Normal("observed", mu=mu, sigma=sigma, observed=censored, shape=n_observed)
```

## Model 2 - Unimputed Censored Model of Censored Data¶

In this model, we do not impute censored data, but instead integrate them out through the likelihood.

The implementations of the likelihoods are non-trivial. See the Stan manual (section 11.3 on censored data) and the original PyMC3 issue on GitHub for more information.

This model makes use of PyMC3’s ``Potential` <https://docs.pymc.io/api/model.html#pymc3.model.Potential>`__.

```
[7]:
```

```
# Import the log cdf and log complementary cdf of the normal Distribution from PyMC3
from pymc3.distributions.dist_math import normal_lccdf, normal_lcdf
# Helper functions for unimputed censored model
def left_censored_likelihood(mu, sigma, n_left_censored, lower_bound):
""" Likelihood of left-censored data. """
return n_left_censored * normal_lcdf(mu, sigma, lower_bound)
def right_censored_likelihood(mu, sigma, n_right_censored, upper_bound):
""" Likelihood of right-censored data. """
return n_right_censored * normal_lccdf(mu, sigma, upper_bound)
```

```
[8]:
```

```
# Unimputed censored model
with pm.Model() as unimputed_censored_model:
mu = pm.Normal("mu", mu=0.0, sigma=(high - low) / 2.0)
sigma = pm.HalfNormal("sigma", sigma=(high - low) / 2.0)
observed = pm.Normal(
"observed",
mu=mu,
sigma=sigma,
observed=censored,
)
left_censored = pm.Potential(
"left_censored", left_censored_likelihood(mu, sigma, n_left_censored, low)
)
right_censored = pm.Potential(
"right_censored", right_censored_likelihood(mu, sigma, n_right_censored, high)
)
```

## Sampling¶

```
[9]:
```

```
# Uncensored model
with uncensored_model:
trace = pm.sample(tune=1000) # Increase `tune` to avoid divergences
pm.plot_posterior(trace);
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, mu]
```

```
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 3 seconds.
```

```
[10]:
```

```
# Imputed censored model
with imputed_censored_model:
trace = pm.sample()
pm.plot_posterior(trace, varnames=["mu", "sigma"]);
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [left_censored, right_censored, sigma, mu]
```

```
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 12 seconds.
/dependencies/pymc3/pymc3/plots/__init__.py:35: UserWarning: Keyword argument `varnames` renamed to `var_names`, and will be removed in pymc3 3.8
warnings.warn('Keyword argument `{old}` renamed to `{new}`, and will be removed in pymc3 3.8'.format(old=old, new=new))
```

```
[11]:
```

```
# Unimputed censored model
with unimputed_censored_model:
trace = pm.sample(tune=1000) # Increase `tune` to avoid divergences
pm.plot_posterior(trace, varnames=["mu", "sigma"]);
```

```
Auto-assigning NUTS sampler...
Initializing NUTS using jitter+adapt_diag...
Multiprocess sampling (4 chains in 4 jobs)
NUTS: [sigma, mu]
```

```
Sampling 4 chains for 1_000 tune and 1_000 draw iterations (4_000 + 4_000 draws total) took 3 seconds.
/dependencies/pymc3/pymc3/plots/__init__.py:35: UserWarning: Keyword argument `varnames` renamed to `var_names`, and will be removed in pymc3 3.8
warnings.warn('Keyword argument `{old}` renamed to `{new}`, and will be removed in pymc3 3.8'.format(old=old, new=new))
```

## Discussion¶

As we can see, both censored models appear to capture the mean and variance of the underlying distribution as well as the uncensored model! In addition, the imputed censored model is capable of generating data sets of censored values (sample from the posteriors of `left_censored`

and `right_censored`

to generate them), while the unimputed censored model scales much better with more censored data, and converges faster.

## Authors¶

Originally authored by Luis Mario Domenzain on Mar 7, 2017.

Updated by George Ho on Jul 14, 2018.

```
[12]:
```

```
%load_ext watermark
%watermark -n -u -v -iv -w
```

```
numpy 1.18.5
pymc3 3.9.0
seaborn 0.10.1
pandas 1.0.4
arviz 0.8.3
last updated: Mon Jun 15 2020
CPython 3.7.7
IPython 7.15.0
watermark 2.0.2
```