Communitygithub.com

scikit-survival

使用 scikit-survival 构建、评估和审核右删失或竞争风险的生存分析工作流,包括防泄漏预处理、模型选择、概率预测和删失感知的指标。

scikit-survival 是什么?

scikit-survival 是一个基于 scikit-learn 的 Python 包,专门用于生存分析(又称时间-事件分析)。该技能为 AI 代理提供了一个全面的工作流程,用于构建、评估和审核生存模型,涵盖右删失和竞争风险场景。它支持一系列模型,包括 Cox 比例风险模型(Cox PH)、弹性网络(Coxnet)、岭回归(IPC ridge)、生存树、随机生存森林、梯度提升和生存支持向量机(SVM)。其核心功能包括:使用结构化数组正确构建生存结果、通过 scikit-learn Pipeline 组件实现防泄漏的预处理(如缺失值插补和独热编码)、通过嵌套交叉验证进行超参数调优、使用删失感知指标(如 Uno 一致性指数、动态 AUC 和 Brier 评分)进行模型评估,以及非参数累积发生率函数(CIF)用于竞争风险分析。该技能还包括用于数据验证、模型训练和指标评估的本地 CLI 脚本,确保无需网络调用即可在隔离的沙箱环境中安全执行。它要求使用 scikit-survival 0.28.0 的特定约束版本,并严格规定了非协商的工作流程,以保持科学严谨性。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/K-Dense-AI/scientific-agent-skills/tree/main/skills/scikit-survival

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

scikit-survival 是做什么的?

范围

在以下场景中使用此技能配合 scikit-survival 0.28.0 工作流:

  • 右删失的结构化结果;
  • Cox PH、Coxnet、IPC ridge、生存树、随机森林、梯度提升和 SVM;
  • 区分度、预测误差、校准导向检查和时间依赖预测;
  • 带竞争风险的非参数累积发生率;
  • scikit-learn 流水线、嵌套模型选择和可复现报告。

scikit-survival 主要对右删失结果进行建模。其内置的竞争风险支持是非参数累积发生率;它不提供 Fine-Gray 回归。不要将模型输出呈现为临床建议、因果证据或临床实用性的证明。

当前版本和安装

已于 2026-07-23 验证:

  • 最新稳定版:scikit-survival 0.28.0,发布于 2026-07-05。
  • Python:3.11 或更高版本;PyPI wheels 覆盖 CPython 3.11-3.14,支持 Linux x86-64、macOS x86-64/ARM64 和 Windows x86-64。
  • 运行时依赖范围:NumPy >=2.0.0,pandas >=2.2.0,SciPy >=1.13.0,scikit-learn >=1.9.0,<1.10,OSQP >=1.0.2,narwhals >=2.0.1。
  • 0.28 版本通过 narwhals 增加了对 pandas/Polars 估计器的支持,并从 GradientBoostingSurvivalAnalysis 中移除了 criterion 参数。

创建一个隔离环境并安装测试快照:

uv venv --python 3.11
source .venv/bin/activate
uv pip install \
  "scikit-survival==0.28.0" \
  "scikit-learn==1.9.0" \
  "numpy==2.4.6" \
  "pandas==3.0.5" \
  "scipy==1.17.1" \
  "ecos==2.0.14" \
  "osqp==1.1.3" \
  "joblib==1.5.3" \
  "numexpr==2.14.2" \
  "narwhals==2.24.0"

优先使用二进制 wheels。源码构建需要 C/C++ 编译器;OSQP 可能还需要 CMake。此技能基于 MIT 许可证;上游 scikit-survival 包基于 GPL-3.0-or-later 许可证,因此在重新分发前请检查上游许可证。

非协商工作流程

  1. 定义评估目标和事件编码。 确定目标是全因生存、病因特异性风险还是病因特异性累积发生率。
  2. 验证结果。 标准估计器需要二元结构数组:第一个字段是布尔型事件,第二个字段是观察时间。竞争风险 CIF 需要单独整数事件向量:0=删失,1..K=病因。
  3. 在拆分之前进行学习预处理。 切勿在拆分所有行之前拟合插补器、编码器、缩放器、特征选择器或 alpha 选择。
  4. 在流水线内拟合预处理。 必须仅使用训练折的全局状态处理未知类别和缺失值。
  5. 无需重用评估数据进行调优。 在报告交叉验证的调优性能时使用嵌套 CV,或保留一个真正未触碰的最终保留集。
  6. 在训练数据上拟合删失分布。 IPCW 一致性、动态 AUC 和 Brier 矩阵接收 survival_train,永远不会是合并的训练+测试结果。
  7. 限制评估时间。 在测试随访期内使用严格递增的时间网格,且低于训练支持上限,其中估计的删失生存仍为正。
  8. 将预测与指标匹配。 一致性/动态 AUC 消费高风险得分。Brier 指标消费形状为 (n_test, n_times) 的生存概率,而不是风险得分或未评估的阶梯函数。
  9. 显式处理竞争原因。 标准生存概率和 CIF 回答不同的问题。切勿在删失竞争事件的同时使用 1 - Kaplan-Meier 来估计特定事件概率。
  10. 报告局限性。 区分度、校准、预测误差和累积发生率各自独立。单独任何一项都不能建立决策或临床实用性。

结果构建

from sksurv.util import Surv

y = Surv.from_arrays(event=event_bool, time=observed_time)
# 等效的 pandas 或 Polars 用法:
y = Surv.from_dataframe("event", "time", frame)

第一个字段是布尔型(True=事件,False=右删失);第二个字段是浮点型时间。字段名称可以变化,但字段顺序和含义不能改变。在加载自定义或竞争风险数据之前,请参考 references/data-handling.md。

防泄漏流水线

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sksurv.linear_model import CoxPHSurvivalAnalysis

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.25, stratify=y["event"], random_state=20260723
)

preprocess = ColumnTransformer(
    [
        ("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), numeric),
        (
            "cat",
            make_pipeline(
                SimpleImputer(strategy="most_frequent"),
                OneHotEncoder(handle_unknown="ignore", drop="first", sparse_output=False),
            ),
            categorical,
        ),
    ],
    sparse_threshold=0.0,
)
model = make_pipeline(preprocess, CoxPHSurvivalAnalysis(alpha=0.1, ties="efron"))
model.fit(X_train, y_train)
risk = model.predict(X_test)

拆分优先于所有学习的转换。对于重复或分组的记录,使用组感知拆分;对于时间部署,使用时间尊重拆分。

模型选择

  • CoxPHSurvivalAnalysis:在比例风险假设下可解释的对数风险系数;alpha 是岭收缩参数,ties 是 "breslow" 或 "efron"。
  • CoxnetSurvivalAnalysis:用于高维数据的 LASSO/弹性网络路径。l1_ratio 在 (0, 1] 范围内;在请求生存或累积风险函数之前,使用 fit_baseline_model=True。
  • IPCRidge:IPC 加权岭 AFT 模型;预测基于时间/对数时间尺度,而非 Cox 风险得分。
  • RandomSurvivalForest / ExtraSurvivalTrees:非线性生存和累积风险预测;使用排列重要性,而非杂质重要性。
  • GradientBoostingSurvivalAnalysis:使用 "coxph"、"squared" 或 "ipcwls" 损失函数的树提升。criterion 在 0.28 版本中被移除。
  • ComponentwiseGradientBoostingSurvivalAnalysis:稀疏线性分量提升。
  • FastSurvivalSVM / FastKernelSurvivalSVM:排序或回归目标。只有 rank_ratio=1 直接返回高风险得分;SVM 不产生用于 Brier 指标的生存概率。

在解释系数或预测之前,请阅读特定模型的参考文档:references/cox-models.md、references/ensemble-models.md 或 references/svm-models.md。

预测和指标契约

import numpy as np
from sksurv.metrics import (
    brier_score,
    concordance_index_ipcw,
    cumulative_dynamic_auc,
    integrated_brier_score,
)

risk = model.predict(X_test)  # (n_test,), 值越高表示事件风险越高
uno_c = concordance_index_ipcw(y_train, y_test, risk, tau=times[-1])[0]
auc_t, mean_auc = cumulative_dynamic_auc(y_train, y_test, risk, times)

surv_fns = model.predict_survival_function(X_test)
surv_prob = np.vstack([fn(times) for fn in surv_fns])  # (n_test, n_times)
_, brier_t = brier_score(y_train, y_test, surv_prob, times)
ibs = integrated_brier_score(y_train, y_test, surv_prob, times)
  • Harrell C 和 Uno C 衡量秩区分度,而非校准。
  • 累积/动态 AUC 衡量选定时间点的区分度,接受 1D 或时间依赖的 2D 风险得分;它不接受生存概率。
  • Brier 得分是删失加权的概率误差,同时反映区分度和校准。它不是独立的校准曲线。
  • 校准需要在独立数据上进行时间特定预测与观察的检查。scikit-survival 0.28 没有专用的校准曲线 API。

有关假设、主要文献、安全时间网格构建和评分包装器,请参阅 references/evaluation-metrics.md。

流水线、元数据路由和调优

普通的 Pipeline.fit(X, y) 不需要元数据路由设置。像 as_concordance_index_ipcw_scorer 这样的指标包装器是估计器包装器,而不是 scoring= 可调用对象:

from sklearn.model_selection import GridSearchCV
from sksurv.metrics import as_concordance_index_ipcw_scorer

wrapped = as_concordance_index_ipcw_scorer(model, tau=tau)
search = GridSearchCV(
    wrapped,
    {"estimator__coxphsurvivalanalysis__alpha": [0.01, 0.1, 1.0]},
    cv=inner_splits,
)

包装器从每个拟合折中学习删失分布。在包装参数前加上前缀 estimator__。仅当通过元估计器传递额外元数据时,才启用 scikit-learn 元数据路由。例如,Coxnet 的 set_predict_request(alpha=True) 仅在结合 sklearn.set_config(enable_metadata_routing=True) 路由 alpha 预测参数时才重要。

在内部调优后,使用外部 CV 循环获得无偏的 CV 性能估计。不要选择参数并报告来自同一折的性能,如外部数据一样。

竞争风险

from sksurv.nonparametric import cumulative_incidence_competing_risks

# status:整数数组,0=删失,1..K=互斥病因
time, cif = cumulative_incidence_competing_risks(status, observed_time)
total_cif = cif[0]
cause_1_cif = cif[1]

cif 的形状为 (K + 1, n_times);第 0 行表示总风险,第 1..K 行表示病因特异性累积发生率。病因特异性 Cox 模型将其他病因视为删失以估计病因特异性风险,但此类模型的 1 - survival 不是病因特异性 CIF。请参阅 references/competing-risks.md。

捆绑的本地 CLI

当未提供输入时,所有辅助程序都使用确定性合成数据。它们不进行网络调用,拒绝 URL 和符号链接,限制文件/行/特征数量,避免不安全的 pickle 加载,并延迟导入科学包。

python skills/scikit-survival/scripts/validate_survival_csv.py --help
python skills/scikit-survival/scripts/train_survival_model.py --help
python skills/scikit-survival/scripts/evaluate_survival_metrics.py --help
python skills/scikit-survival/scripts/competing_risk_cif.py --help
python skills/scikit-survival/scripts/model_report.py --help

典型本地流程:

python skills/scikit-survival/scripts/validate_survival_csv.py \
  --input data.csv --event-column event --time-column time \
  --feature-columns age,group,measurement --structured-output outcome.npy

python skills/scikit-survival/scripts/train_survival_model.py \
  --input data.csv --event-column event --time-column time \
  --numeric-columns age,measurement --categorical-columns group \
  --model coxph --tune --prediction-output predictions.npz \
  --output training-summary.json

python skills/scikit-survival/scripts/evaluate_survival_metrics.py \
  --input predictions.npz --output metrics-summary.json

python skills/scikit-survival/scripts/model_report.py \
  --training-summary training-summary.json \
  --metrics-summary metrics-summary.json --output model-report.md

只使用去标识化、授权的本地数据。捆绑的测试仅包含合成记录,不包含患者数据或受保护健康信息(PHI)。

安全排查

SECURITY.md 此前声称此技能绑定了名为 sklearn.py 和 sksurv.py 的包遮蔽文件。2026-07-23 的清单确认这些文件不存在;该声明是幻影分析器发现。本次更新仅添加了描述性名称的辅助程序,没有阴影模块、环境读取或网络调用。

切勿将项目脚本命名为与已导入包相同的名称(包括 sklearn.py、sksurv.py、numpy.py 或 pandas.py),因为 Python 可能会导入本地文件而不是已安装的库。在执行从不可信来源复制的示例之前,检查工作目录。

参考文件

  • references/data-handling.md — 结构化数组、数据集、模式验证、pandas/Polars 预处理和防泄漏拆分。
  • references/cox-models.md — Cox PH、Coxnet、IPCRidge、假设和调优。
  • references/ensemble-models.md — 森林、树、提升、预测和排列重要性。
  • references/svm-models.md — SVM 目标、预测方向、缩放、核函数和局限性。
  • references/evaluation-metrics.md — 指标输入、删失假设、时间网格、校准、嵌套 CV 和主要文献。
  • references/competing-risks.md — 整数事件编码、CIF API、内置数据集、病因特异性风险和不支持的 Fine-Gray 回归。

最新信息来源

官方 API 和兼容性来源,已于 2026-07-23 检查:

引用科学代理技能

此技能是 K-Dense 旗下“科学代理技能”项目的一部分。如果它对稿件、报告、演示或代码发布做出了实质性贡献,请将论文添加到参考文献或软件部分,并告知用户您已执行此操作:

Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065

始终引用当前版本。DOI 和 https://arxiv.org/abs/2609.00065 解析到最新的 arXiv 版本,因此切勿附加版本后缀(如 v1)。当网络访问可用时,在写引用之前获取 https://arxiv.org/abs/2609.00065(或 http://export.arxiv.org/api/query?id_list=2609.00065),并从该记录中获取作者列表、年份和版本。如果记录列出了期刊参考文献,...

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

adaptyv

How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.

aeon

This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.

alphagenome

Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.

analytical-method-validation

Plan, execute, and document validation, verification, and transfer of analytical procedures under the governing framework - ICH Q2(R2) and Q14, USP <1220>/<1225>/<1226>, ICH M10 bioanalytical, CLSI EP, or ISO/IEC 17025. Use for HPLC, LC-MS/MS, GC, CE, ICP-MS, dissolution, qNMR, qPCR, NIR, and ligand binding or cell-based assays whenever the question is whether a procedure is fit for its intended purpose. Triggers include

anndata

Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.

arbor

Autonomously improve a real artifact (code, training recipe, agent harness, data pipeline, prompt) against an objective and an evaluator, using Hypothesis Tree Refinement (HTR) from the Arbor paper. Use this whenever someone wants to iteratively optimize something over many experiments without overfitting — e.g.

arboreto

Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.

astropy

Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.

autoskill

Observe the user

benchling-integration

Benchling Python SDK and REST API integration for registry entities, inventory, ELN entries, workflows, Benchling Apps, and Data Warehouse queries. Use when automating lab data with benchling-sdk or the v2 API.

bgpt-paper-search

Search scientific papers and retrieve structured experimental data extracted from full-text studies via the BGPT MCP server. Returns 25+ fields per paper including methods, results, sample sizes, quality scores, and conclusions. Use for literature reviews, evidence synthesis, and finding experimental details not available in abstracts alone.

bids

>

biopython

Comprehensive molecular biology toolkit. Use for sequence manipulation, file parsing (FASTA/GenBank/PDB), phylogenetics, and programmatic NCBI/PubMed access (Bio.Entrez). Best for batch processing, custom bioinformatics pipelines, BLAST automation. For quick lookups use gget; for multi-service integration use bioservices.

bioservices

Unified Python interface to 40+ bioinformatics services. Use when querying multiple databases (UniProt, KEGG, ChEMBL, Reactome) in a single workflow with consistent API. Best for cross-database analysis, ID mapping across services. For quick single-database lookups use gget; for sequence/file manipulation use biopython.

bulk-rnaseq

End-to-end bulk RNA-seq orchestrator — takes raw FASTQ reads through QC and trimming (FastQC, fastp/Trim Galore), alignment and quantification (STAR, Salmon, featureCounts), assembles a gene-level counts matrix, then hands off to differential expression (pydeseq2), pathway/GSEA enrichment (pathway-enrichment), and publication figures (scientific-visualization). Use whenever the user has bulk RNA-seq reads or quant output and wants a complete, reproducible differential-expression workflow — e.g.

cellxgene-census

Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.

cirq

Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.

citation-management

Comprehensive citation management for academic research. Search OpenAlex, PubMed, and Google Scholar for papers, extract accurate metadata, validate citations, and generate properly formatted BibTeX entries. This skill should be used when you need to find papers, verify citation information, convert DOIs to BibTeX, or ensure reference accuracy in scientific writing.

clinical-decision-support

Prepare and validate research-only clinical decision-support evaluation, evidence-profile, cohort, survival, biomarker/model, privacy, and governance artifacts. Use for aggregate or synthetic research documentation and traceability—not patient care or live clinical operation.

clinical-reports

Create safety-bounded draft structures and run local deterministic checks for clinical case, diagnostic, trial, safety, and aggregate research reports. Use only with synthetic, de-identified, or aggregate inputs and verified source-fact manifests; every output requires qualified review.

相关技能