TorchSurv

TorchSurv: A Lightweight Package for Deep Survival Analysis - Published in JOSS (2024)

https://github.com/novartis/torchsurv

Science Score: 93.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
    Found codemeta.json file
  • .zenodo.json file
    Found .zenodo.json file
  • DOI references
    Found 6 DOI reference(s) in README and JOSS metadata
  • Academic publication links
    Links to: joss.theoj.org
  • Committers with academic emails
  • Institutional organization owner
  • JOSS paper metadata
    Published in Journal of Open Source Software

Keywords

deep-learning pytorch survival-analysis
Last synced: 4 months ago · JSON representation

Repository

Deep survival analysis made easy

Basic Info
Statistics
  • Stars: 150
  • Watchers: 8
  • Forks: 13
  • Open Issues: 8
  • Releases: 5
Topics
deep-learning pytorch survival-analysis
Created almost 2 years ago · Last pushed 4 months ago
Metadata Files
Readme License

README.md

Deep survival analysis made easy

Ruff Python PyPI - Version Conda PyPI Downloads Conda Downloads

CodeQC Docs CodeFactor JOSS License Documentation

TorchSurv is a Python package that serves as a companion tool to perform deep survival modeling within the PyTorch environment. Unlike existing libraries that impose specific parametric forms on users, TorchSurv enables the use of custom PyTorch-based deep survival models. With its lightweight design, minimal input requirements, full PyTorch backend, and freedom from restrictive survival model parameterizations, TorchSurv facilitates efficient survival model implementation, particularly beneficial for high-dimensional input data scenarios.

If you find this repository useful, please consider giving a star! ⭐

This package was developed by Novartis and the US Food and Drug Administration as part of a research collaboration agreement on radiogenomics.

TL;DR

Our idea is to keep things simple. You are free to use any model architecture you want! Our code has 100% PyTorch backend and behaves like any other functions (losses or metrics) you may be familiar with.

Our functions are designed to support you, not to make you jump through hoops. Here's a pseudo code illustrating how easy is it to use TorchSurv to fit and evaluate a Cox proportional hazards model:

```python from torchsurv.loss import cox from torchsurv.metrics.cindex import ConcordanceIndex

Pseudo training loop

for data in dataloader: x, event, time = data estimate = model(x) # shape = torch.Size([64, 1]), if batch size is 64 loss = cox.negpartiallog_likelihood(estimate, event, time) loss.backward() # native torch backend

You can check model performance using our evaluation metrics, e.g, the concordance index with

cindex = ConcordanceIndex() cindex(estimate, event, time)

You can obtain the confidence interval of the c-index

cindex.confidence_interval()

You can test whether the observed c-index is greater than 0.5 (random estimator)

cindex.pvalue(method="noether", alternative="twosided")

You can even compare the metrics between two models (e.g., vs. model B)

cindex.compare(cindexB) ```

Installation and dependencies

First, install the package using either PyPI or Conda

  • Using conda (recommended) bash conda install conda-forge::torchsurv
  • Using PyPI bash pip install torchsurv

  • Using for local installation (latest version)

bash git clone <repo> cd <repo> pip install -e .

Additionally, to build the documentation (notebooks, sphinx) and for package development (tests), please see the development notes and dev/environment.yml. This step is not required to use TorchSurv in your projects but only for optional features.

Getting started

We recommend starting with the introductory guide, where you'll find an overview of the package's functionalities.

Survival data

We simulate a random batch of 64 subjects. Each subject is associated with a binary event status (= True if event occurred), a time-to-event or censoring and 16 covariates.

```python

import torch _ = torch.manual_seed(52) n = 64 x = torch.randn((n, 16)) event = torch.randint(low=0, high=2, size=(n,)).bool() time = torch.randint(low=1, high=100, size=(n,)).float() ```

Cox proportional hazards model

The user is expected to have defined a model that outputs the estimated log relative hazard for each subject. For illustrative purposes, we define a simple linear model that generates a linear combination of the covariates.

```python

from torch import nn modelcox = nn.Sequential(nn.Linear(16, 1)) loghz = modelcox(x) print(loghz.shape) torch.Size([64, 1]) ```

Given the estimated log relative hazard and the survival data, we calculate the current loss for the batch with:

```python

from torchsurv.loss.cox import negpartialloglikelihood loss = negpartialloglikelihood(loghz, event, time) print(loss) tensor(4.1723, gradfn=) ```

We obtain the concordance index for this batch with:

```python

from torchsurv.metrics.cindex import ConcordanceIndex with torch.nograd(): loghz = modelcox(x) cindex = ConcordanceIndex() print(cindex(loghz, event, time)) tensor(0.4872) ```

We obtain the Area Under the Receiver Operating Characteristic Curve (AUC) at a new time t = 50 for this batch with:

```python

from torchsurv.metrics.auc import Auc newtime = torch.tensor(50.) auc = Auc() print(auc(loghz, event, time, new_time=50)) tensor([0.4737]) ```

Weibull accelerated failure time (AFT) model

The user is expected to have defined a model that outputs for each subject the estimated log scale and optionally the log shape of the Weibull distribution that the event density follows. In case the model has a single output, TorchSurv assume that the shape is equal to 1, resulting in the event density to be an exponential distribution solely parametrized by the scale.

For illustrative purposes, we define a simple linear model that estimate two linear combinations of the covariates (log scale and log shape parameters).

```python

from torch import nn modelweibull = nn.Sequential(nn.Linear(16, 2)) logparams = modelweibull(x) print(logparams.shape) torch.Size([64, 2]) ```

Given the estimated log scale and log shape and the survival data, we calculate the current loss for the batch with:

```python

from torchsurv.loss.weibull import negloglikelihood loss = negloglikelihood(logparams, event, time) print(loss) tensor(82931.5078, gradfn=) ```

To evaluate the predictive performance of the model, we calculate subject-specific log hazard and survival function evaluated at all times with:

```python

from torchsurv.loss.weibull import loghazard from torchsurv.loss.weibull import survivalfunction with torch.nograd(): logparams = modelweibull(x) loghz = loghazard(logparams, time) print(loghz.shape) torch.Size([64, 64]) surv = survivalfunction(log_params, time) print(surv.shape) torch.Size([64, 64]) ```

We obtain the concordance index for this batch with:

```python

from torchsurv.metrics.cindex import ConcordanceIndex cindex = ConcordanceIndex() print(cindex(log_hz, event, time)) tensor(0.4062) ```

We obtain the AUC at a new time t = 50 for this batch with:

```python

from torchsurv.metrics.auc import Auc newtime = torch.tensor(50.) loghzt = loghazard(logparams, time=newtime) auc = Auc() print(auc(loghzt, event, time, newtime=newtime)) tensor([0.3509]) ```

We obtain the integrated brier-score with:

```python

from torchsurv.metrics.brierscore import BrierScore brierscore = BrierScore() bs = brierscore(surv, event, time) print(brierscore.integral()) tensor(0.4447) ```

Related Packages

The table below compares the functionalities of TorchSurv with those of auton-survival, pycox, torchlife, scikit-survival, lifelines, and deepsurv. While several libraries offer survival modelling functionalities, no existing library provides the flexibility to use a custom PyTorch-based neural networks to define the survival model parameters.

The outputs of both the log-likelihood functions and the evaluation metrics functions have undergone thorough comparison with benchmarks generated using Python and R packages. The comparisons (at time of publication) are summarised in the Related packages summary.

Survival analysis libraries in Python Survival analysis libraries in Python

Survival analysis libraries in R. For obtaining the evaluation metrics, packages survival, riskRegression, SurvMetrics and pec require the fitted model object as input (a specific object format) and RisksetROC imposes a smoothing method. Packages timeROC, riskRegression and pec force the user to choose a form for subject-specific weights (e.g., inverse probability of censoring weighting (IPCW)). Packages survcomp and SurvivalROC do not implement the general AUC but the censoring-adjusted AUC estimator proposed by Heagerty et al. (2000).

Survival analysis libraries in R

Contributing

We value contributions from the community to enhance and improve this project. If you'd like to contribute, please consider the following:

  1. Create Issues: If you encounter bugs, have feature requests, or want to suggest improvements, please create an issue in the GitHub repository. Make sure to provide detailed information about the problem, including code for reproducibility, or enhancement you're proposing.

  2. Fork and Pull Requests: If you're willing to address an existing issue or contribute a new feature, fork the repository, create a new branch, make your changes, and then submit a pull request. Please ensure your code follows our coding conventions and include tests for any new functionality.

By contributing to this project, you agree to license your contributions under the same license as this project.

Contacts

If you have any questions, suggestions, or feedback, feel free to reach out the development team us.

Cite

If you use this project in academic work or publications, we appreciate citing it using the following BibTeX entry:

@article{Monod2024, doi = {10.21105/joss.07341}, url = {https://doi.org/10.21105/joss.07341}, year = {2024}, publisher = {The Open Journal}, volume = {9}, number = {104}, pages = {7341}, author = {Mélodie Monod and Peter Krusche and Qian Cao and Berkman Sahiner and Nicholas Petrick and David Ohlssen and Thibaud Coroller}, title = {TorchSurv: A Lightweight Package for Deep Survival Analysis}, journal = {Journal of Open Source Software} }

Owner

  • Name: Novartis
  • Login: Novartis
  • Kind: organization
  • Email: open.source@novartis.com
  • Location: Cambridge, MA

JOSS Publication

TorchSurv: A Lightweight Package for Deep Survival Analysis
Published
December 30, 2024
Volume 9, Issue 104, Page 7341
Authors
Mélodie Monod ORCID
Novartis Pharma AG, Switzerland
Peter Krusche ORCID
Novartis Pharma AG, Switzerland
Qian Cao
Center for Devices and Radiological Health, Food and Drug Administration, MD, USA
Berkman Sahiner
Center for Devices and Radiological Health, Food and Drug Administration, MD, USA
Nicholas Petrick
Center for Devices and Radiological Health, Food and Drug Administration, MD, USA
David Ohlssen
Novartis Pharmaceuticals Corporation, NJ, USA
Thibaud Coroller ORCID
Novartis Pharmaceuticals Corporation, NJ, USA
Editor
Kanishka B. Narayan ORCID
Tags
Deep Learning Survival Analysis PyTorch

GitHub Events

Total
  • Create event: 27
  • Release event: 1
  • Issues event: 49
  • Watch event: 81
  • Delete event: 19
  • Issue comment event: 76
  • Push event: 118
  • Pull request review event: 11
  • Pull request review comment event: 8
  • Pull request event: 45
  • Fork event: 6
Last Year
  • Create event: 27
  • Release event: 1
  • Issues event: 49
  • Watch event: 81
  • Delete event: 19
  • Issue comment event: 76
  • Push event: 118
  • Pull request review event: 11
  • Pull request review comment event: 8
  • Pull request event: 45
  • Fork event: 6

Committers

Last synced: 5 months ago

All Time
  • Total Commits: 145
  • Total Committers: 8
  • Avg Commits per committer: 18.125
  • Development Distribution Score (DDS): 0.49
Past Year
  • Commits: 57
  • Committers: 6
  • Avg Commits per committer: 9.5
  • Development Distribution Score (DDS): 0.281
Top Committers
Name Email Commits
Thibaud Coroller 1****r 74
Peter Krusche p****e@n****m 36
melodiemonod m****e@g****m 27
Qian Cao q****v@g****m 4
Sonia 8****m 1
Ikko Eltociear Ashimine e****r@g****m 1
IM D****t 1
Akinori Mitani a****y@g****m 1
Committer Domains (Top 20 + Academic)

Issues and Pull Requests

Last synced: 4 months ago

All Time
  • Total issues: 62
  • Total pull requests: 94
  • Average time to close issues: 20 days
  • Average time to close pull requests: 9 days
  • Total issue authors: 17
  • Total pull request authors: 10
  • Average comments per issue: 0.84
  • Average comments per pull request: 0.59
  • Merged pull requests: 65
  • Bot issues: 0
  • Bot pull requests: 0
Past Year
  • Issues: 35
  • Pull requests: 53
  • Average time to close issues: 23 days
  • Average time to close pull requests: 10 days
  • Issue authors: 9
  • Pull request authors: 8
  • Average comments per issue: 0.69
  • Average comments per pull request: 0.7
  • Merged pull requests: 31
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
  • tcoroller (27)
  • melodiemonod (9)
  • kruscpe1 (7)
  • SoniaDem (3)
  • tadongguk (3)
  • Liumucan (2)
  • Lamgayin (1)
  • aakhmetz (1)
  • Minxiangliu (1)
  • StatMixedML (1)
  • qiancao (1)
  • ToddMorrill (1)
  • lyyraaa (1)
  • abebe9849 (1)
  • mayurmallya (1)
Pull Request Authors
  • tcoroller (46)
  • kruscpe1 (18)
  • melodiemonod (12)
  • SoniaDem (4)
  • qiancao (4)
  • amitani (2)
  • ahmedhshahin (2)
  • ivanmilevtues (2)
  • eltociear (2)
  • davidgajdos1 (2)
Top Labels
Issue Labels
documentation (9) enhancement (6) enhancement ✨ (5) bug 🐛 (4) JOSS review (3) bug (3) good first issue (3) documentation 📖 (3) question ❓ (2) question (1) onhold ⏸️ (1) outofscope🙈 (1) help wanted 🆘 (1)
Pull Request Labels
enhancement ✨ (10) documentation 📖 (7) documentation (7) bug 🐛 (6) enhancement (2) bug (2) JOSS review (1)

Packages

  • Total packages: 1
  • Total downloads:
    • pypi 1,548 last-month
  • Total dependent packages: 0
  • Total dependent repositories: 0
  • Total versions: 5
  • Total maintainers: 3
pypi.org: torchsurv

Deep survival analysis made easy with pytorch

  • Homepage: https://github.com/Novartis/torchsurv
  • Documentation: https://opensource.nibr.com/torchsurv/
  • License: The MIT License (MIT) Copyright (c) 2023 Novartis Pharmaceuticals Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  • Latest release: 0.1.5
    published 6 months ago
  • Versions: 5
  • Dependent Packages: 0
  • Dependent Repositories: 0
  • Downloads: 1,548 Last month
Rankings
Dependent packages count: 9.5%
Average: 36.3%
Dependent repos count: 63.0%
Maintainers (3)
Last synced: 4 months ago

Dependencies

.github/workflows/build-release.yml actions
  • actions/checkout v2 composite
  • actions/setup-python v2 composite
  • actions/upload-artifact v2 composite
.github/workflows/codeqc.yml actions
  • actions/cache v3 composite
  • actions/checkout v2 composite
  • actions/upload-artifact v4 composite
  • conda-incubator/setup-miniconda v3 composite
.github/workflows/docs.yml actions
  • actions/cache v3 composite
  • actions/checkout v2 composite
  • conda-incubator/setup-miniconda v3 composite
pyproject.toml pypi
.github/workflows/check-changelog.yml actions
  • actions/checkout v2 composite
.github/workflows/draft-pdf.yml actions
  • actions/checkout v4 composite
  • actions/upload-artifact v4 composite
  • openjournals/openjournals-draft-action master composite
dev/environment.yml pypi