ZhangMortality#
Index#
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"] = "DNA methylation" # Paper: The score is based on whole-blood DNA methylation.
model.metadata["species"] = "Homo sapiens" # Paper: The ESTHER and KORA cohorts comprise human participants.
model.metadata["year"] = 2017
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Zhang, Y., Wilson, R., Heiss, J. et al. DNA methylation signatures in peripheral blood strongly predict all-cause mortality. Nature Communications 8, 14617 (2017)."
model.metadata["doi"] = "https://doi.org/10.1038/ncomms14617"
model.metadata["notes"] = "Ten-CpG whole-blood mortality risk score. Pyaging implements the paper supplement's continuous LASSO-weighted score exactly (the sum of ten raw beta values multiplied by their published coefficients). The same study also defines a separate simplified 0-10 aberrant-methylation count based on cohort-specific quartile cutoffs."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"] # Paper: DNAm was quantified in baseline whole blood.
model.metadata["predicts"] = ["mortality risk"] # Paper: The implementation returns a continuous weighted methylation score from the ten mortality CpGs.
model.metadata["training_target"] = ["mortality"] # Paper: Ten CpGs were selected from mortality-associated loci for an all-cause mortality risk score.
model.metadata["unit"] = ["unitless"] # Paper: The pyaging model applies no postprocess and returns the weighted sum directly.
model.metadata["model_type"] = "weighted linear score" # Paper: The implementation is a one-layer linear weighted sum of ten methylation beta values.
model.metadata["platform"] = ["Illumina 450K"] # Paper: Whole-blood DNAm was measured using the Infinium HumanMethylation450K BeadChip.
model.metadata["population"] = "older adults" # Paper: The ESTHER general-population cohort enrolled adults aged 50 to 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)