Skip to main content

Deep Recurrent Survival Analysis in PyTorch

Documentation

This project features a PyTorch implementation of the Deep Recurrent Survival Analysis model that is intended for use on uncensored sequential data in which the event is known to occur at the last time step for each observation More specifically, this library is made up of two small modules.

  1. functions.py, which contains utilities for computing conventional survival analysis quantities, given a torch.Tensor of predicted conditional hazard rates.

  2. model.py, which contains the DRSA class (a subclass of torch.nn.Module), and is easily extended to handle categorical embeddings, additional layers, or any other arbitrary PyTorch operations.

Installation

$ pip install drsa

Usage

from drsa.functions import event_time_loss, event_rate_loss
from drsa.model import DRSA
import torch
import torch.nn as nn
import torch.optim as optim
# generating random data
batch_size, seq_len, n_features = (64, 25, 10)
def data_gen(batch_size, seq_len, n_features):
    samples = []
    for _ in range(batch_size):
        sample = torch.cat([torch.normal(mean=torch.arange(1., float(seq_len)+1)).unsqueeze(-1) for _ in range(n_features)], dim=-1)
        samples.append(sample.unsqueeze(0))
    return torch.cat(samples, dim=0)
data = data_gen(batch_size, seq_len, n_features)

# generating random embedding for each sequence
n_embeddings = 10
embedding_idx = torch.mul(
    torch.ones(batch_size, seq_len, 1),
    torch.randint(low=0, high=n_embeddings, size=(batch_size, 1, 1)),
)

# concatenating embeddings and features
X = torch.cat([embedding_idx, data], dim=-1)
# instantiating embedding parameters
embedding_size = 5
embeddings = torch.nn.Embedding(n_embeddings, embedding_size)
# instantiating model
model = DRSA(
    n_features=n_features + 1,  # +1 for the embeddings
    hidden_dim=2,
    n_layers=1,
    embeddings=[embeddings],
)
# defining training loop
def training_loop(X, optimizer, alpha, epochs):
    for epoch in range(epochs):
        optimizer.zero_grad()
        preds = model(X)

        # weighted average of survival analysis losses
        evt_loss = event_time_loss(preds)
        evr_loss = event_rate_loss(preds)
        loss = (alpha * evt_loss) + ((1 - alpha) * evr_loss)

        # updating parameters
        loss.backward()
        optimizer.step()
        if epoch % 100 == 0:
            print(f"epoch: {epoch} - loss: {round(loss.item(), 4)}")
# running training loop
optimizer = optim.Adam(model.parameters())
training_loop(X, optimizer, alpha=0.5, epochs=1001)
epoch: 0 - loss: 12.485
epoch: 100 - loss: 10.0184
epoch: 200 - loss: 6.5471
epoch: 300 - loss: 4.6741
epoch: 400 - loss: 3.9786
epoch: 500 - loss: 3.5133
epoch: 600 - loss: 3.1826
epoch: 700 - loss: 2.9421
epoch: 800 - loss: 2.7656
epoch: 900 - loss: 2.6355
epoch: 1000 - loss: 2.5397

Metadata

Release files for drsa 0.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for drsa 0.0.3
File Size Uploaded
drsa-0.0.3.tar.gz 11.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for drsa 0.0.3
File Interpreter ABI Platform
drsa-0.0.3-py3-none-any.whl Python 3 none any Details

Total release size: 21.2 kB

Release files / drsa-0.0.3.tar.gz

Download URL drsa-0.0.3.tar.gz
Size 11.0 kB
Tags Source
SHA-256 checksum
How to use checksums
3affdeeea1462f8a158feb6fa4dd19b6e4b943ac92027df899d4dc6d9721da77
BLAKE2b-256 checksum
How to use checksums
5ce9747cfa158c735d0b1162f91b24da05a87d703aee86c7828e3ed5e34bc72f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.1.3.post20200330 requests-toolbelt/0.9.1 tqdm/4.38.0 CPython/3.7.7

Release files / drsa-0.0.3-py3-none-any.whl

Download URL drsa-0.0.3-py3-none-any.whl
Size 10.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
cb1211577ee9e7dc96c341e3a5a9481eb9266358af06e791071f08ed9fc34e79
BLAKE2b-256 checksum
How to use checksums
7a31c9d5b343ac2c699a2de897becb637481ec1ad5f1cb06daff6ea6df7ac260
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.1.3.post20200330 requests-toolbelt/0.9.1 tqdm/4.38.0 CPython/3.7.7

Release history Release notifications | RSS feed

This release

0.0.3 This release

2 release files

0.0.2

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page