Survival Analysis: Kaplan-Meier, Cox Regression & Applications
1. Introduction to Survival Analysis
Survival Analysis is a statistical method used to analyze the time until a particular event occurs.
Unlike traditional regression, which predicts a numerical value, survival analysis focuses on the duration until an event happens.
The event can represent:
- Time until a patient recovers from a disease.
- Time until a customer cancels a subscription.
- Time until a machine component fails.
- Time until a loan defaults.
- Time until an employee leaves an organization.
- Time until a product requires maintenance.
For example, imagine a hospital wants to understand how long patients survive after receiving a particular treatment.
The hospital collects information about patients, including their treatment dates, follow-up periods, and whether the event of interest occurred.
Survival analysis helps answer questions such as:
- What proportion of patients are expected to survive for one year?
- How does survival probability change over time?
- Does a treatment improve survival?
- Which factors increase the risk of an event?
- How long might a machine operate before failure?
The main objective is to understand and model the time until an event occurs.
2. Important Concepts in Survival Analysis
Before exploring survival models, it is important to understand a few fundamental concepts.
2.1 Event
An event is the outcome being studied.
Examples:
- Death in a medical study.
- Customer churn in subscription analytics.
- Machine failure in reliability engineering.
- Loan default in banking.
The event definition must be clear before building a model.
2.2 Survival Time
Survival time represents the duration between the beginning of observation and the occurrence of the event.
For example:
| Patient | Start Date | Event Date | Survival Time |
|---|---|---|---|
| A | January 1 | March 1 | 59 days |
| B | January 1 | April 1 | 90 days |
| C | January 1 | May 1 | 120 days |
In practice, some individuals may not experience the event during the study period. This introduces an important concept called censoring.
2.3 Censoring
Censoring occurs when the exact event time is not observed for an individual.
The most common type is right censoring.
For example:
A hospital follows a patient for 12 months. The patient is still alive at the end of the study.
The hospital knows that the patient's survival time is greater than 12 months, but the exact future event time is unknown.
This observation is right-censored.
Other types include:
- Left censoring: The event occurred before the observation period, but its exact time is unknown.
- Interval censoring: The event occurred within a known interval, but its exact time is unknown.
Survival analysis is especially useful because it can incorporate censored observations rather than simply discarding them.
2.4 Survival Function
The survival function describes the probability that an individual survives beyond a particular time.
It is represented as:
\[ S(t)=P(T>t) \]
Where:
- \(S(t)\): Survival probability at time \(t\).
- \(T\): Random variable representing event time.
- \(t\): Time point.
For example:
If:
\[ S(12)=0.85 \]
This means the estimated probability of remaining event-free beyond 12 months is 85%.
The meaning of survival depends on the event being studied. In customer analytics, it may mean remaining subscribed rather than being alive.
2.5 Hazard Function
The hazard function measures the instantaneous event rate at time \(t\), conditional on the individual having remained event-free until that time.
It is represented as:
\[ h(t)=\lim_{\Delta t\to0} \frac{ P(t\leq T<t+\Delta t\mid T\geq t) }{ \Delta t } \]
A higher hazard indicates a higher instantaneous event rate among individuals still at risk.
For example:
A machine may have a low failure hazard during its first year but a higher hazard after several years of operation.
2.6 Cumulative Hazard Function
The cumulative hazard function measures the accumulated hazard over time.
\[ H(t)=\int_0^t h(u)\,du \]
For a continuous survival distribution:
\[ S(t)=e^{-H(t)} \]
The survival function and hazard function provide different but related perspectives on event timing.
3. Types of Survival Analysis Models
There are several approaches to survival analysis.
The most important methods include:
- Kaplan-Meier Estimator.
- Log-Rank Test.
- Cox Proportional Hazards Regression.
- Parametric Survival Models.
- Advanced Machine Learning Survival Models.
Let's understand the first three in detail.
4. Kaplan-Meier Estimator
What Is the Kaplan-Meier Estimator?
The Kaplan-Meier estimator is a non-parametric statistical method used to estimate the survival function from observed event times.
It is also known as the product-limit estimator.
It does not require the user to assume a particular probability distribution for survival times.
The Kaplan-Meier estimator is especially useful when the dataset contains censored observations.
4.1 Kaplan-Meier Formula
The Kaplan-Meier survival estimate is:
\[ \hat{S}(t)= \prod_{t_i\leq t} \left( 1-\frac{d_i}{n_i} \right) \]
Where:
- \(\hat{S}(t)\): Estimated survival probability.
- \(t_i\): Observed event time.
- \(d_i\): Number of events at time \(t_i\).
- \(n_i\): Number of individuals at risk immediately before \(t_i\).
The estimator multiplies the conditional probability of surviving each observed event time.
4.2 Understanding with an Example
Consider a study involving five patients.
| Patient | Follow-up Time (Months) | Event Observed |
|---|---|---|
| A | 2 | Yes |
| B | 3 | No |
| C | 4 | Yes |
| D | 5 | Yes |
| E | 6 | No |
Here:
- Yes means the event occurred.
- No means the observation was censored.
At month 2:
- Five patients are initially at risk.
- One event occurs.
\[ S(2)=1-\frac{1}{5}=0.8 \]
At month 3, patient B is censored. No event occurs, so the survival estimate remains unchanged.
At month 4:
- Three patients remain at risk.
- One event occurs.
\[ S(4)=0.8\times \left(1-\frac{1}{3}\right) \]
\[ S(4)=0.5333 \]
At month 5:
- Two patients remain at risk.
- One event occurs.
\[ S(5)=0.5333\times \left(1-\frac{1}{2}\right) \]
\[ S(5)=0.2667 \]
The estimated survival probability decreases whenever an event occurs. Censoring changes the risk set but does not directly cause a downward step in the survival curve.
4.3 Kaplan-Meier Survival Curve
A Kaplan-Meier curve displays estimated survival probability against time.
Its key characteristics are:
- The curve starts at 1.0, representing 100% survival at the beginning.
- It decreases at observed event times.
- It remains flat between events.
- Censored observations are often marked with small ticks.
- It never increases.
The curve helps researchers understand how survival probability changes throughout the observation period.
4.4 Kaplan-Meier Implementation in Python
We can implement Kaplan-Meier estimation using the lifelines library.
Install the required libraries:
pip install lifelines pandas matplotlib
Import the libraries:
import pandas as pd
import matplotlib.pyplot as plt
from lifelines import KaplanMeierFitter
Create a sample dataset:
data = pd.DataFrame({
"duration": [2, 3, 4, 5, 6],
"event": [1, 0, 1, 1, 0]
})
print(data)
Here:
durationrepresents observed follow-up time.event = 1means the event occurred.event = 0means the observation was censored.
Fit the Kaplan-Meier model:
kmf = KaplanMeierFitter()
kmf.fit(
durations=data["duration"],
event_observed=data["event"],
label="Patient Survival"
)
print(kmf.survival_function_)
Plot the survival curve:
kmf.plot_survival_function(
ci_show=True
)
plt.title("Kaplan-Meier Survival Curve")
plt.xlabel("Time (Months)")
plt.ylabel("Survival Probability")
plt.grid(True)
plt.show()
The plot displays the estimated survival probability and its confidence interval.
4.5 Comparing Two Groups with Kaplan-Meier
Suppose a hospital wants to compare survival between patients receiving Treatment A and Treatment B.
data = pd.DataFrame({
"duration": [2, 3, 4, 5, 6, 3, 4, 5, 7, 8],
"event": [1, 0, 1, 1, 0, 1, 1, 0, 1, 0],
"treatment": [
"A", "A", "A", "A", "A",
"B", "B", "B", "B", "B"
]
})
Fit separate Kaplan-Meier curves:
kmf = KaplanMeierFitter()
for group in ["A", "B"]:
group_data = data[
data["treatment"] == group
]
kmf.fit(
group_data["duration"],
group_data["event"],
label=f"Treatment {group}"
)
kmf.plot_survival_function()
plt.title("Survival Comparison: Treatment A vs B")
plt.xlabel("Time")
plt.ylabel("Survival Probability")
plt.grid(True)
plt.show()
This visualization helps compare the estimated survival patterns of both groups.
However, a visual difference alone does not establish statistical significance or prove that a treatment caused better outcomes.
5. Log-Rank Test
What Is the Log-Rank Test?
The Log-Rank Test is a statistical hypothesis test used to compare survival distributions between two or more groups.
For example:
- Treatment A vs Treatment B.
- Male vs Female patients.
- High-risk vs Low-risk customers.
- Different machine types.
It evaluates whether the observed survival curves differ more than would be expected under the null hypothesis.
5.1 Hypotheses
The null hypothesis is:
\[ H_0:S_1(t)=S_2(t) \]
The alternative hypothesis is:
\[ H_1:S_1(t)\neq S_2(t) \]
A small p-value provides evidence against the null hypothesis.
A p-value below a chosen significance level, such as 0.05, is often treated as statistically significant.
5.2 Log-Rank Test in Python
from lifelines.statistics import logrank_test
group_a = data[data["treatment"] == "A"]
group_b = data[data["treatment"] == "B"]
results = logrank_test(
group_a["duration"],
group_b["duration"],
event_observed_A=group_a["event"],
event_observed_B=group_b["event"]
)
print(results.summary)
Important output:
- Test statistic.
- Degrees of freedom.
- p-value.
The log-rank test is most sensitive to differences that are reasonably consistent over time. If survival curves cross substantially, other comparison methods may be more informative.
6. Cox Proportional Hazards Regression
What Is Cox Regression?
Cox Proportional Hazards Regression is a semi-parametric survival analysis model developed by statistician David Cox.
It is used to investigate how different variables influence the hazard of an event.
Unlike the Kaplan-Meier estimator, Cox regression can incorporate multiple explanatory variables.
Examples include:
- Age.
- Gender.
- Treatment type.
- Blood pressure.
- Disease stage.
- Customer usage.
- Loan characteristics.
The model estimates the relationship between these variables and the event hazard.
6.1 Cox Regression Formula
The Cox Proportional Hazards model is:
\[ h(t|X)=h_0(t)e^{\beta_1X_1+\beta_2X_2+\cdots+\beta_pX_p} \]
Where:
- \(h(t|X)\): Hazard for an individual with predictors \(X\).
- \(h_0(t)\): Baseline hazard.
- \(X_1,\ldots,X_p\): Predictor variables.
- \(\beta_1,\ldots,\beta_p\): Estimated coefficients.
- \(p\): Number of predictors.
The baseline hazard is left unspecified, which makes the Cox model semi-parametric.
6.2 Understanding Hazard Ratios
The hazard ratio is one of the most important outputs of Cox regression.
For a one-unit increase in a predictor, holding other variables constant:
\[ HR=e^\beta \]
Interpretation:
| Hazard Ratio | Interpretation |
|---|---|
| HR = 1 | No change in hazard |
| HR greater than 1 | Higher hazard |
| HR less than 1 | Lower hazard |
For example:
If a predictor has:
\[ HR=1.5 \]
The estimated hazard is 50% higher for a one-unit increase in that predictor, assuming the proportional hazards model is appropriate.
If:
\[ HR=0.7 \]
The estimated hazard is 30% lower for a one-unit increase.
A hazard ratio is not the same as a ratio of survival probabilities or a percentage change in survival time.
6.3 Cox Regression Implementation in Python
Create a sample dataset:
import pandas as pd
data = pd.DataFrame({
"duration": [
5, 8, 12, 4, 10,
15, 7, 9, 14, 6
],
"event": [
1, 0, 1, 1, 0,
1, 1, 0, 1, 1
],
"age": [
45, 50, 60, 35, 55,
65, 40, 48, 70, 38
],
"treatment": [
1, 0, 1, 0, 1,
1, 0, 1, 0, 0
]
})
Install and import the Cox model:
pip install lifelines
from lifelines import CoxPHFitter
cph = CoxPHFitter()
cph.fit(
data,
duration_col="duration",
event_col="event"
)
cph.print_summary()
The output includes:
- Regression coefficients.
- Hazard ratios.
- Standard errors.
- Confidence intervals.
- p-values.
This is a small illustrative dataset. Meaningful clinical or business conclusions require substantially more observations, appropriate covariates, and model diagnostics.
6.4 Visualizing Cox Regression Results
cph.plot()
plt.title("Cox Regression Coefficients")
plt.show()
The coefficient plot helps identify the direction and estimated strength of relationships between predictors and hazard.
6.5 Checking the Proportional Hazards Assumption
The Cox model assumes that hazard ratios remain constant over time.
In other words, the relative hazard between individuals with different predictor values should not systematically change over the observation period.
This is known as the Proportional Hazards (PH) Assumption.
The lifelines library provides a diagnostic method:
cph.check_assumptions(
data,
p_value_threshold=0.05,
show_plots=True
)
If the assumption is violated, possible approaches include:
- Stratifying by a variable.
- Adding time-varying effects.
- Using time-dependent covariates.
- Considering an alternative survival model.
The assumption should be checked rather than automatically presumed to hold.
7. Kaplan-Meier vs. Cox Regression
Both methods are important, but they solve different problems.
| Feature | Kaplan-Meier | Cox Regression |
|---|---|---|
| Model type | Non-parametric | Semi-parametric |
| Main purpose | Estimate survival probability | Model hazard relationships |
| Predictor variables | Grouping for separate curves | Multiple covariates |
| Censored observations | Supported | Supported |
| Hazard ratios | Not directly estimated | Yes |
| Survival curves | Directly estimated | Can derive adjusted survival curves |
| Assumptions | Independent, non-informative censoring | Also requires proportional hazards for standard interpretation |
When should you use Kaplan-Meier?
Use Kaplan-Meier when you want to estimate and visualize survival probabilities for a population or compare groups descriptively.
When should you use Cox Regression?
Use Cox regression when you want to understand how multiple variables are associated with event hazard.
8. Parametric Survival Models
Parametric survival models assume that event times follow a particular probability distribution.
Common distributions include:
- Exponential.
- Weibull.
- Log-Normal.
- Log-Logistic.
These models can be useful when the distributional assumptions fit the data and predictions beyond the observed period are needed.
8.1 Exponential Survival Model
The exponential model assumes a constant hazard over time.
Its survival function is:
\[ S(t)=e^{-\lambda t} \]
Where:
- \(\lambda\): Constant event rate.
- \(t\): Time.
This assumption can be too restrictive for many real-world situations.
8.2 Weibull Survival Model
The Weibull model supports a hazard that can increase or decrease over time.
Its survival function is:
\[ S(t)=e^{-(\lambda t)^k} \]
Where:
- \(\lambda\): Scale parameter.
- \(k\): Shape parameter.
The shape parameter determines the hazard pattern:
- \(k=1\): Constant hazard.
- \(k>1\): Increasing hazard.
- \(k<1\): Decreasing hazard.
8.3 Weibull Model in Python
from lifelines import WeibullFitter
wf = WeibullFitter()
wf.fit(
durations=data["duration"],
event_observed=data["event"]
)
print(wf.summary)
wf.plot_survival_function()
plt.title("Weibull Survival Model")
plt.show()
Parametric models are particularly useful when their assumptions are scientifically or empirically justified.
9. Advanced Survival Analysis Techniques
Beyond Kaplan-Meier and Cox regression, several advanced approaches are used in modern analytics.
9.1 Time-Varying Covariates
Some predictor variables change over time.
For example:
- A patient's blood pressure changes during treatment.
- A customer changes subscription plans.
- A machine receives maintenance.
- A borrower makes partial loan repayments.
Time-varying Cox models allow these changing variables to influence the hazard over time.
9.2 Competing Risks Analysis
Sometimes multiple different events can prevent the event of interest from occurring.
For example, in a medical study:
- A patient may die from the disease being studied.
- A patient may die from an unrelated cause.
These events are called competing risks.
Treating a competing event as ordinary censoring can produce misleading estimates of real-world event probability.
Common methods include:
- Cumulative incidence functions.
- Cause-specific hazard models.
- Fine-Gray subdistribution hazard models.
9.3 Random Survival Forests
Random Survival Forests adapt the random forest approach to censored time-to-event data.
They can model nonlinear relationships and interactions without requiring the proportional hazards assumption.
They are useful when the relationship between predictors and survival is complex.
9.4 Deep Learning for Survival Analysis
Deep learning models can also be applied to survival prediction.
Examples include:
- DeepSurv.
- DeepHit.
- Neural survival models.
These approaches can learn nonlinear relationships from large and complex datasets.
However, they require careful handling of censoring, validation, calibration, and interpretability.
10. Real-World Applications of Survival Analysis
1. Healthcare and Medical Research
Survival analysis is widely used to study:
- Patient survival.
- Cancer treatment effectiveness.
- Disease progression.
- Time to recovery.
- Hospital readmission.
Kaplan-Meier curves help visualize survival, while Cox regression helps investigate associations between patient characteristics and event hazard.
2. Customer Churn Prediction
Subscription-based businesses want to understand how long customers remain active.
Survival analysis can estimate:
- Time until subscription cancellation.
- Customer retention patterns.
- Factors associated with churn.
- Differences between customer segments.
Example predictors:
- Subscription price.
- Customer engagement.
- Number of support requests.
- Contract type.
- Usage frequency.
3. Banking and Finance
Banks and financial institutions can use survival analysis to study:
- Time until loan default.
- Time until repayment.
- Credit risk over time.
- Time until customer account closure.
It provides a time-dependent perspective on risk rather than only predicting whether an event will happen.
4. Manufacturing and Reliability Engineering
Manufacturers use survival analysis to estimate:
- Machine component lifetime.
- Time until equipment failure.
- Maintenance intervals.
- Product reliability.
It can help organizations plan preventive maintenance and reduce unexpected downtime.
5. Employee Retention
Human resource departments can study:
- Time until employee resignation.
- Employee retention patterns.
- Differences across departments.
- Factors associated with employee turnover.
The analysis can help identify patterns associated with employee departures.
11. Common Mistakes in Survival Analysis
- Ignoring censoring: Removing censored observations can introduce bias.
- Confusing survival probability with hazard: They measure different aspects of event timing.
- Incorrect event coding: Make sure event indicators correctly represent whether the event occurred.
- Ignoring the PH assumption: Standard Cox regression requires proportional hazards for its usual interpretation.
- Treating competing risks as ordinary censoring: This can distort cumulative event probability.
- Using too few observations: Small datasets can produce unstable estimates.
- Ignoring missing data: Missing covariates may affect model reliability.
- Interpreting hazard ratios as survival-time ratios: A hazard ratio does not directly tell you how much longer an individual will survive.
- Confusing association with causation: Observational survival models do not automatically establish causal effects.
- Extrapolating beyond the data without caution: Long-term predictions depend heavily on model assumptions.
12. Practical Workflow for Survival Analysis
A typical survival analysis project follows these steps:
Step 1: Define the event
Clearly identify the event being studied.
Step 2: Define the time origin
Determine when observation begins for each individual.
Step 3: Prepare the dataset
Create duration, event indicator, and predictor columns.
Step 4: Inspect censoring
Identify which observations are complete and which are censored.
Step 5: Perform exploratory analysis
Explore distributions, event frequencies, and relevant subgroups.
Step 6: Estimate survival curves
Use Kaplan-Meier to understand survival patterns.
Step 7: Compare groups
Apply the log-rank test when appropriate.
Step 8: Build a regression model
Use Cox regression to investigate predictor relationships.
Step 9: Validate assumptions
Check proportional hazards, censoring assumptions, and model diagnostics.
Step 10: Evaluate and communicate results
Report confidence intervals, hazard ratios, survival estimates, and limitations.
13. Frequently Asked Questions (FAQs)
Q1. What is Survival Analysis in machine learning?
Survival Analysis is a statistical and machine learning approach used to predict or analyze the time until an event occurs while accounting for censored observations.
Q2. What is the Kaplan-Meier estimator used for?
It estimates the probability that an individual remains event-free beyond a particular time. It is commonly used to visualize survival curves.
Q3. What is censoring in survival analysis?
Censoring occurs when the exact event time is unknown. For example, a patient may still be alive when a study ends.
Q4. What is the difference between survival function and hazard function?
The survival function measures the probability of remaining event-free beyond time \(t\). The hazard function measures the instantaneous event rate at time \(t\), conditional on remaining event-free until then.
Q5. What is Cox Proportional Hazards Regression?
It is a semi-parametric regression model that examines how predictor variables are associated with the hazard of an event.
Q6. What does a hazard ratio of 2 mean?
A hazard ratio of 2 indicates twice the estimated instantaneous hazard for a one-unit increase in the predictor, holding other variables constant, under the model assumptions.
Q7. Which Python library is useful for survival analysis?
The lifelines library is a popular Python package for Kaplan-Meier estimation, Cox regression, parametric survival models, and other survival analysis techniques.
Q8. What is the difference between Kaplan-Meier and Cox regression?
Kaplan-Meier estimates survival probabilities, while Cox regression models the relationship between predictor variables and event hazard.
Q9. Can survival analysis be used for customer churn?
Yes. It can estimate how long customers are likely to remain subscribed and identify factors associated with cancellation.
Q10. Is survival analysis only used in healthcare?
No. It is also widely used in finance, insurance, manufacturing, telecommunications, marketing, and customer analytics.
14. Conclusion
Survival Analysis is a powerful approach for understanding time-to-event problems.
It provides methods for analyzing event timing even when some observations are censored.
The most important techniques include:
- Kaplan-Meier Estimator: Estimates and visualizes survival probability over time.
- Log-Rank Test: Compares survival distributions between groups.
- Cox Proportional Hazards Regression: Investigates how multiple variables are associated with event hazard.
- Parametric Survival Models: Model survival times using probability distributions.
- Advanced Survival Models: Random Survival Forests and deep learning approaches handle more complex relationships.
Survival analysis connects statistics, machine learning, and predictive analytics to solve real-world problems involving time and uncertainty.
Whether you are predicting customer churn, patient survival, loan default, or machine failure, understanding the time until an event occurs can lead to better decisions.
Don't just predict what will happen. Understand when it is likely to happen.