Skip to content
ImagineWorld

Survival Models

node_idnode-book_building-statistical-models-in-python_chapter-14-survival-models
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num14
chapter_titleSurvival Models
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

In Chapter 13*, Time-to-Event Variables*, we introduced the topics of survival analysis, censoring, and time-to-event (TTE) variables. In this chapter, we will provide an in-depth overview and walkthrough of the implementation of these techniques with respect to three primary model frameworks:

  • Kaplan-Meier model
  • Exponential model
  • Cox Proportional Hazards model

We will discuss how each approach provides probabilistic insight into the survival and hazard risk of study subjects using univariate Kaplan-Meier and exponential approaches as well as the multivariate Cox Proportional Hazards regression model. We’ll walk through examples using real data and discuss the results so that the reader understands how to assess performance and translate test output into useful information. Finally, we will show how to use the trained models to provide forecast probabilities for unseen data.

In this chapter, we use an additional Python library for survival analysis: lifelines. Please install the following versions of these libraries to run the provided code. Instructions for installing libraries can be found in Chapter 1*, Sampling* and Generalization:

  • lifelines== 0.27.4

More information about lifelines can be found at this link:

https://lifelines.readthedocs.io/en/latest/index.html

The first model for survival analysis we will discuss is the Kaplan-Meier model (also called the Kaplan-Meier estimator). We will start this section with a discussion model definition and learn how it is built. Then, we will close this section with an example of how to use this model in Python using the lifelines library. Let’s get started.

The Kaplan-Meier estimator is defined by the following formula:

Here, is the number of subjects at risk just before time, is the number of death events at time, and (the survival function) is the probability that life is longer than. The symbol used in the formula is like the symbol; however, indicates multiplication. This means that the preceding formula will result in a multiplication of fractions for each time step. This means that the Kaplan-Meier estimator is a series of declining horizontal steps. To make this clear, let’s take a look at its application with some example data.

Let’s say that we have the following data, where the duration column represents how long a subject survived and the death column indicates whether a death was observed in the study. Let’s walk through the calculations for the Kaplan-Meier estimator for this data:

durationdeath
51
71
3.51
80
21
51

Figure 14.1 – Death and duration example data

Initially (at ), all subjects are at risk, but no subjects have died. That means the current survival rate is 1. We calculate the value of the survival function at as follows:

The first event occurs at. At this point, all subjects (six subjects) are at risk just before the event, and one subject dies at this time. We calculate the current survival rate at this point, then multiply this value by all the previous values. The survival rate at is given here:

Then, we calculate the survival function at:

The next event occurs at. We repeat the process as outlined previously. However, there are only five subjects at risk at this point since one has already died. Thus, the current survival rate at time is this:

Then, we calculate the survival function at this point:

The next event occurs at, where two subjects die. At, there are four remaining subjects at risk, and two subjects die. Thus, we have a survival rate of 0.5 at. The new value of the survival function is calculated as follows:

The final event occurs at. At this point, the survival rate is 0.5 and the value of the survival function at this point is approximately 0.167:

Since our study ends here, this is the final value of the survival function, and the function value remains constant through the end of the study.

As you can see, this survival model is simple to calculate. Notice also that we did not mention assumptions or underlying statistical distributions. The Kaplan-Meier estimator is a nonparametric survival model. As we discussed in Chapter 5*, Non-Parametric Tests*, this means it can be used as an alternative to parametric models when the data under analysis does not meet the assumptions of parametric models. The Kaplan-Meier estimator is a useful model to have in your tool belt for that reason.

Now that we have had a walkthrough of how this model works, let’s look at how to calculate the Kaplan-Meier estimator survival function with the lifelines package in Python.

For this example, we will use the larynx dataset from lifelines. This dataset consists of six variables: time, age, death, Stage_II, Stage_III, and Stage_IV. The information for this dataset is limited, so we will make the following assumptions about the variables for the purposes of this example:

  • time is the amount of time a patient lived after diagnosis of larynx cancer
  • age is the age of the patient at the time of diagnosis
  • death indicates whether the death was observed during the study
  • Stage_II indicates that the cancer was at stage two at the time of diagnosis
  • Stage_III indicates that the cancer was at stage three at the time of diagnosis
  • Stage_IV indicates that the cancer was at stage four at the time of diagnosis
  • When a patient is not indicated in stage two or above, they were in stage one at the time of diagnosis

Let’s start by calculating the survival function of all the patients in the study. We will use KaplanMeierFitter from lifelines. This is an object that will be the Kaplan-Meier model we just discussed. To fit this model, we will use the fit() method, which takes two arguments: duration and event_observed. duration is how long the patient lived in the study. event_observed is whether the death was observed: True for observed and False for not observed. The data is already set up to work with these two arguments. We can fit the model as follows:

import matplotlib.pyplot as plt
from lifelines import datasets
from lifelines.fitters.kaplan_meier_fitter import KaplanMeierFitter
data = datasets.load_larynx()
kmf = KaplanMeierFitter()
kmf.fit(data.time, data.death)
# this prints the first 5 elements of the survival function
kmf.survival_function_.head()

The output of the preceding code is shown in Figure 14*.2*, which is the first five elements of the survival function:

Figure 14.2 – First five elements of the larynx survival function

The elements of the survival function shown in Figure 14*.2* are slowly decreasing, which is indicative of patients dying over time. However, it’s difficult to get the full story from a series of numbers. Let’s plot this series. We can also get the confidence intervals from the KaplanMeierFitter object, as shown in the next code block:

fig, ax = plt.subplots(1)
kmf.survival_function_.plot(ax=ax)
ci = kmf.confidence_interval_survival_function_
index = ci.index
ci_low, ci_high = ci.values[:, 0], ci.values[:, 1]
ax.fill_between(index, ci_low, ci_high, color='gray', alpha=0.3)

This code results in the plot shown in Figure 14*.3*, which is the survival function over time:

Figure 14.3 – Larynx survival function using Kaplan-Meier estimation

The Kaplan-Meier estimator survival function for the larynx data is shown in Figure 14*.3*. This function decreases over time until the last observed death at time step 8 where the function remains constant until the end of the study.

Now, consider we have a few features in this dataset that we may want to compare. For example, we have the stages of cancer at the initial diagnosis, and we have the ages of the individuals. Let us start by comparing the survival functions of two age groups. Then, let us compare the survival functions of groups based on the cancer stage.

The ages of individuals in the study range from about 40 to 85, with the bulk of the individuals in the range of 60 to 80 years old. Let’s split the individuals into groups at the age of 65. Anyone younger than 65 will be in the younger group, and anyone 65 or older will be in the older group. The survival functions for the two groups are shown in Figure 14*.4*:

Figure 14.4 – Larynx survival functions for older and younger groups

The survival functions for the older and younger group shown in Figure 14*.4* appear to exhibit little difference until around time step 7. However, the confidence intervals never appear to diverge. It appears that age does not appear to be a strong factor for survival based on this data.

Now, let’s do a similar survival analysis with the various stages. As mentioned previously, we will assume that any individual that is not indicated in stage two or above was diagnosed as stage one. The survival functions for these groups are shown in Figure 14*.5*:

Figure 14.5 – Larynx survival functions based on stage

The survival functions for the groups based on stage are shown in Figure 14*.5*. This plot omits the confidence intervals for plot clarity. Based on the plot, there does not appear to be a significant difference between stage one and stage two. We start to see a difference at stage three. The difference between stage four and the other stages is distinctly noticeable.

In this section, we discussed the Kaplan-Meier model for survival, which is a nonparametric model for survival data. We also discussed how to compare the survival functions of multiple groups within a set. In the next section, we will discuss the exponential model, which is a parametric model for survival data.

In the last section, we studied the non-parametric Kaplan-Meier survival model. We will now bridge parametric modeling with the exponential model and then will discuss a semi-parametric model, the Cox Proportional Hazards model, in the next section. Before considering the exponential model, we will review what the exponential distribution is and why we mention it in this section. This distribution is based on the Poisson process. Here, events occur independently over time and the event rate,, is calculated by the number of occurrences per unit of time, as follows:

The Poisson distribution is a statistical discrete distribution concerning the number of events occurring in a specified time period. It is defined as follows. Let Y be the number of occurrences in time t. follows the Poisson distribution with parameter if a probability mass function is given by the following formula:

The mean and the variance of the discrete variable are equal to the event rate. Instead of focusing on how many events occur in a specific time period, we can think about how long the event occurs; that’s why the exponential distribution is considered in this section. Let be the time until the event occurs. The probability density function is calculated by the following formula:

And the cumulative distribution function is calculated as follows:

The function represents the probability of not surviving past time or the probability that survival time is less than. We can see in Figure 14*.6* the following probability form:

Figure 14.6 – Curve of the probability of not surviving past time t

In contrast, the survival function is related to the probability of surviving past a certain time:

By visualization, the survival function will have the form seen in Figure 14*.7*:

Figure 14.7 – Curve of the survival function

The accumulated hazard function is. We can then we can rewrite the survival function in terms of the hazard function as follows:

Given and, we can use the idea of the log-likelihood equation approach and estimate the value for via maximum likelihood estimation.

We will use the same larynx dataset from lifeline as in the last section. In this example, we will use ExponentialFitter from lifelines. Similarly, the fit() method takes two arguments: duration and event_observed. We can fit the model as follows:

from lifelines import ExponentialFitter
from lifelines import datasets
data = datasets.load_larynx()
exf = ExponentialFitter()
exf.fit(data.time, data.death)
# this print the first 5 elements of the survival function
exf.survival_function_.head()

In the Kaplan-Meier model, the curve looks like stair steps, but using the exponential approach, the curve is gradually decreasing continuously, as we can see here:

Figure 14.8 – Larynx survival function using exponential distribution

At time step 8, the function remains constant until the end of the study in the Kaplan-Meier model, but in the exponential model, the curve continues to decrease until the end of the study. We also perform similar studies between the younger group (less than 65 years old) and the older group (from 65 years old) (see Figure 14*.9*):

Figure 14.9 – Larynx survival functions for older and younger groups

We also do this on survival analysis with the various stages in the Larynx case (see Figure 14*.10*):

Figure 14.10 – Larynx survival functions based on stage

Both the exponential and Kaplan-Meier models give us similar information. There are advantages and disadvantages between the two models. In the Kaplan-Meier model, results interpretation is simpler; we can estimate the survival function value for both models, but one advantage of the exponential model is to be able to estimate the hazard ratio. Two disadvantages of exponential models are that results are not always realistic and that we must assume a constant hazard ratio, which is not always practical. In the next section, we will discuss another survival model, the Cox Proportional Hazards regression model, which is semi-parametric.

Survival analysis, also called TTE analysis, as we discussed in Chapter 13*, Time-to-Event Variables*, is an analytical approach that uses probability to estimate the time remaining before an event occurs based on previous observations. We have seen how this can be helpful when including appropriate covariates in applications such as estimating life expectancy, mechanical failure, and customer churn, which can help with prioritizing needs and to more efficiently allocate resources. As we discussed in depth in Chapter 13, censoring is an aspect making survival analysis unique from other statistical questions that can be solved using techniques such as regression. Consequently—and because dropping an observation due to censoring will almost certainly mislead our model and provide results we cannot trust—we insert what is known as an event status indicator to help account for whether an event will occur or fail to occur prior to estimating the time before an event’s occurrence. Recall that the event status indicator,, for object is described as follows:

We noted that when the true event occurs before censoring time and when the true event occurs after censoring time and that thus, the outcome for object is this:

Censored survival data for object can be captured as In this chapter, we have discussed the non-parametric Kaplan-Meier survival model, which uses a raw conditional probability of survival counts respective to the sample volume at each point in time without consideration of covariates. We then walked through the parametric exponential survival model, which, unlike the Kaplan-Meier model assumes the data fits specific distributions and additionally includes a hazard ratio to compare groups. We will now discuss the semi-parametric Cox Proportional Hazards survival model, also referred to as the Cox Proportional Hazards regression model.

The primary purpose and distinction of the Cox Proportional Hazards model is to use multiple covariates risk factors to model survival time. These covariates can be categorical or continuous. The Cox Proportional Hazards model is able to account for differences in survival between groups by leveraging the hazard ratio. As we have discussed, the hazard ratio is the ratio of the event rate, at any point in time, for one group with respect to another group provided that survival up to that point in time has been maintained among the two groups.

The hazard ratio can be calculated as follows:

The issue with the hazard ratio is that when we fail to obtain a balance of values across covariates shared among the groups, we lose control of confounding variables. When we cannot control for confounding variables, we cannot reliably obtain inference. To account for any imbalance that may exist among covariate values in survival analysis, we can use the Cox Proportional Hazards model to introduce coefficients that help explain different levels of exogenous influence. The model follows this form:

Here, is the expected hazard value at the base time, t, is the baseline hazard value at t when all covariates in the variable matrix X are equal to zero, and n is the count of variables included in the model. The coefficients provide quantification into the impact (effect) of each columnar variable in X. Therefore, we are able to predict survival using the specific values of the input variables multiplied against their corresponding estimated coefficients.

Cox Proportional Hazards has three pertinent assumptions:

  • It is assumed the hazard ratio remains constant through follow-up. If the nature of input for one group is subject to change, this may negatively influence the results of the model; for example, we compare the performance of two machines, but one is likely to improve when the weather is warmer and the other is not, so our model may not be able to properly model mechanical survival.
  • Complete survival independence. This means the survival of one study participant or object has no dependence on the other. Consider two separate machines. If one’s vibrations are likely to result in an early failure that would not otherwise occur, and that vibration is additionally felt by the other machine, also at that other machine’s detriment, there may not be survival independence between the two machines. However, if the vibration of the first machine is not felt by the other, there is likely to be survival independence if all other confounders are controlled for.
  • The model assumes any censoring that takes place is non-informative. As such, any censoring that takes place does not introduce confounding into the model. Losing a study subject due to censoring prior to follow-up must not be correlated to changes in survival risk. For example, when testing the mechanical survival of two types of machines in a specific area of a facility, if one machine is relocated to another area of the facility to minimize its own self-destructive vibrations, this is informative censoring. However, if the machine was moved to a different area simply to make space and the move does not impact the machine’s survival risk or outcome, the censoring is non-informative. Therefore, it does not introduce model confounding. The Cox Proportional Hazards model is for right-censored data.

The steps to be taken when performing Cox Proportional Hazards regression modeling are outlined next. The sequence is important as the test should only be performed when practical. These steps follow the outline provided by the National Institutes of Health (NIH) (https://www.ncbi.nlm.nih.gov/pmc/articles/PMC7876211/).

Set up the null hypothesis to be tested (hypotheses in the multivariate case, which we will look at). We will use the Stanford heart transplant dataset, which lists the survival of the patients waiting for transplants in the Stanford heart transplant program. We will use age and year with respect to the start date of the program, transplant status, and the existence of previous bypass surgery as predictors for survival, which ends in either death or transplant. Survival duration is the stop variable, which is the exit time of the study. event is the variable confirming right-censoring and corresponds to either death or transplant. The null hypothesis for each variable is that there is no statistically significant difference in survival between the groups. For example, age has no impact on survival, while awaiting transplant would be the null hypothesis. The code is shown in the following snippet:

import statsmodels.api as sm
data = sm.datasets.get_rdataset('heart', package='survival').data
train_data = data.iloc[0:171]
test_data = data.iloc[171:]
exog=train_data[['age','year', 'transplant','surgery']]#df_test[['age','year','surgery','transplant']]
endog=train_data['stop']
data.head(2)

Two additional aspects of our data to be aware of are (1) that age has negative values; the starting age value is 48 years old, so an age of -1 corresponds to a 47-year-old patient and (2) year starts November 1, 1967. id is unique to each patient’s identification. We will not model this variable but can use it for reference. In Figure 14*.11* we can see, for reference, the first two rows of the data, including all variables we will use to model survival:

startstopEventAgeyearsurgerytransplantid
0501-17.15540.123203001
0613.8357290.25462002

Figure 14.11 – First two rows of the Stanford Heart Transplant data set

We estimate the survival function using a Kaplan-Meier estimate, which accounts for right-censoring in the data. In our example, right-censoring occurs when the event variable is equal to one. We can see 171 enter at point 0. On the first day (stop=1), corresponding to index column event_at equal to 1, we have right-censoring for three patients. We observed the event take place for one patient (observed=1) and the other two patients were censored. Here, we show the corresponding data. The patient with id=45 stops but restarts the same day, then survives until day 45. We see the same for patient id=3, who survives until day 16 when they receive a transplant. The patient with id=15 does not re-enter for follow-up; we assume since they did not receive a transplant, they did not survive.

In the following code sample, the durations variable corresponds to survival time and event_observed corresponds to the event (transplant or death) that results in right-censoring:

from lifelines import KaplanMeierFitter
import matplotlib.pyplot as plt
KaplanMeierFitter = KaplanMeierFitter()
KaplanMeierFitter.fit(durations=train_data['stop'], event_observed=train_data['event'])
KaplanMeierFitter.event_table.reset_index()

Note from the Kaplan-Meier results that event=1 with stop=1 results in observed=1, whereas event=0 with stop=1 results in censored=1 and stop=1 results in removed=1. All three conditions result in those corresponding samples being removed from the calculation for that day’s calculation, but unlike the patient who experienced the event, those who were censored are considered to survive at least as long as the study continues. We can see this by considering the Kaplan-Meier survival estimation probability function,:

Here, survival probability at any time, t, is denoted as.

In looking at our event table from the KaplanMeierFitter function, we have the following:

We can understand that a removed patient has limited impact on survival estimations unless they were also noted as observed=1, which we can ascribe to event=1.

Let’s consider patients 3, 15, and 45 to understand this relationship better. We can see based on counts in Figure 14*.12* and Figure 14*.13* that these patients were removed from the denominator on day 1 (event_at=1). However, by looking at Figure 14*.14*, we can see patients 15 and 45 have later stops corresponding to events that get factored into the survival function. Let’s look at Figure 14*.12* first so we can see the three removed patients on day 1:

event_atremovedobservedcensoredentranceat_risk
00000171171
113120171
226330168
336330162
442020156
…………………
107140110105
108140810104
109157210103
110158710102
111180010101

Figure 14.12 – Summary of the events table for the Stanford Heart Transplant data set

Now, we can see in Figure 14*.13* all patients that had stops on day 1.

train_data.loc[train_data['stop']==1]

The patients with stops on day 1 are patients with id 3, 15, and 45:

startStopeventAgeYearsurgerytransplantid
0106.2970570.265572003
0115.8151950.9911021015
010-11.81663.2635180045

Figure 14.13 – Training data values for patients who exited the study on day 1

To get a better understanding of how this analysis works, we can look specifically at all records for the patients having id 3, 15, and 45:

train_data.loc[train_data['id'].isin([3, 15,45])]

These patients registered a stop on day 1, but patients 3 and 45 also registered stops on days 16 and 45, respectively:

startstopeventAgeyearsurgerytransplantid
0106.2970570.265572003
11616.2970570.265572013
0115.8151950.9911021015
010-11.81663.2635180045
1451-11.81663.2635180145

Figure 14.14 – Training data values for patients 3, 15, and 45

We can also see patient 45 is the only patient with a stop value (corresponding to event_at) on day 45. Therefore, we know a transplant results in an observation and a removal. To identify the values at day 45, run the following code:

KaplanMeierFitter.event_table.loc[KaplanMeierFitter.event_table.index==45.0]

The code outputs the table in Figure 14*.15*:

event_atremovedobservedcensoredentranceat_risk
45110087

Figure 14.15 – Events on day 45

Now we can look at the events table filtered to events with a stop at day 45 by running the following code:

train_data.loc[train_data['stop']==45]

This gives us the tabular output seen in Figure 14*.16*:

startstopeventAgeyearsurgerytransplantid
1451-11.81663.2635180145

Figure 14.16 – Events having a stop on day 45

We can repeat this step to see if there is a difference in survival until the end of the study for those who receive a transplant and those who do not by splitting the two groups out in the following code:

from lifelines import KaplanMeierFitter
import matplotlib.pyplot as plt
KaplanMeierFitter_n = KaplanMeierFitter()
KaplanMeierFitter_y = KaplanMeierFitter()
KaplanMeierFitter_n.fit(durations=data.loc[data['transplant']==0]['stop'], event_observed=data.loc[data['transplant']==0]['event'], label='no transplant')
KaplanMeierFitter_y.fit(durations=data.loc[data['transplant']==1]['stop'], event_observed=data.loc[data['transplant']==1]['event'], label='transplant');

We observe in the Kaplan-Meier survival function in Figure 14*.17* a steady decrease in survival probability for both groups, but a steeper decrease for the group that does not receive a transplant. We can also see the group, overall, with no transplant does not survive if the group that does receive the transplant. By the time the program closed, there were no non-transplants surviving. The shading corresponds to the 95% confidence interval bands for each probability interval:

Figure 14.17 – Kaplan-Meier survival estimation probability function

To generate the exact probability of survival on any day (corresponding to the stop time), we can run the following code:

print('Non-Transplant Survival Probability at day 300: ', KaplanMeierFitter_n.predict(300))
print('Transplant Survival Probability at day 300: ', KaplanMeierFitter_y.predict(300))

Here we can see the probabilities of survival at day 300 for the transplant and non-transplant groups:

Non-Transplant Survival Probability at day 300: 0.3545098269168237
Transplant Survival Probability at day 300: 0.4911598783770023

Now, we will use a log-rank test to determine if survivor curves are statistically different. At this step, we investigate if there is any statistical significance in survival between transplant and non-transplant groups. If there is no statistical significance, it would not be useful to understand the relationships between the covariates and their impacts on survival. We looked at contingency table analysis using the Chi-Square test of independence earlier in the book. This is essentially the log-rank test here, where we compare the survival distributions of the two groups (transplant versus non-transplant). We use this approach because the data is right-censored, and thus right-skewed; as such, we are working with non-parametric distributions. The null hypothesis is that the hazard ratio between the two groups is equal to 1, which would mean they are equal in terms of survival or hazard risk.

In the following code sample, we use the two different patient distributions (those with and those without transplants) as groups A and B in the logrank_test function:

from lifelines.statistics import logrank_test
lr_results = logrank_test(durations_A=data.loc[data['transplant']==0]['stop'],
durations_B=data.loc[data['transplant']==1]['stop'],
event_observed_A=data.loc[data['transplant']==0]['event'],
event_observed_B=data.loc[data['transplant']==1]['event'])

We can see the Chi-Square distribution is used:

print(lr_results.null_distribution)

This shows the default distribution is the chi-square distribution:

chi squared

We can run the following code to see the results of the test:

lr_results.summary

We can also see a statistically significant difference at a 5% level of significance between the two groups. Therefore, we can assume there is a purpose in proceeding to use the Cox Proportional Hazards model to understand the relationships between the covariates we outlined earlier and the hazard risk for survival:

test_statisticP- log2(p)
4.026510.0447914.480663

Figure 14.18 – Log-rank test results

Here, we run the Cox Proportional Hazards test and analyze the p-values and confidence intervals for the terms included to identify whether they have statistical significance with respect to influence on survival rate. We look at the hazard ratio to determine any effects they have provided:

from lifelines import CoxPHFitter
CoxPHFitter = CoxPHFitter()
CoxPHFitter.fit(df=train_data[['age','year','surgery','transplant','stop','event']], duration_col='stop', event_col='event')
CoxPHFitter.print_summary()

We can see three of our four terms are significant at the 5% level of significance for predicting survival; our surgery variable does not appear to be based on the p-value. The 95% confidence interval for surgery does not contain 0, however, which suggests statistical significance. The difference is because the p-value is calculated based on the test statistic with respect to the critical value, which is estimated using the log of the hazard ratio, and the confidence interval is based on the hazard ratio itself. This discrepancy could mean the surgery variable is significant, but also that it may not be. Since we are not statistically certain, we should err on the side of caution and not consider it useful when predicting future survival.

Note that exp(coef) corresponds to the hazard ratio and coef is the log of the hazard ratio. This follows the equation we provided earlier for the expected hazard value at the base time, t.

We can say, based on the hazard ratio (exp(coef)) of 1.03, that a single unit increase in age over age 48 results in an increase of the hazard by a factor of 1.03, or 3%. With respect to our transplant variable, we can say with a 95% level of confidence that having the heart transplant decreased the hazard by a factor of 0.54, which is equivalent to 46%.

Here in Figure 14*.19*, we can see the results of the Cox Proportional Hazards regression model:

Model

lifelines.CoxPHFitter

Duration column

stop

Event column

event

Baseline estimation

breslow

Number of observations

171

Number of events observed

74

Partial log likelihood

-298.47

Time fit was run

2023-03-18 16:23:26 UTC

coef

exp (coef)

se (coef)

coef lower 95%

coef upper 95%

exp (coef) lower 95%

exp (coef) upper 95%

cmp to

z

p

-log2 (p)

Age

0.03

1.03

0.01

0.01

0.06

1.01

1.06

0

2.35

0.02

5.74

Year

-0.16

0.85

0.07

-0.3

-0.02

0.74

0.98

0

-2.25

0.02

5.35

Surgery

-0.64

0.53

0.37

-1.36

0.08

0.26

1.08

0

-1.74

0.08

3.62

Transplant

-0.62

0.54

0.27

-1.15

-0.08

0.32

0.92

0

-2.26

0.02

5.41

Concordance

0.67

Partial AIC

604.95

Log-likelihood ratio test

21.22 on 4 df

-log2(p) of ll-ratio test

11.77

Figure 14.19 – Cox Proportional Hazard model output

In Figure 14*.20*, we can see age, which applies only a 3% increase in hazard, does not explain much of the variance in the results. The age range spans roughly 9 years through 64 years of age. Without other covariates, we cannot say exactly why this might be, but including more covariates could prove helpful in understanding this variable more. Of the significant variables, transplant has notably the largest impact on survival outcomes:

plt.title('Coefficients within Confidence Intervals')
CoxPHFitter.plot()

Figure 14.20 – Confidence intervals for hazard-ratio terms

We can see the assumption of a constant hazard ratio between all patients in the survival function plot in Figure 14*.21*. This is why it is important to prevent informative censoring. Let us assume this assumption is met.

Note that when predicting, we do not have start and stop times. Therefore, we can input only the quantifiable covariates for a given patient, as follows:

CoxPHFitter.predict_survival_function(train_data[['age','year','surgery','transplant']]).plot()
plt.xlabel('Survival Time')
plt.ylabel('Survival Probability')
plt.title('Survival Function for All Patients')
plt.legend().set_visible(False)

Figure 14.21 – Survival function for all patients

In Figure 14*.22*, we can use the Cox Proportional Hazards model to predict the survival function for our held-out test patient:

CoxPHFitter.predict_survival_function(test_data[['age','year','surgery','transplant']]).plot()
plt.xlabel('Survival Time')
plt.ylabel('Survival Probability')
plt.title('Survival Function for Holdout')

Figure 14.22 – Survival function for test patient, id=171

To generate the probability for this patient’s survival, using their covariates, at each potential stop point, we can run the following code:

CoxPHFitter.predict_survival_function(test_data[['age','year','surgery','transplant','stop','event']])

In this chapter, we discussed three survival analysis models in depth; the Kaplan-Meier, the exponential, and the Cox Proportional Hazards regression models. Using these frameworks, we modeled survival functions and estimated survival probabilities and hazard ratios for various TTE, right-censored studies. For the multivariate case, we used Cox Proportional Hazards regression to model hazard ratios for covariate analysis on dependent variables. For all models, we demonstrated using the confidence intervals for assessing significance, as well as the corresponding p-values. At this point, the reader should be able to confidently identify the scenarios in which each model would outperform the others and appropriately fit and implement that model to obtain the necessary results for strategic success.