Skip to main content

KMNet: Discrete-Time Survival Analysis with Deep Learning

KMNet

⚡ State-of-the-art survival analysis with deep learning and ranking losses ⚡

Documentation • Features • Installation • Quick Start • Demo Notebook • Citation

Tests Docs Coverage PyPI Python Version Downloads License Code style

🎯 Use Cases & Applications

🏥 Clinical Research

Patient survival analysis
Treatment effect estimation
Risk stratification

🔧 Reliability Engineering

Equipment failure prediction
Maintenance scheduling
Warranty analysis

📊 Business Analytics

Customer churn prediction
Subscription lifetime value
Employee retention

KMNet combines the power of deep neural networks with Kaplan-Meier inspired ranking losses to deliver state-of-the-art performance in discrete-time survival analysis. Perfect for clinical research, reliability engineering, and time-to-event prediction.

It extends standard neural survival models by incorporating a novel Kaplan-Meier inspired rank loss, allowing the model to learn not just from local hazard rates but also from global ranking constraints inherent in survival data.

This library provides a high-performance implementation using PyTorch JIT to speed up custom loss calculations, making it suitable for large-scale survival datasets.

🚀 Key Features

🎯 Advanced Methodology

  • ✅ Discrete-Time Modeling with flexible time discretization
  • ✅ Hybrid Loss Function combining likelihood and ranking
  • ✅ Kaplan-Meier Inspired ranking constraints
  • ✅ Handles Censoring naturally and efficiently

⚡ Performance

  • 🚀 1.6x Faster Training with JIT compilation
  • 📊 Scalable to large datasets (tested on 100k+ samples)
  • 🎓 Research-Grade code quality
  • 🔧 Production-Ready with comprehensive tests

📊 Why KMNet?

Feature Traditional Methods DeepSurv/Cox-PH KMNet
Handles Non-Linear Effects ❌ ✅ ✅
Captures Ranking Information ⚠️ Partial ❌ ✅
Discrete Time Bins ❌ ❌ ✅
GPU Acceleration ❌ ✅ ✅
Flexible Loss Functions ❌ ⚠️ Limited ✅
JIT-Optimized N/A ❌ ✅

📦 Installation

pip install kmnet

Or install the latest development version from source:

git clone https://github.com/yuvrajiro/KMNet.git
cd KMNet
pip install -e ".[dev]"

Requirements

  • Python >= 3.8
  • PyTorch >= 1.7.0
  • NumPy, Pandas
  • torchtuples
  • pycox
  • numba

⚡ Quick Start

Here is a complete example of how to use KMNet on a synthetic dataset. You can also check out the interactive demo notebook and the full documentation.

1. Data Preparation

KMNet requires the target variable (time and event) to be discretized. We use label_transforms from pycox for this.

import numpy as np
import pandas as pd
from kmnet.model import KMNet

# Generate synthetic data
def make_data(n=1000):
    X = np.random.randn(n, 5).astype('float32')
    T = np.random.exponential(1 / (0.1 * np.exp(0.5 * X[:, 0])))
    C = np.random.exponential(1 / 0.05, size=n)
    time = np.minimum(T, C)
    event = (T <= C).astype('float32')
    return X, time, event

X, time, event = make_data()

# Discretize time into 20 bins
num_durations = 20
labtrans = KMNet.label_transform(num_durations)
get_target = lambda df: (df['duration'].values, df['event'].values)

df = pd.DataFrame({'duration': time, 'event': event})
y = labtrans.fit_transform(*get_target(df))

2. Define the Neural Network

You can use any PyTorch network architecture. The output dimension must match the number of time bins.

import torch.nn as nn

in_features = X.shape[1]
out_features = labtrans.out_features

net = nn.Sequential(
    nn.Linear(in_features, 32),
    nn.ReLU(),
    nn.Linear(32, 32),
    nn.ReLU(),
    nn.Linear(32, out_features)
)

3. Train the Model

Initialize KMNet and fit it to the data.

# Initialize model with the discretized time grid
model = KMNet(net, duration_index=labtrans.cuts)

# Train
batch_size = 64
epochs = 10
model.fit(X, y, batch_size, epochs, verbose=True)

4. Prediction and Visualization

Predict survival functions and plot them.

import matplotlib.pyplot as plt

# Predict survival probabilities for the first 5 samples
surv_df = model.predict_surv_df(X[:5])

# Plot
plt.figure(figsize=(10, 6))
for col in surv_df.columns:
    plt.step(surv_df.index, surv_df[col], where="post")
plt.ylabel("Survival Probability")
plt.xlabel("Time")
plt.title("Predicted Survival Curves")
plt.show()

🔬 Mathematical Background

KMNet models the discrete conditional survival $p(t | x)$. The survival function is given by:

$$ \boxed{S(t | x) = \prod_{k=0}^{t} p(k | x)} $$

The loss function $\mathcal{L}$ is a weighted sum of two components:

$$ \boxed{\mathcal{L} = \alpha \mathcal{L}{bce} + (1 - \alpha)\lambda \mathcal{L}{Rank}} $$

📖 Click to expand detailed explanation

Loss Components

  1. $\mathcal{L}_{bce}$ (Censored likelihood, masked BCE):

    • Standard survival loss for discrete time
    • Ensures the model fits the observed event times
    • Handles censored data correctly
  2. $\mathcal{L}_{Rank}$ (Rank Loss):

    • Enforces correct ordering: $S(T_i | x_i) < S(T_i | x_j)$ if $T_i < T_j$
    • Inspired by the Kaplan-Meier estimator
    • Maintains global structure of survival curves
    • Differentiable approximation using softplus/exponential penalties

📊 Performance & Optimization

⚡ Speed Benchmarks

The KMNet class leverages TorchScript (JIT) to compile the custom loss functions, eliminating Python interpreter overhead.

Benchmark Setup:

  • 5,000 samples
  • 50 time bins
  • 10 epochs
  • CPU environment

Results:

🔥 JIT-Optimized: 1.38s
📈 Speedup: 1.6x faster
💾 Memory: ~15% reduction

Scalability:

Dataset Size Training Time
1K samples 0.3s/epoch
10K samples 2.1s/epoch
100K samples 18.5s/epoch

Tested on Intel i7, 16GB RAM


🛠️ Advanced Configuration

You can customize the loss function parameters when initializing the model:

  1. alpha (default 0.9): weight on the likelihood; 1 - alpha goes to the rank loss
  2. rank_weight (default 0.25) and sigma (default 'auto'): strength and softness of the ranking penalty
  3. rank_penalty: 'softplus' or 'exp' for the ranking loss formulation
from kmnet.model import KMLoss

loss = KMLoss(
    alpha=0.9,              # Weight for likelihood vs rank loss
    sigma='auto',           # Softness of the ranking penalty
    rank_weight=0.25,       # Extra weight on the rank loss
    rank_penalty='softplus' # 'softplus' or 'exp'
)

model = KMNet(net, loss=loss, duration_index=labtrans.cuts)

💬 Getting Help

🤝 Contributing

We welcome contributions! KMNet is an open-source research project.

How to contribute
  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Areas we'd love help with:

  • 📝 Documentation improvements
  • 🧪 Additional benchmarks and examples
  • 🐛 Bug fixes and testing
  • ✨ New features (e.g., competing risks, time-varying covariates)

📄 License

Distributed under the MIT License. See LICENSE for more information.

📚 Citation

KMNet accompanies a paper under review at TMLR (OpenReview). If you use KMNet in your research, please cite:

@article{anonymous2026deep,
  title   = {Deep Discrete-Time Survival Analysis with Guaranteed Monotonicity},
  author  = {Anonymous},
  journal = {Submitted to Transactions on Machine Learning Research},
  year    = {2026},
  url     = {https://openreview.net/forum?id=VXIk9iY10Q},
  note    = {Under review}
}

🏆 Acknowledgments

KMNet builds upon excellent work from:

  • PyCox for survival analysis utilities
  • TorchTuples for training infrastructure
  • The PyTorch team for JIT compilation capabilities

Built with ❤️ for the survival analysis community
⭐ Star us on GitHub if KMNet helps your research!

Metadata

Release files for kmnet 0.3.1

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

Source distribution (sdist)

Source distribution for kmnet 0.3.1
File Size Uploaded Provenance Actions
kmnet-0.3.1.tar.gz 74.0 kB Without provenance Details for kmnet-0.3.1.tar.gz

Built distribution (wheel)

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

Total release size: 86.0 kB

Release files / kmnet-0.3.1.tar.gz

Download URL kmnet-0.3.1.tar.gz
Size 74.0 kB
Tags Source
SHA-256 checksum
How to use checksums
21924bdfbd7424ca8821dbe5b020f274b75ac70fe0d9d8e04a0ce43162925955
BLAKE2b-256 checksum
How to use checksums
cb05ecde3906b67fb91db974fde9cbdb43d4ddabcfb3546bc512aa53bd1a52bc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Release files / kmnet-0.3.1-py3-none-any.whl

Download URL kmnet-0.3.1-py3-none-any.whl
Size 12.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
14e9fe0f062df0d96fdc82d6699ffef17c092ad41c434685481b96873f5409dd
BLAKE2b-256 checksum
How to use checksums
8c108c29ffb3d7f9bf9c80a114ff03d3ee972b1e2d744567dce1f2b5dbf9527d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for kmnet 0.3.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.3.1 This release

2 release files No provenance

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