ZhangMortality#

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.ZhangMortality)
class ZhangMortality(pyagingModel):
    def __init__(self):
        super().__init__()

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'zhangmortality'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2017
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Zhang, Yan, et al. \"DNA methylation signatures in peripheral blood strongly predict all-cause mortality.\" Nature communications 8.1 (2017): 14617."
model.metadata["doi"] = "https://doi.org/10.1038/ncomms14617"
model.metadata["research_only"] = None
model.metadata["notes"] = "Peripheral-blood methylation risk score for all-cause mortality derived from 10 CpGs selected by LASSO Cox regression from epigenome-wide screening. The score stratifies mortality risk independently of chronological-age epigenetic clocks, with several CpGs also linked to smoking."
model.metadata["tissue"] = 'whole blood (peripheral blood)'
model.metadata["predicts"] = 'all-cause mortality risk'
model.metadata["unit"] = 'relative risk/hazard'
model.metadata["model_type"] = 'Cox regression'
model.metadata["platform"] = 'Illumina 450K'
model.metadata["population"] = 'adults (general population, ~50-75 years)'
model.metadata["journal"] = 'Nature Communications'
model.metadata["last_author"] = 'Hermann Brenner'
model.metadata["n_features"] = 10
model.metadata["citations"] = 404
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
features = [
    'cg01612140',
    'cg05575921',
    'cg06126421',
    'cg08362785',
    'cg10321156',
    'cg14975410',
    'cg19572487',
    'cg23665802',
    'cg24704287',
    'cg25983901'
]

coefficients = [
    -0.38253,
    -0.92224,
    -1.70129,
    2.71749,
    -0.02073,
    -0.04156,
    -0.28069,
    -0.89440,
    -2.98637,
    -1.80325,
]

Load features#

[6]:
model.features = features

Load weights into base model#

[7]:
weights = torch.tensor(coefficients).unsqueeze(0)
intercept = torch.tensor([0.0])

Linear model#

[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 = None
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': 'Zhang, Yan, et al. "DNA methylation signatures in peripheral '
             'blood strongly predict all-cause mortality." Nature '
             'communications 8.1 (2017): 14617.',
 'clock_name': 'zhangmortality',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1038/ncomms14617',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2017}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg01612140',
 'cg05575921',
 'cg06126421',
 'cg08362785',
 'cg10321156',
 'cg14975410',
 'cg19572487',
 'cg23665802',
 'cg24704287',
 'cg25983901']
base_model_features: None

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

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

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

base_model.linear.weight: tensor([[-0.3825, -0.9222, -1.7013,  2.7175, -0.0207, -0.0416, -0.2807, -0.8944,
         -2.9864, -1.8032]])
base_model.linear.bias: tensor([0.])

%==================================== 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.4323],
        [ -7.2390],
        [ -4.4894],
        [ -0.7974],
        [  2.5606],
        [ -0.6228],
        [ -4.8378],
        [ -6.7516],
        [-10.8399],
        [ -3.3397]], dtype=torch.float64, grad_fn=<AddmmBackward0>)

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)