ZhangEN#

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

    def preprocess(self, x):
        """
        Scales the input PyTorch tensor per row with mean 0 and std 1.
        """
        row_means = torch.mean(x, dim=1, keepdim=True)
        row_stds = torch.std(x, dim=1, keepdim=True)

        # Avoid division by zero in case of a row with constant value
        row_stds = torch.where(row_stds == 0, torch.ones_like(row_stds), row_stds)

        x_scaled = (x - row_means) / row_stds
        return x_scaled

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "zhangen"
model.metadata["data_type"] = "DNA methylation"  # Paper: The predictors use DNA-methylation beta values.
model.metadata["species"] = "Homo sapiens"  # Paper: The training collection comprises human blood and saliva cohorts.
model.metadata["year"] = 2019
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Zhang, Q., Vallerga, C.L., Walker, R.M. et al. Improved precision of epigenetic clock estimates across tissues and its implication for biological ageing. Genome Medicine 11, 54 (2019)."
model.metadata["doi"] = "https://doi.org/10.1186/s13073-019-0667-1"
model.metadata["notes"] = "Elastic-net chronological-age predictor released from the largest multi-cohort training set, using 514 selected CpGs from predominantly blood plus saliva data."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood", "saliva"]  # Paper: The assembled training collection contained 13,402 blood and 259 saliva samples.
model.metadata["predicts"] = ["chronological age"]  # Paper: Both released predictors estimate chronological age.
model.metadata["training_target"] = ["chronological age"]  # Paper: Chronological age was the regression outcome.
model.metadata["unit"] = ["years"]  # Paper: Predicted chronological age and prediction error are reported in years.
model.metadata["model_type"] = "elastic net regression"  # Paper: Elastic net was used to select and shrink CpG effects for the released predictor.
model.metadata["platform"] = ["Illumina 450K", "Illumina EPIC"]  # Paper: The 14 training cohorts were measured on HumanMethylation450 and EPIC arrays.
model.metadata["population"] = "all ages"  # Paper: The assembled 14-cohort collection spanned ages 2–104 years.
model.metadata["journal"] = "Genome Medicine"
model.metadata["last_author"] = "Peter M. Visscher"
model.metadata["n_features"] = 514
model.metadata["citations"] = 519
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

Download GitHub repository#

[5]:
github_url = "https://github.com/qzhang314/DNAm-based-age-predictor.git"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")
[5]:
0

Download from R package#

[6]:
%%writefile download.r

data = readRDS("DNAm-based-age-predictor/data.rds")

write.csv(data, "example_data.csv")
Writing download.r
[7]:
os.system("Rscript download.r")
[7]:
0

Load features#

From CSV file#

[8]:
df = pd.read_table('DNAm-based-age-predictor/en.coef', sep=' ')
df['feature'] = df['probe']
df['coefficient'] = df['coef']

model.features = df['feature'][1:].tolist()

Load weights into base model#

[9]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'][0]])

Linear model#

[10]:
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#

From CSV file#

[11]:
reference_feature_values_df = pd.read_csv('example_data.csv', index_col=0)
reference_feature_values_df = reference_feature_values_df.loc[:, model.features]
model.reference_values = reference_feature_values_df.mean().tolist()

Load preprocess and postprocess objects#

[12]:
model.preprocess_name = 'scale_row'
model.preprocess_dependencies = None
[13]:
model.postprocess_name = None
model.postprocess_dependencies = None

Check all clock parameters#

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

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

training: True
metadata: {'approved_by_author': '⌛',
 'citation': 'Zhang, Qian, et al. "Improved precision of epigenetic clock '
             'estimates across tissues and its implication for biological '
             'ageing." Genome medicine 11 (2019): 1-11.',
 'clock_name': 'zhangen',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1186/s13073-019-0667-1',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2019}
reference_values: [0.4203926578618443, 0.4908907575500855, 0.4552739071801655, 0.4913173878831697, 0.1630209603278157, 0.28031076416301215, 0.5630446021353376, 0.07173451377952844, 0.5286791351513329, 0.4914897138593993, 0.8776324935503583, 0.7783989797577173, 0.3679109172453385, 0.5469457656601266, 0.36321717183155133, 0.3929905988245433, 0.11900061695097393, 0.1448950534091979, 0.11166595534101968, 0.08958121797351054, 0.262072821834283, 0.4936214944065201, 0.07967343711600829, 0.4159523391121834, 0.6393676229693106, 0.28478196991507315, 0.2528507814707874, 0.3516112115460574, 0.4707586149929079, 0.8216726560029178]... [Total elements: 514]
preprocess_name: 'scale_row'
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg24611351', 'cg24173182', 'cg09604333', 'cg13617776', 'cg09432590', 'cg05516505', 'cg12757684', 'cg23606718', 'cg20050761', 'cg22452230', 'cg05898618', 'cg01620164', 'cg06758350', 'cg23615741', 'cg09692396', 'cg02046143', 'cg08540945', 'cg11714320', 'cg22708738', 'cg21567504', 'cg08313880', 'cg03527802', 'cg23995914', 'cg04027548', 'cg07077459', 'cg03025830', 'cg07978099', 'cg24349631', 'cg04218760', 'cg24788483']... [Total elements: 514]
base_model_features: None

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

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

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

base_model.linear.weight: [-0.0018107433570548892, -0.2039545476436615, -0.703967809677124, -0.011524459347128868, 1.048977255821228, -0.14274194836616516, -0.7550708651542664, 3.435948610305786, -0.025350039824843407, -0.5448949933052063, -0.8968744874000549, -0.787463366985321, -0.06834892183542252, -0.7093232870101929, -1.467730164527893, -0.6339927315711975, 0.032782625406980515, -0.8660809397697449, 0.12924738228321075, 0.6532240509986877, -0.5267062187194824, -0.07851535081863403, 0.6190375089645386, -1.0144543647766113, -0.03378598392009735, 0.1000944972038269, -0.037325769662857056, -0.029759708791971207, -0.07072985917329788, -1.4537116289138794]... [Tensor of shape torch.Size([1, 514])]
base_model.linear.bias: tensor([65.7930])

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

Basic test#

[15]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[15]:
tensor([[ 28.2548],
        [104.3112],
        [ 83.9525],
        [ 78.0909],
        [ 60.1387],
        [ 63.0642],
        [ 67.6295],
        [ 73.1206],
        [ 72.9059],
        [ 56.8473]], dtype=torch.float64, grad_fn=<AddmmBackward0>)

Save torch model#

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

Clear directory#

[17]:
# 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: download.r
Deleted folder: DNAm-based-age-predictor
Deleted file: example_data.csv