In [1]:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
from matplotlib import pyplot as plt
from lifelines import CoxPHFitter
import numpy as np
import pandas as pd
This Jupyter notebook is a small tutorial on how to test and fix proportional hazard problems. An important question to first ask is: do I need to care about the proportional hazard assumption? - often the answer is no.
The proportional hazard assumption is that all individuals have the same hazard function, but a unique scaling factor infront. So the shape of the hazard function is the same for all individuals, and only a scalar multiple changes per individual.
$$h_i(t) = a_i h(t)$$At the core of the assumption is that $a_i$ is not time varying, that is, $a_i(t) = a_i$. Further more, if we take the ratio of this with another subject (called the hazard ratio):
$$\frac{h_i(t)}{h_j(t)} = \frac{a_i h(t)}{a_j h(t)} = \frac{a_i}{a_j}$$is constant for all $t$. In this tutorial we will test this non-time varying assumption, and look at ways to handle violations.
In [2]:
from lifelines.datasets import load_rossi
rossi = load_rossi()
cph = CoxPHFitter()
cph.fit(rossi, 'week', 'arrest')
Out[2]:
In [3]:
cph.print_summary(model="untransformed variables", decimals=3)
check_assumptions
New to lifelines 0.16.0 is the CoxPHFitter.check_assumptions
method. This method will compute statistics that check the proportional hazard assumption, produce plots to check assumptions, and more. Also included is an option to display advice to the console. Here's a breakdown of each information displayed:
This section can be skipped on first read. Let $s_{t,j}$ denote the scaled Schoenfeld residuals of variable $j$ at time $t$, $\hat{\beta_j}$ denote the maximum-likelihood estimate of the $j$th variable, and $\beta_j(t)$ a time-varying coefficient in (fictional) alternative model that allows for time-varying coefficients. Therneau and Grambsch showed that.
$$E[s_{t,j}] + \hat{\beta_j} = \beta_j(t)$$The proportional hazard assumption implies that $\hat{\beta_j} = \beta_j(t)$, hence $E[s_{t,j}] = 0$. This is what the above proportional hazard test is testing. Visually, plotting $s_{t,j}$ over time (or some transform of time), is a good way to see violations of $E[s_{t,j}] = 0$, along with the statisical test.
In [4]:
cph.check_assumptions(rossi, p_value_threshold=0.05, show_plots=True)
Alternatively, you can use the proportional hazard test outside of check_assumptions
:
In [5]:
from lifelines.statistics import proportional_hazard_test
results = proportional_hazard_test(cph, rossi, time_transform='rank')
results.print_summary(decimals=3, model="untransformed variables")
In the advice above, we can see that wexp
has small cardinality, so we can easily fix that by specifying it in the strata
. What does the strata
do? Let's go back to the proportional hazard assumption.
In the introduction, we said that the proportional hazard assumption was that
$$ h_i(t) = a_i h(t)$$In a simple case, it may be that there are two subgroups that have very different baseline hazards. That is, we can split the dataset into subsamples based on some variable (we call this the stratifying variable), run the Cox model on all subsamples, and compare their baseline hazards. If these baseline hazards are very different, then clearly the formula above is wrong - the $h(t)$ is some weighted average of the subgroups' baseline hazards. This ill fitting average baseline can cause $a_i$ to have time-dependent influence. A better model might be:
$$ h_{i |i\in G}(t) = a_i h_G(t)$$where now we have a unique baseline hazard per subgroup $G$. Because of the way the Cox model is designed, inference of the coefficients is identical (expect now there are more baseline hazards, and no variation of the stratifying variable within a subgroup $G$).
In [6]:
cph.fit(rossi, 'week', 'arrest', strata=['wexp'])
cph.print_summary(model="wexp in strata")
In [7]:
cph.check_assumptions(rossi, show_plots=True)
Since age
is still violating the proportional hazard assumption, we need to model it better. From the residual plots above, we can see a the effect of age start to become negative over time. This will be relevant later. Below, we present three options to handle age
.
The proportional hazard test is very sensitive (i.e. lots of false positives) when the functional form of a variable is incorrect. For example, if the association between a covariate and the log-hazard is non-linear, but the model has only a linear term included, then the proportional hazard test can raise a false positive.
The modeller can choose to add quadratic or cubic terms, i.e:
rossi['age**2'] = (rossi['age'] - rossi['age'].mean())**2
rossi['age**3'] = (rossi['age'] - rossi['age'].mean())**3
but I think a more correct way to include non-linear terms is to use splines. Both Patsy and zEpid provide functionality for splines (tutorial incoming), but let's stick with the form above.
In [8]:
rossi_higher_order_age = rossi.copy()
rossi_higher_order_age['age'] = rossi_higher_order_age['age'] - rossi_higher_order_age['age'].mean()
rossi_higher_order_age['age**2'] = (rossi_higher_order_age['age'] - rossi_higher_order_age['age'].mean())**2
rossi_higher_order_age['age**3'] = (rossi_higher_order_age['age'] - rossi_higher_order_age['age'].mean())**3
cph.fit(rossi_higher_order_age, 'week', 'arrest', strata=['wexp'])
cph.print_summary(model="quad and cubic age terms"); print()
cph.check_assumptions(rossi_higher_order_age, show_plots=True, p_value_threshold=0.05)
We see we still have potentially some violation, but it's a heck of a lot less. Also, interestingly, when we include these non-linear terms for age
, the wexp
proportionality violation disappears. It is not uncommon to see changing the functional form of one variable effects other's proportional tests, usually positively. So, we could remove the strata=['wexp']
if we wished.
The second option proposed is to bin the variable into equal-sized bins, and stratify like we did with wexp
. There is a trade off here between estimation and information-loss. If we have large bins, we will lose information (since different values are now binned together), but we need to estimate less new baseline hazards. On the other hand, with tiny bins, we allow the age
data to have the most "wiggle room", but must compute many baseline hazards each of which has a smaller sample size. Like most things, the optimial value is somewhere inbetween.
In [9]:
rossi_strata_age = rossi.copy()
rossi_strata_age['age_strata'] = pd.cut(rossi_strata_age['age'], np.arange(0, 80, 3))
rossi_strata_age[['age', 'age_strata']].head()
Out[9]:
In [10]:
# drop the orignal, redundant, age column
rossi_strata_age = rossi_strata_age.drop('age', axis=1)
cph.fit(rossi_strata_age, 'week', 'arrest', strata=['age_strata', 'wexp'])
Out[10]:
In [11]:
cph.print_summary(3, model="stratified age and wexp")
cph.plot()
Out[11]:
In [12]:
cph.check_assumptions(rossi_strata_age)
Our second option to correct variables that violate the proportional hazard assumption is to model the time-varying component directly. This is done in two steps. The first is to transform your dataset into episodic format. This means that we split a subject from a single row into $n$ new rows, and each new row represents some time period for the subject. It's okay that the variables are static over this new time periods - we'll introduce some time-varying covariates later.
See below for how to do this in lifelines:
In [13]:
from lifelines.utils import to_episodic_format
# the time_gaps parameter specifies how large or small you want the periods to be.
rossi_long = to_episodic_format(rossi, duration_col='week', event_col='arrest', time_gaps=1.)
rossi_long.head(25)
Out[13]:
Each subject is given a new id (but can be specified as well if already provided in the dataframe). This id is used to track subjects over time. Notice the arrest
col is 0 for all periods prior to their (possible) event as well.
Above I mentioned there were two steps to correct age
. The first was to convert to a episodic format. The second is to create an interaction term between age
and stop
. This is a time-varying variable.
Instead of CoxPHFitter
, we must use CoxTimeVaryingFitter
instead since we are working with a episodic dataset.
In [14]:
rossi_long['time*age'] = rossi_long['age'] * rossi_long['stop']
In [15]:
from lifelines import CoxTimeVaryingFitter
ctv = CoxTimeVaryingFitter()
ctv.fit(rossi_long,
id_col='id',
event_col='arrest',
start_col='start',
stop_col='stop',
strata=['wexp'])
Out[15]:
In [16]:
ctv.print_summary(3, model="age * time interaction")
In [17]:
ctv.plot()
Out[17]:
In the above scaled Schoenfeld residual plots for age
, we can see there is a slight negative effect for higher time values. This is confirmed in the output of the CoxTimeVaryingFitter
: we see that the coefficient for time*age
is -0.005.
The point estimates and the standard errors are very close to each other using either option, we can feel confident that either approach is okay to proceed.
You may be surprised that often you don't need to care about the proportional hazard assumption. There are many reasons why not:
If your goal is survival prediction, then you don't need to care about proportional hazards. Your goal is to maximize some score, irrelevant of how predictions are generated.
Given a large enough sample size, even very small violations of proportional hazards will show up.
There are legitimate reasons to assume that all datasets will violate the proportional hazards assumption. This is detailed well in Stensrud & Hernán's "Why Test for Proportional Hazards?" [1].
"Even if the hazards were not proportional, altering the model to fit a set of assumptions fundamentally changes the scientific question. As Tukey said, "Better an approximate answer to the exact question, rather than an exact answer to the approximate question." If you were to fit the Cox model in the presence of non-proportional hazards, what is the net effect? Slightly less power. In fact, you can recover most of that power with robust standard errors (specify
robust=True
). In this case the interpretation of the (exponentiated) model coefficient is a time-weighted average of the hazard ratio--I do this every single time." from AdamO, slightly modified to fit lifelines [2]
Given the above considerations, the status quo is still to check for proportional hazards. So if you are avoiding testing for proportional hazards, be sure to understand and able to answer why you are avoiding testing.
In [ ]: