Survival Analysis with lifelines

VerifiedSafe

Analyzes time-to-event data using Kaplan-Meier curves, log-rank tests, and Cox proportional hazards regression with lifelines.

Sby Skills Guide Bot
Data & AIIntermediate
8/24/2026
Claude CodeCursorCodex
#survival-analysis#lifelines#cox-regression#kaplan-meier#bioinformatics

Recommended for

Automated summary

This skill walks through time-to-event analysis with the Python lifelines library: Kaplan-Meier curves, log-rank tests and Cox proportional hazards regression, including models built from clinical and omics features.

Strengths

  • Gives directly runnable snippets for Kaplan-Meier, log-rank tests and CoxPH, with censoring handled explicitly
  • Covers a multivariate model that combines clinical metadata with gene expression, using L2 penalization for stability
  • Includes survival-appropriate evaluation: hazard ratios, confidence intervals and the concordance index
  • Warns about leakage from follow-up dates, event dates and post-consultation information in oncology prediction settings

Limitations

  • The file is truncated: the proportional hazards assumption check section is cut off
  • The advertised comparison against zero-shot LLM extraction and fine-tuned document models is not backed by any code
  • Despite the 'machine-learning' name, no non-linear or deep survival models are provided — only the classical lifelines path
When to use it

Use it when you need to estimate or compare survival curves, fit a Cox model, or derive risk scores from censored clinical and omics data.

When not to use it

Avoid it if you need deep survival models (DeepSurv, Random Survival Forests) or a ready-made pipeline for LLM-based extraction from consultation documents.

Security analysis

Safe
Quality score88/100

The skill provides Python code for survival analysis using lifelines. It does not include destructive shell commands, exfiltration, or obfuscated code. While it declares run_shell_command as an allowed tool, the content focuses on standard statistical analysis and plotting, with no risky execution patterns.

No concerns found

How this analysis is made

Examples

Comparer deux groupes de risque
J'ai un tableau CSV avec les colonnes time, event et risk_group. Trace les courbes de Kaplan-Meier pour les groupes high et low et donne-moi la p-valeur du test du log-rank.
Modèle de Cox multivarié
Construis un modèle de Cox pénalisé avec l'âge, le stade et l'expression de GENE1/GENE2 comme covariables, puis affiche les hazard ratios et le c-index.
Score de risque et stratification
À partir de mon modèle Cox ajusté, calcule les partial hazards de chaque patient et crée un groupe de risque haut/bas selon la médiane pour un tracé Kaplan-Meier.
<!-- # COPYRIGHT NOTICE # This file is part of the "Universal AI Agentic Skills" project. # Copyright (c) 2026 MD BABU MIA, PhD <md.babu.mia@mssm.edu> # All Rights Reserved. # # This code is proprietary and confidential. # Unauthorized copying of this file, via any medium is strictly prohibited. # # Provenance: Authenticated by MD BABU MIA -->

name: bio-machine-learning-survival-analysis description: Analyzes time-to-event data using Kaplan-Meier curves, log-rank tests, and Cox proportional hazards regression with lifelines. Builds survival models from clinical and omics features. Use when predicting patient survival or modeling time-to-event outcomes. tool_type: python primary_tool: lifelines measurable_outcome: Execute skill workflow successfully with valid output within 15 minutes. allowed-tools:

  • read_file
  • run_shell_command

Survival Prediction with lifelines

Core Capabilities

  • For cancer survival prediction from initial oncology consultation documents, compare zero-shot LLM extraction/risk scoring, fine-tuned document models, and classical survival models built from explainable consultation-text features; prevent leakage from future outcomes, follow-up, event dates, or post-consultation information; handle censoring explicitly; and validate calibration plus censoring-aware time-to-event performance internally and on external cohorts when available.

Kaplan-Meier Curves

from lifelines import KaplanMeierFitter
import matplotlib.pyplot as plt

kmf = KaplanMeierFitter()

# T: time to event or censoring
# E: event indicator (1=event occurred, 0=censored)
kmf.fit(T, event_observed=E)

# Plot survival curve
kmf.plot_survival_function()
plt.xlabel('Time (months)')
plt.ylabel('Survival probability')
plt.savefig('km_curve.png', dpi=150)

Compare Groups with Log-Rank Test

from lifelines import KaplanMeierFitter
from lifelines.statistics import logrank_test
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 6))

for group, color in zip(['high', 'low'], ['red', 'blue']):
    mask = df['risk_group'] == group
    kmf = KaplanMeierFitter()
    kmf.fit(df.loc[mask, 'time'], event_observed=df.loc[mask, 'event'], label=group)
    kmf.plot_survival_function(ax=ax, color=color)

# Log-rank test
high = df[df['risk_group'] == 'high']
low = df[df['risk_group'] == 'low']
results = logrank_test(high['time'], low['time'], event_observed_A=high['event'], event_observed_B=low['event'])
print(f'Log-rank p-value: {results.p_value:.4e}')

ax.set_xlabel('Time (months)')
ax.set_ylabel('Survival probability')
ax.set_title(f'Log-rank p = {results.p_value:.4e}')
plt.savefig('km_comparison.png', dpi=150)

Cox Proportional Hazards Regression

from lifelines import CoxPHFitter

# Prepare data: must have 'time' and 'event' columns
# Include covariates as additional columns
cph = CoxPHFitter()
cph.fit(df, duration_col='time', event_col='event')

# Summary with hazard ratios
cph.print_summary()

# Get hazard ratios as DataFrame
hr = cph.summary[['exp(coef)', 'exp(coef) lower 95%', 'exp(coef) upper 95%', 'p']]
print(hr)

# Concordance index (c-index): 0.5=random, 1.0=perfect
print(f'C-index: {cph.concordance_index_:.3f}')

Multivariate Cox Model

from lifelines import CoxPHFitter
import pandas as pd

# Combine clinical and omics features
cox_df = pd.DataFrame({
    'time': meta['survival_months'],
    'event': meta['vital_status'],
    'age': meta['age'],
    'stage': meta['stage_numeric'],
    'GENE1': expr.loc['GENE1'],
    'GENE2': expr.loc['GENE2']
})

cph = CoxPHFitter(penalizer=0.1)  # L2 regularization for stability
cph.fit(cox_df, duration_col='time', event_col='event')
cph.print_summary()

Predict Risk Scores

# Partial hazard (risk score)
risk_scores = cph.predict_partial_hazard(cox_df)

# Median risk split for KM plot
df['risk_group'] = (risk_scores > risk_scores.median()).map({True: 'high', False: 'low'})

Check Proportional Hazards Assumption

# Test PH assumption
cph.check_assumptions(df, p_value_threshold=0.05, show_plots=True)

Survival at Specific Time

# Survival probability at specific times
survival_probs = kmf.survival_function_at_times([12, 24, 60])
print(survival_probs)

# Median survival
print(f'Median survival: {kmf.median_survival_time_:.1f}')

Feature Selection for Survival

from lifelines import CoxPHFitter
import pandas as pd

# Univariate screening
results = []
for gene in expr.index[:1000]:
    cox_df = pd.DataFrame({
        'time': meta['survival_months'],
        'event': meta['vital_status'],
        'gene': expr.loc[gene]
    })
    cph = CoxPHFitter()
    cph.fit(cox_df, duration_col='time', event_col='event')
    results.append({
        'gene': gene,
        'hr': cph.hazard_ratios_['gene'],
        'p': cph.summary.loc['gene', 'p']
    })

results_df = pd.DataFrame(results)
sig_genes = results_df[results_df['p'] < 0.05].sort_values('p')

Related Skills

  • clinical-databases/variant-prioritization - Clinical variant interpretation
  • differential-expression/de-results - Find DE genes for survival model
  • machine-learning/biomarker-discovery - Select predictive features

References

  • https://pubmed.ncbi.nlm.nih.gov/42004490/
<!-- AUTHOR_SIGNATURE: 9a7f3c2e-MD-BABU-MIA-2026-MSSM-SECURE -->

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/survival-analysis-with-lifelines-mt6repsz/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/survival-analysis-with-lifelines-mt6repsz' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/survival-analysis-with-lifelines-mt6repsz/download' --output '.skill-downloads/survival-analysis-with-lifelines-mt6repsz/SKILL.md.part' && mv '.skill-downloads/survival-analysis-with-lifelines-mt6repsz/SKILL.md.part' '.skill-downloads/survival-analysis-with-lifelines-mt6repsz/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

This file does not provide a usable name/description header for this native procedure. It remains available to download and inspect; use the manual method below.

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/survival-analysis-with-lifelines-mt6repsz/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills