{"data":{"slug":"github-aipoch-medical-research-skills-scientific-skills-data-analysis-scikit-survival-e0e819d9b230","title":"Survival Analysis with scikit-survival","summary":"Model time-to-event outcomes with censoring using scikit-survival, including fitting Cox Proportional Hazards models, training Random Survival Forests, and evaluating with metrics like Uno\u2019s C-index.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-scikit-survival-e0e819d9b230","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-scikit-survival-e0e819d9b230","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-scikit-survival-e0e819d9b230.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-scikit-survival-e0e819d9b230\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Ensure data is preprocessed with appropriate scaling and categorical encoding before fitting most models. Use `Surv` from `sksurv.util` to construct survival targets with event indicators and time values.","instructions":"---\nname: scikit-survival\ndescription: A comprehensive toolkit for survival analysis and time-to-event modeling in Python using scikit-survival; use it when you need to model censored time-to-event outcomes, fit Cox\/RSF\/GB models or Survival SVMs, evaluate with C-index\/Brier score, or handle competing risks.\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n## When to Use\n\nUse this skill when you need to:\n\n1. Model **time-to-event outcomes with censoring** (right\/left\/interval censored observations).\n2. Fit and interpret **Cox Proportional Hazards** models (including **penalized** Cox for high-dimensional data).\n3. Train **non-linear survival models** such as **Random Survival Forests** or **Gradient Boosting** survival models.\n4. Use **Survival SVMs** for margin-based survival prediction (linear or kernel).\n5. Evaluate survival predictions with **censoring-aware metrics** (Uno\/Harrell C-index, time-dependent AUC, Brier\/Integrated Brier Score) and\/or perform **competing risks** analysis.\n\n## Key Features\n\n- **Survival target construction** via `sksurv.util.Surv` (arrays or DataFrame).\n- **Model families**\n  - Cox models: `CoxPHSurvivalAnalysis`, `CoxnetSurvivalAnalysis`\n  - Ensembles: `RandomSurvivalForest`, `GradientBoostingSurvivalAnalysis`, `ExtraSurvivalTrees`\n  - SVM-based: `FastSurvivalSVM`, `FastKernelSurvivalSVM`\n- **Non-parametric estimators**: Kaplan\u2013Meier and Nelson\u2013Aalen.\n- **Competing risks**: cumulative incidence estimation.\n- **scikit-learn compatibility**: pipelines, cross-validation, and `GridSearchCV` with survival scorers.\n- **Evaluation utilities**: IPCW-based metrics (e.g., Uno\u2019s C-index) and calibration-aware scores (IBS).\n\n> Additional topic guides may exist under:\n> - `references\/cox-models.md`\n> - `references\/ensemble-models.md`\n> - `references\/svm-models.md`\n> - `references\/data-handling.md`\n> - `references\/evaluation-metrics.md`\n> - `references\/competing-risks.md`\n\n## Dependencies\n\n- `scikit-survival` (recommended: `>=0.22`)\n- `scikit-learn` (recommended: `>=1.2`)\n- `numpy` (recommended: `>=1.23`)\n- `pandas` (recommended: `>=1.5`)\n\n## Example Usage\n\nA complete, runnable example using a scikit-survival built-in dataset, a scikit-learn pipeline, and Uno\u2019s C-index (IPCW):\n\n```python\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import StandardScaler\n\nfrom sksurv.datasets import load_breast_cancer\nfrom sksurv.linear_model import CoxPHSurvivalAnalysis\nfrom sksurv.metrics import concordance_index_ipcw, as_concordance_index_ipcw_scorer\n\n# 1) Load data (X: features, y: structured array with fields like ('event', 'time'))\nX, y = load_breast_cancer()\n\n# 2) Split (keep y_train for IPCW-based metrics)\nX_train, X_test, y_train, y_test = train_test_split(\n    X, y, test_size=0.2, random_state=42\n)\n\n# 3) Build a pipeline (scaling is important for many survival models)\npipe = Pipeline([\n    (\"scaler\", StandardScaler()),\n    (\"model\", CoxPHSurvivalAnalysis()),\n])\n\n# 4) Optional: hyperparameter tuning (CoxPH has few knobs; shown for workflow completeness)\n# If your version exposes regularization parameters, tune them here.\nparam_grid = {\n    # Example placeholder; remove if unsupported in your installed version:\n    # \"model__alpha\": [0.0, 1e-4, 1e-3]\n}\n\nif param_grid:\n    search = GridSearchCV(\n        pipe,\n        param_grid=param_grid,\n        scoring=as_concordance_index_ipcw_scorer(),\n        cv=5,\n        n_jobs=-1,\n    )\n    search.fit(X_train, y_train)\n    best = search.best_estimator_\nelse:\n    best = pipe.fit(X_train, y_train)\n\n# 5) Predict risk scores (higher typically means higher risk \/ shorter survival)\nrisk_scores = best.predict(X_test)\n\n# 6) Evaluate with Uno's C-index (IPCW)\nc_uno = concordance_index_ipcw(y_train, y_test, risk_scores)[0]\nprint(f\"Uno's C-index (IPCW): {c_uno:.3f}\")\n```\n\n## Implementation Details\n\n### 1) Survival Target Representation (`Surv`)\nscikit-survival expects outcomes as a **structured array** with at least:\n- an **event indicator** (boolean)\n- a **time** value (float\/int)\n\nCommon construction patterns:\n\n```python\nfrom sksurv.util import Surv\n\ny = Surv.from_arrays(event=event_array, time=time_array)\n# or\ny = Surv.from_dataframe(\"event\", \"time\", df)\n```\n\n### 2) Model Selection Heuristics\n- **High-dimensional (p > n)**: prefer `CoxnetSurvivalAnalysis` (Elastic Net) for stability and feature selection.\n- **Interpretability required**: prefer `CoxPHSurvivalAnalysis` (coefficients as log hazard ratios).\n- **Strong non-linearities \/ interactions**: prefer `RandomSurvivalForest` or `GradientBoostingSurvivalAnalysis`.\n- **Kernelized decision boundaries**: consider `FastKernelSurvivalSVM` (ensure scaling).\n\n### 3) Preprocessing Requirements\n- **Scaling**: strongly recommended for SVMs and often beneficial for penalized Cox models.\n- **Categoricals**: encode (e.g., one-hot) before fitting most estimators.\n- **Data validation**: ensure non-negative times; verify enough events relative to feature count.\n\n### 4) Evaluation Under Censoring\n- **Harrell\u2019s C-index** (`concordance_index_censored`): common, but can be less robust with heavy censoring.\n- **Uno\u2019s C-index** (`concordance_index_ipcw`): uses **inverse probability of censoring weights** and requires `y_train` to estimate censoring distribution.\n\n```python\nfrom sksurv.metrics import concordance_index_censored, concordance_index_ipcw\n\nc_harrell = concordance_index_censored(y_test[\"event\"], y_test[\"time\"], risk_scores)[0]\nc_uno = concordance_index_ipcw(y_train, y_test, risk_scores)[0]\n```\n\n### 5) Time-dependent Metrics (AUC, Brier\/IBS)\n- **Time-dependent AUC** evaluates discrimination at specific time horizons.\n- **Brier score \/ Integrated Brier Score (IBS)** evaluates calibration + discrimination over time and requires survival probabilities\/functions.\n\n```python\nfrom sksurv.metrics import cumulative_dynamic_auc\n\ntimes = np.array([365, 730, 1095])  # example horizons\nauc, mean_auc = cumulative_dynamic_auc(y_train, y_test, risk_scores, times)\n```\n\n### 6) Competing Risks (Cumulative Incidence)\nUse competing risks methods when multiple mutually exclusive event types exist and one event prevents the others.\n\n```python\nfrom sksurv.nonparametric import cumulative_incidence_competing_risks\n\n# y must encode event types appropriately for competing risks workflows\ntime_points, cif1, cif2 = cumulative_incidence_competing_risks(y)\n```","use_cases":["Modeling censored time-to-event outcomes in medical research","Fitting Cox Proportional Hazards models for survival analysis","Training Random Survival Forests for non-linear survival modeling"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/scientific-skills\/Data%20Analysis\/scikit-survival\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T12:44:20.000000Z","updated_at":"2026-11-24T12:17:13.000000Z","seo_title":"Survival Analysis with scikit-survival","seo_description":"Model censored time-to-event outcomes with scikit-survival for survival analysis and time-to-event modeling, including Cox Proportional Hazards and Random Survival Forest","seo_keywords":["survival analysis","time-to-event modeling","Cox Proportional Hazards","Random Survival Forests","scikit-survival","medical research"]}}