# Bayesian Survival Analysis in Python with pymc3

Survival analysis studies the distribution of the time to an event. Its applications span many fields across medicine, biology, engineering, and social science. This post shows how to fit and analyze a Bayesian survival model in Python using `pymc3`

.

We illustrate these concepts by analyzing a mastectomy data set from `R`

’s `HSAUR`

package.

`%matplotlib inline`

```
from matplotlib import pyplot as plt
import numpy as np
import pymc3 as pm
from pymc3.distributions.timeseries import GaussianRandomWalk
import seaborn as sns
from statsmodels import datasets
from theano import tensor as T
```

`Couldn't import dot_parser, loading of dot files will not be possible.`

Fortunately, `statsmodels.datasets`

makes it quite easy to load a number of data sets from `R`

.

```
= datasets.get_rdataset('mastectomy', 'HSAUR', cache=True).data
df = df.event.astype(np.int64)
df.event = (df.metastized == 'yes').astype(np.int64)
df.metastized = df.shape[0]
n_patients = np.arange(n_patients) patients
```

` df.head()`

time | event | metastized | |
---|---|---|---|

0 | 23 | 1 | 0 |

1 | 47 | 1 | 0 |

2 | 69 | 1 | 0 |

3 | 70 | 0 | 0 |

4 | 100 | 0 | 0 |

` n_patients`

`44`

Each row represents observations from a woman diagnosed with breast cancer that underwent a mastectomy. The column `time`

represents the time (in months) post-surgery that the woman was observed. The column `event`

indicates whether or not the woman died during the observation period. The column `metastized`

represents whether the cancer had metastized prior to surgery.

This post analyzes the relationship between survival time post-mastectomy and whether or not the cancer had metastized.

#### A crash course in survival analysis

First we introduce a (very little) bit of theory. If the random variable \(T\) is the time to the event we are studying, survival analysis is primarily concerned with the survival function

\[S(t) = P(T > t) = 1 - F(t),\]

where \(F\) is the CDF of \(T\). It is mathematically convenient to express the survival function in terms of the hazard rate, \(\lambda(t)\). The hazard rate is the instantaneous probability that the event occurs at time \(t\) given that it has not yet occured. That is,

\[\begin{align*} \lambda(t) & = \lim_{\Delta t \to 0} \frac{P(t < T < t + \Delta t\ |\ T > t)}{\Delta t} \\ & = \lim_{\Delta t \to 0} \frac{P(t < T < t + \Delta t)}{\Delta t \cdot P(T > t)} \\ & = \frac{1}{S(t)} \cdot \lim_{\Delta t \to 0} \frac{S(t + \Delta t) - S(t)}{\Delta t} = -\frac{S'(t)}{S(t)}. \end{align*}\]

Solving this differential equation for the survival function shows that

\[S(t) = \exp\left(-\int_0^s \lambda(s)\ ds\right).\]

This representation of the survival function shows that the cumulative hazard function

\[\Lambda(t) = \int_0^t \lambda(s)\ ds\]

is an important quantity in survival analysis, since we may consicesly write \(S(t) = \exp(-\Lambda(t)).\)

An important, but subtle, point in survival analysis is censoring. Even though the quantity we are interested in estimating is the time between surgery and death, we do not observe the death of every subject. At the point in time that we perform our analysis, some of our subjects will thankfully still be alive. In the case of our mastectomy study, `df.event`

is one if the subject’s death was observed (the observation is not censored) and is zero if the death was not observed (the observation is censored).

` df.event.mean()`

`0.59090909090909094`

Just over 40% of our observations are censored. We visualize the observed durations and indicate which observations are censored below.

```
= plt.subplots(figsize=(8, 6))
fig, ax
= sns.color_palette()[:3]
blue, _, red
== 0], 0, df[df.event.values == 0].time,
ax.hlines(patients[df.event.values =blue, label='Censored');
color
== 1], 0, df[df.event.values == 1].time,
ax.hlines(patients[df.event.values =red, label='Uncensored');
color
== 1].time, patients[df.metastized.values == 1],
ax.scatter(df[df.metastized.values ='k', zorder=10, label='Metastized');
color
=0);
ax.set_xlim(left'Months since mastectomy');
ax.set_xlabel(
-0.25, n_patients + 0.25);
ax.set_ylim(
='center right'); ax.legend(loc
```

When an observation is censored (`df.event`

is zero), `df.time`

is not the subject’s survival time. All we can conclude from such a censored obsevation is that the subject’s true survival time exceeds `df.time`

.

This is enough basic surival analysis theory for the purposes of this post; for a more extensive introduction, consult Aalen et al.^{1}

#### Bayesian proportional hazards model

The two most basic estimators in survial analysis are the Kaplan-Meier estimator of the survival function and the Nelson-Aalen estimator of the cumulative hazard function. However, since we want to understand the impact of metastization on survival time, a risk regression model is more appropriate. Perhaps the most commonly used risk regression model is Cox’s proportional hazards model. In this model, if we have covariates \(\mathbf{x}\) and regression coefficients \(\beta\), the hazard rate is modeled as

\[\lambda(t) = \lambda_0(t) \exp(\mathbf{x} \beta).\]

Here \(\lambda_0(t)\) is the baseline hazard, which is independent of the covariates \(\mathbf{x}\). In this example, the covariates are the one-dimensonal vector `df.metastized`

.

Unlike in many regression situations, \(\mathbf{x}\) should not include a constant term corresponding to an intercept. If \(\mathbf{x}\) includes a constant term corresponding to an intercept, the model becomes unidentifiable. To illustrate this unidentifiability, suppose that

\[\lambda(t) = \lambda_0(t) \exp(\beta_0 + \mathbf{x} \beta) = \lambda_0(t) \exp(\beta_0) \exp(\mathbf{x} \beta).\]

If \(\tilde{\beta}_0 = \beta_0 + \delta\) and \(\tilde{\lambda}_0(t) = \lambda_0(t) \exp(-\delta)\), then \(\lambda(t) = \tilde{\lambda}_0(t) \exp(\tilde{\beta}_0 + \mathbf{x} \beta)\) as well, making the model with \(\beta_0\) unidentifiable.

In order to perform Bayesian inference with the Cox model, we must specify priors on \(\beta\) and \(\lambda_0(t)\). We place a normal prior on \(\beta\), \(\beta \sim N(\mu_{\beta}, \sigma_{\beta}^2),\) where \(\mu_{\beta} \sim N(0, 10^2)\) and \(\sigma_{\beta} \sim U(0, 10)\).

A suitable prior on \(\lambda_0(t)\) is less obvious. We choose a semiparametric prior, where \(\lambda_0(t)\) is a piecewise constant function. This prior requires us to partition the time range in question into intervals with endpoints \(0 \leq s_1 < s_2 < \cdots < s_N\). With this partition, \(\lambda_0 (t) = \lambda_j\) if \(s_j \leq t < s_{j + 1}\). With \(\lambda_0(t)\) constrained to have this form, all we need to do is choose priors for the \(N - 1\) values \(\lambda_j\). We use independent vague priors \(\lambda_j \sim \operatorname{Gamma}(10^{-2}, 10^{-2}).\) For our mastectomy example, we make each interval three months long.

```
= 3
interval_length = np.arange(0, df.time.max() + interval_length + 1, interval_length)
interval_bounds = interval_bounds.size - 1
n_intervals = np.arange(n_intervals) intervals
```

We see how deaths and censored observations are distributed in these intervals.

```
= plt.subplots(figsize=(8, 6))
fig, ax
== 1].time.values, bins=interval_bounds,
ax.hist(df[df.event =red, alpha=0.5, lw=0,
color='Uncensored');
label== 0].time.values, bins=interval_bounds,
ax.hist(df[df.event =blue, alpha=0.5, lw=0,
color='Censored');
label
0, interval_bounds[-1]);
ax.set_xlim('Months since mastectomy');
ax.set_xlabel(
0, 1, 2, 3]);
ax.set_yticks(['Number of observations');
ax.set_ylabel(
; ax.legend()
```

With the prior distributions on \(\beta\) and \(\lambda_0(t)\) chosen, we now show how the model may be fit using MCMC simulation with `pymc3`

. The key observation is that the piecewise-constant proportional hazard model is closely related to a Poisson regression model. (The models are not identical, but their likelihoods differ by a factor that depends only on the observed data and not the parameters \(\beta\) and \(\lambda_j\). For details, see Germán Rodríguez’s WWS 509 course notes.)

We define indicator variables based on whether or the \(i\)-th suject died in the \(j\)-th interval,

\[d_{i, j} = \begin{cases} 1 & \textrm{if subject } i \textrm{ died in interval } j \\ 0 & \textrm{otherwise} \end{cases}.\]

```
= np.floor((df.time - 0.01) / interval_length)
last_period
= np.zeros((n_patients, n_intervals))
death = df.event death[patients, last_period]
```

We also define \(t_{i, j}\) to be the amount of time the \(i\)-th subject was at risk in the \(j\)-th interval.

```
= np.greater_equal.outer(df.time, interval_bounds[:-1]) * interval_length
exposure = df.time - interval_bounds[last_period] exposure[patients, last_period]
```

Finally, denote the risk incurred by the \(i\)-th subject in the \(j\)-th interval as \(\lambda_{i, j} = \lambda_j \exp(\mathbf{x}_i \beta)\).

We may approximate \(d_{i, j}\) with a Possion random variable with mean \(t_{i, j}\ \lambda_{i, j}\). This approximation leads to the following `pymc3`

model.

`= 5078864 # from random.org SEED `

```
with pm.Model() as model:
= pm.Gamma('lambda0', 0.01, 0.01, shape=n_intervals)
lambda0
= pm.Uniform('sigma', 0., 10.)
sigma = pm.Deterministic('tau', sigma**-2)
tau = pm.Normal('mu_beta', 0., 10**-2)
mu_beta = pm.Normal('beta', mu_beta, tau)
beta
= pm.Deterministic('lambda_', T.outer(T.exp(beta * df.metastized), lambda0))
lambda_ = pm.Deterministic('mu', exposure * lambda_)
mu
= pm.Poisson('obs', mu, observed=death) obs
```

We now sample from the model.

```
= 40000
n_samples = 20000
burn = 20 thin
```

```
with model:
= pm.Metropolis()
step = pm.sample(n_samples, step, random_seed=SEED) trace_
```

` [-----------------100%-----------------] 40000 of 40000 complete in 39.0 sec`

`= trace_[burn::thin] trace `

We see that the hazard rate for subjects whose cancer has metastized is about one and a half times the rate of those whose cancer has not metastized.

`'beta'].mean()) np.exp(trace[`

`1.645592148084472`

`vars=['beta']); pm.traceplot(trace, `

`vars=['beta']); pm.autocorrplot(trace, `

We now examine the effect of metastization on both the cumulative hazard and on the survival function.

```
= trace['lambda0']
base_hazard = trace['lambda0'] * np.exp(np.atleast_2d(trace['beta']).T) met_hazard
```

```
def cum_hazard(hazard):
return (interval_length * hazard).cumsum(axis=-1)
def survival(hazard):
return np.exp(-cum_hazard(hazard))
```

```
def plot_with_hpd(x, hazard, f, ax, color=None, label=None, alpha=0.05):
= f(hazard.mean(axis=0))
mean
= 100 * np.array([alpha / 2., 1. - alpha / 2.])
percentiles = np.percentile(f(hazard), percentiles, axis=0)
hpd
0], hpd[1], color=color, alpha=0.25)
ax.fill_between(x, hpd[=color, label=label); ax.step(x, mean, color
```

```
= plt.subplots(ncols=2, sharex=True, sharey=False, figsize=(16, 6))
fig, (hazard_ax, surv_ax)
-1], base_hazard, cum_hazard,
plot_with_hpd(interval_bounds[:=blue, label='Had not metastized')
hazard_ax, color-1], met_hazard, cum_hazard,
plot_with_hpd(interval_bounds[:=red, label='Metastized')
hazard_ax, color
0, df.time.max());
hazard_ax.set_xlim('Months since mastectomy');
hazard_ax.set_xlabel(
r'Cumulative hazard $\Lambda(t)$');
hazard_ax.set_ylabel(
=2);
hazard_ax.legend(loc
-1], base_hazard, survival,
plot_with_hpd(interval_bounds[:=blue)
surv_ax, color-1], met_hazard, survival,
plot_with_hpd(interval_bounds[:=red)
surv_ax, color
0, df.time.max());
surv_ax.set_xlim('Months since mastectomy');
surv_ax.set_xlabel(
'Survival function $S(t)$');
surv_ax.set_ylabel(
'Bayesian survival model'); fig.suptitle(
```

We see that the cumulative hazard for metastized subjects increases more rapidly initially (through about seventy months), after which it increases roughly in parallel with the baseline cumulative hazard.

These plots also show the pointwise 95% high posterior density interval for each function. One of the distinct advantages of the Bayesian model fit with `pymc3`

is the inherent quantification of uncertainty in our estimates.

##### Time varying effects

Another of the advantages of the model we have built is its flexibility. From the plots above, we may reasonable believe that the additional hazard due to metastization varies over time; it seems plausible that cancer that has metastized increases the hazard rate immediately after the mastectomy, but that the risk due to metastization decreases over time. We can accomodate this mechanism in our model by allowing the regression coefficients to vary over time. In the time-varying coefficent model, if \(s_j \leq t < s_{j + 1}\), we let \(\lambda(t) = \lambda_j \exp(\mathbf{x} \beta_j).\) The sequence of regression coefficients \(\beta_1, \beta_2, \ldots, \beta_{N - 1}\) form a normal random walk with \(\beta_1 \sim N(0, 1)\), \(\beta_j\ |\ \beta_{j - 1} \sim N(\beta_{j - 1}, 1)\).

We implement this model in `pymc3`

as follows.

```
with pm.Model() as time_varying_model:
= pm.Gamma('lambda0', 0.01, 0.01, shape=n_intervals)
lambda0
= GaussianRandomWalk('beta', tau=1., shape=n_intervals)
beta
= pm.Deterministic('h', lambda0 * T.exp(T.outer(T.constant(df.metastized), beta)))
lambda_ = pm.Deterministic('mu', exposure * lambda_)
mu
= pm.Poisson('obs', mu, observed=death) obs
```

We proceed to sample from this model.

```
with time_varying_model:
= pm.Metropolis()
step = pm.sample(n_samples, step, random_seed=SEED) time_varying_trace_
```

` [-----------------100%-----------------] 40000 of 40000 complete in 56.7 sec`

`= time_varying_trace_[burn::thin] time_varying_trace `

We see from the plot of \(\beta_j\) over time below that initially \(\beta_j > 0\), indicating an elevated hazard rate due to metastization, but that this risk declines as \(\beta_j < 0\) eventually.

```
= plt.subplots(figsize=(8, 6))
fig, ax
= np.percentile(time_varying_trace['beta'], [2.5, 97.5], axis=0)
beta_hpd = beta_hpd[0]
beta_low = beta_hpd[1]
beta_high -1], beta_low, beta_high,
ax.fill_between(interval_bounds[:=blue, alpha=0.25);
color= time_varying_trace['beta'].mean(axis=0)
beta_hat -1], beta_hat, color=blue);
ax.step(interval_bounds[:== 1) & (df.metastized == 1)]],
ax.scatter(interval_bounds[last_period[(df.event.values == 1) & (df.metastized == 1)]],
beta_hat[last_period[(df.event.values =red, zorder=10, label='Died, cancer metastized');
c== 0) & (df.metastized == 1)]],
ax.scatter(interval_bounds[last_period[(df.event.values == 0) & (df.metastized == 1)]],
beta_hat[last_period[(df.event.values =blue, zorder=10, label='Censored, cancer metastized');
c
0, df.time.max());
ax.set_xlim('Months since mastectomy');
ax.set_xlabel(
r'$\beta_j$');
ax.set_ylabel(
; ax.legend()
```

The coefficients \(\beta_j\) begin declining rapidly around one hundred months post-mastectomy, which seems reasonable, given that only three of twelve subjects whose cancer had metastized lived past this point died during the study.

The change in our estimate of the cumulative hazard and survival functions due to time-varying effects is also quite apparent in the following plots.

```
= time_varying_trace['lambda0']
tv_base_hazard = time_varying_trace['lambda0'] * np.exp(np.atleast_2d(time_varying_trace['beta'])) tv_met_hazard
```

```
= plt.subplots(figsize=(8, 6))
fig, ax
-1], cum_hazard(base_hazard.mean(axis=0)),
ax.step(interval_bounds[:=blue, label='Had not metastized');
color-1], cum_hazard(met_hazard.mean(axis=0)),
ax.step(interval_bounds[:=red, label='Metastized');
color
-1], cum_hazard(tv_base_hazard.mean(axis=0)),
ax.step(interval_bounds[:=blue, linestyle='--', label='Had not metastized (time varying effect)');
color-1], cum_hazard(tv_met_hazard.mean(axis=0)),
ax.step(interval_bounds[:=red, linestyle='--', label='Metastized (time varying effect)');
color
0, df.time.max() - 4);
ax.set_xlim('Months since mastectomy');
ax.set_xlabel(
0, 2);
ax.set_ylim(r'Cumulative hazard $\Lambda(t)$');
ax.set_ylabel(
=2); ax.legend(loc
```

```
= plt.subplots(ncols=2, sharex=True, sharey=False, figsize=(16, 6))
fig, (hazard_ax, surv_ax)
-1], tv_base_hazard, cum_hazard,
plot_with_hpd(interval_bounds[:=blue, label='Had not metastized')
hazard_ax, color-1], tv_met_hazard, cum_hazard,
plot_with_hpd(interval_bounds[:=red, label='Metastized')
hazard_ax, color
0, df.time.max());
hazard_ax.set_xlim('Months since mastectomy');
hazard_ax.set_xlabel(
0, 2);
hazard_ax.set_ylim(r'Cumulative hazard $\Lambda(t)$');
hazard_ax.set_ylabel(
=2);
hazard_ax.legend(loc
-1], tv_base_hazard, survival,
plot_with_hpd(interval_bounds[:=blue)
surv_ax, color-1], tv_met_hazard, survival,
plot_with_hpd(interval_bounds[:=red)
surv_ax, color
0, df.time.max());
surv_ax.set_xlim('Months since mastectomy');
surv_ax.set_xlabel(
'Survival function $S(t)$');
surv_ax.set_ylabel(
'Bayesian survival model with time varying effects'); fig.suptitle(
```

We have really only scratched the surface of both survival analysis and the Bayesian approach to survival analysis. More information on Bayesian survival analysis is available in Ibrahim et al.^{2} (For example, we may want to account for individual frailty in either or original or time-varying models.)

This post is available as an IPython notebook here.