ADBahadoSingh#

Index#

  1. Instantiate model class

  2. Define clock metadata

  3. Download clock dependencies

  4. Load features

  5. Load weights into base model

  6. Load reference values

  7. Load preprocess and postprocess objects

  8. Check all clock parameters

  9. Basic test

  10. Save torch model

  11. Clear directory

Let’s first import some packages:

[1]:
import os
import inspect
import shutil
import json
import torch
import pandas as pd
import pyaging as pya

Instantiate model class#

[2]:
def print_entire_class(cls):
    source = inspect.getsource(cls)
    print(source)

print_entire_class(pya.models.ADBahadoSingh)
class ADBahadoSingh(LinearReferenceClock):
    def postprocess(self, x):
        """Logistic transform to an Alzheimer's disease risk probability.

        The published logit constant (-0.072) is carried in the linear intercept.
        """
        return torch.sigmoid(x)

[3]:
model = pya.models.ADBahadoSingh()

Define clock metadata#

[4]:
model.metadata["clock_name"] = "adbahadosingh"
model.metadata["data_type"] = "DNA methylation"  # Paper: Genome-wide DNA methylation analysis
model.metadata["species"] = "Homo sapiens"  # Paper: 24 late-onset AD and 24 cognitively healthy subjects
model.metadata["year"] = 2021
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Bahado-Singh, R. O., Vishweswaraiah, S., Aydas, B., et al. (2021). Artificial intelligence and leukocyte epigenomics: Evaluation and prediction of late-onset Alzheimer's disease. PLOS ONE, 16(4), e0248375."
model.metadata["doi"] = "https://doi.org/10.1371/journal.pone.0248375"
model.metadata["notes"] = "PyAging implements the paper’s conventional four-CpG logistic-regression equation and applies a sigmoid to return LOAD case probability; it does not implement the separate high-dimensional deep-learning classifiers also evaluated in the paper."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"]  # Paper: Genomic DNA was extracted from whole blood samples; leukocyte epigenomic biomarkers
model.metadata["predicts"] = ["late-onset Alzheimer's disease"]  # Paper: where P is Pr(y = 1|x)
model.metadata["training_target"] = ["late-onset Alzheimer's disease"]  # Paper: 24 late-onset AD and 24 cognitively healthy subjects
model.metadata["unit"] = ["probability"]  # Paper: return torch.sigmoid(x)
model.metadata["model_type"] = "logistic regression"  # Paper: The logistic regression model is represented below
model.metadata["platform"] = ["Illumina EPIC"]  # Paper: Infinium MethylationEPIC array in 24 LOAD and 24 healthy subjects
model.metadata["population"] = "older adults"  # Paper: Cases: 83.17 (7.97); Controls: 80.04 (8.42)
model.metadata["journal"] = "PLOS ONE"
model.metadata["last_author"] = "Uppala Radhakrishna"
model.metadata["n_features"] = 4
model.metadata["citations"] = 33
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

[5]:
os.system(f"curl -sL -o coefficients.csv https://raw.githubusercontent.com/bio-learn/biolearn/180852e2bab473303cb85da627178b1695ee9d86/biolearn/data/AD_Bahado-Singh.csv")
[5]:
0

Load features#

[6]:
df = pd.read_csv('coefficients.csv')
mask = df['CpGmarker'].astype(str).str.lower().isin(['intercept', '(intercept)'])
coef_df = df.loc[~mask].reset_index(drop=True)
model.features = coef_df['CpGmarker'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(coef_df['CoefficientTraining'].tolist()).unsqueeze(0).float()
# Published logistic-regression constant (Bahado-Singh 2021, eq. e001)
intercept = torch.tensor([-0.072]).float()
[8]:
base_model = pya.models.LinearModel(input_dim=len(model.features))

base_model.linear.weight.data = weights.float()
base_model.linear.bias.data = intercept.float()

model.base_model = base_model

Load reference values#

[9]:
model.reference_values = None

Load preprocess and postprocess objects#

[10]:
model.preprocess_name = None
model.preprocess_dependencies = None
[11]:
model.postprocess_name = 'sigmoid'
model.postprocess_dependencies = None

Check all clock parameters#

[12]:
pya.utils.print_model_details(model)

%==================================== Model Details ====================================%
Model Attributes:

training: True
metadata: {'approved_by_author': '⌛',
 'citation': 'Bahado-Singh, Ray O., et al. "Artificial intelligence and '
             'leukocyte epigenomics: Evaluation and prediction of late-onset '
             'Alzheimer\'s disease." PLOS ONE 16.4 (2021): e0248375.',
 'clock_name': 'adbahadosingh',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1371/journal.pone.0248375',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2021}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'sigmoid'
postprocess_dependencies: None
features: ['cg02356786', 'cg04515524', 'cg00613827', 'cg07509935']
base_model_features: None

%==================================== Model Details ====================================%
Model Structure:

base_model: LinearModel(
  (linear): Linear(in_features=4, out_features=1, bias=True)
)

%==================================== Model Details ====================================%
Model Parameters and Weights:

base_model.linear.weight: tensor([[-0.9920, -1.5000, -1.9010, -1.3580]])
base_model.linear.bias: tensor([-0.0720])

%==================================== Model Details ====================================%

Basic test#

[13]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[13]:
tensor([[0.2779],
        [0.9795],
        [0.1451],
        [0.7133],
        [0.0025],
        [0.1557],
        [0.9681],
        [0.7552],
        [0.9825],
        [0.5411]], dtype=torch.float64, grad_fn=<SigmoidBackward0>)

Save torch model#

[14]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")

Clear directory#

[15]:
# Function to remove a folder and all its contents
def remove_folder(path):
    try:
        shutil.rmtree(path)
        print(f"Deleted folder: {path}")
    except Exception as e:
        print(f"Error deleting folder {path}: {e}")

# Get a list of all files and folders in the current directory
all_items = os.listdir('.')

# Loop through the items
for item in all_items:
    # Check if it's a file and does not end with .ipynb
    if os.path.isfile(item) and not item.endswith('.ipynb'):
        os.remove(item)
        print(f"Deleted file: {item}")
    # Check if it's a folder
    elif os.path.isdir(item):
        remove_folder(item)
Deleted file: coefficients.csv