Skip to main content

A library for estimating Biological Age using classical and ML methods

Project description

tse_ba_comp

PyPI version Python 3.7+

tse_ba_comp stands for Tse Biological Age Comparator (named after Prof. Gary Tse's Research Group) is a robust, easy-to-use Python library for estimating Biological Age (BA) from clinical biomarkers.

Developed by Mehrdad S. Beni & Gary Tse, this package evaluates and ensembles classical mathematical approaches against modern Machine Learning models to provide highly accurate, cross-validated age estimations.

Key Features

  • Classical Models: Fast, vectorized implementations of the Klemera-Doubal Method (KDM) and PCA-Dubina.
  • Machine Learning: Automated pipelines for Elastic Net, Random Forest, and XGBoost.
  • Smart Ensembling: Automatically combine predictions using Mean or Median strategies to smooth out variance.
  • Automated Preprocessing: Handles train/test splitting, scaling, and missing data imputation safely to prevent data leakage.
  • Built-in Visualization: Generates standardized, publication-ready scatter plots of Biological Age vs. Chronological Age.

Installation

Install directly from PyPI:

pip install tse-ba-comp


Examples & Usage

Example 1: Quick Start (Default & Shortest)

The easiest way to use the library is to pass a CSV dataset file path directly to the run function. The library uses highly optimized defaults out-of-the-box.

import tse_ba_comp

my_biomarkers = ["albumin", "alp", "bun", "creat", "hba1c", "glucose", "sbp"]

results = tse_ba_comp.run(
    data="nhanes4_model_input.csv",
    biomarkers=my_biomarkers,
    out="my_results_folder"  # Automatically saves plots and CSVs here
)

print(results["metrics"])

Example 2: ML Auto Tuning & Control

Pass a list of models to ml and set tune=True to let the library automatically grid search the best hyperparameters for those specific models.

import tse_ba_comp

my_biomarkers = ["albumin", "alp", "bun", "creat", "hba1c", "glucose", "sbp"]

results = tse_ba_comp.run(
    data="nhanes4_model_input.csv",
    biomarkers=my_biomarkers,
    impute="knn",              # switch imputation to knn
    seed=101,                  # fix random seed for reproducibility
    ml=["rf", "xgb"],          # only run Random Forest & XGBoost
    tune=True,                 # trigger automated Grid Search
    out="advanced_results"
)

print(results["metrics"])

Example 3: Comprehensive Pipeline (All parameters that our lib offer)

For full programmatic control, you can utilize every argument the library offers and pass an exact dictionary of fixed hyperparameters to bypass the automated grid search.

import tse_ba_comp

my_biomarkers = ["albumin", "alp", "bun", "creat", "hba1c", "glucose", "sbp"]

# Define exact parameters to pass to scikit-learn / XGBoost
custom_ml_settings = {
    "en": {"l1_ratio": 0.7},
    "rf": {"n_estimators": 200, "max_depth": 10},
    "xgb": {"n_estimators": 150, "learning_rate": 0.05, "max_depth": 4}
}

results = tse_ba_comp.run(
    data="nhanes4_model_input.csv",
    biomarkers=my_biomarkers,
    age="age",                      # target column name
    impute="mean",                  # imputation strategy
    test_size=0.25,                 # hold out 25% for testing
    seed=42,                        # random seed
    kdm=True,                       # enable Klemera-Doubal Method
    kdm_s2_floor=0.05,              # tweak KDM variance floor
    pca=True,                       # enable PCA-Dubina
    ml=custom_ml_settings,          # apply custom ML settings directly
    tune=False,                     # skip grid search
    cv_folds=5,                     # cross-validation folds
    ensemble="mean",                # use arithmetic mean for ensemble
    out="all_keywords_results"
)

print(results["metrics"])

Complete API Reference

Below is the complete list of arguments accepted by the run function.

Core Data Settings

  • data (str or pandas.DataFrame): Path to your CSV file, or a loaded Pandas DataFrame.
  • biomarkers (list of str): List of column names representing the biomarkers to be used.
  • age (str): The column name containing chronological age. Default: "age".

Processing & Splitting

  • impute (str): How to handle missing data. Options: "median", "mean", "zero", "knn". Default: "median".
  • test_size (float): The fraction of the dataset to hold out for testing and evaluation. Default: 0.2.
  • seed (int): Random seed to ensure reproducible train/test splits. Default: 42.

Classical Model Toggles

  • kdm (bool): Toggle the Klemera-Doubal Method. Default: True.
  • kdm_s2_floor (float): Minimum variance floor for KDM calculations to prevent division by near-zero. Default: 0.1.
  • pca (bool): Toggle the PCA-Dubina method. Default: True.

Machine Learning Settings

  • ml (bool, list, or dict): Controls the ML models.
    • True: Runs Elastic Net ("en"), Random Forest ("rf"), and XGBoost ("xgb") with defaults.
    • False: Skips ML entirely.
    • list: E.g., ["rf", "en"] runs only specific models.
    • dict: Passes explicit kwargs to the underlying model constructors.
  • tune (bool): If True, runs a GridSearchCV over a predefined parameter grid for the active ML models. Default: False.
  • cv_folds (int): Number of cross-validation folds used during training/tuning. Default: 5.

Ensemble & Outputs

  • ensemble (str or None): How to combine the model predictions. Options: "median", "mean", or None (to skip). Default: "median".
  • out (str or None): Directory path to save the generated scatter plots and prediction CSVs. If None, no files are saved to the disk.

Outputs

The run function returns a dictionary with two keys:

  1. results["metrics"]: A Pandas DataFrame containing the Pearson r, R², RMSE, and MAE for all executed models evaluated strictly on the test set.
  2. results["predictions"]: A Pandas DataFrame mapping the Chronological Age to the estimated Biological Ages for every patient in the test set.

Developers

Developed by Dr. Mehrdad S. Beni and Prof. Gary Tse at Hong Kong Metropolitan University, 2026.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tse_ba_comp-0.1.4.tar.gz (22.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tse_ba_comp-0.1.4-py3-none-any.whl (21.7 kB view details)

Uploaded Python 3

File details

Details for the file tse_ba_comp-0.1.4.tar.gz.

File metadata

  • Download URL: tse_ba_comp-0.1.4.tar.gz
  • Upload date:
  • Size: 22.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for tse_ba_comp-0.1.4.tar.gz
Algorithm Hash digest
SHA256 af15fb059d91aae0232e7b949c5cea2ed28eb8dbefa1dd091ed1fc252b5b6e5a
MD5 7f6706f569988c597c80d6c5a1bead96
BLAKE2b-256 5d245d14ef8b83f856130f0d3f1876bcb2d9e130564dfe068aad432dcb79612e

See more details on using hashes here.

File details

Details for the file tse_ba_comp-0.1.4-py3-none-any.whl.

File metadata

  • Download URL: tse_ba_comp-0.1.4-py3-none-any.whl
  • Upload date:
  • Size: 21.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for tse_ba_comp-0.1.4-py3-none-any.whl
Algorithm Hash digest
SHA256 87d9ede16cf310e4b418c278288faec737fc3807ff9c9f65c7f287fe2174c94e
MD5 18de494f5b9c26e775d379e4b4c7653b
BLAKE2b-256 de5e0232f0b68cbbbe63f1f83e77c1246b22456b1db18aff95723ce0c0b4f91a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page