Hannum#

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

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "hannum"
model.metadata["data_type"] = "DNA methylation"  # Paper: The model uses genome-wide CpG methylation fractions.
model.metadata["species"] = "Homo sapiens"  # Paper: The cohorts contained 656 human participants.
model.metadata["year"] = 2013
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Hannum, G., et al. “Genome-wide methylation profiles reveal quantitative views of human aging rates.” Molecular Cell 49(2), 359–367 (2013)."
model.metadata["doi"] = "https://doi.org/10.1016/j.molcel.2012.10.016"
model.metadata["notes"] = "Whole-blood elastic-net predictor of chronological age from 71 CpG methylation fractions, derived in a 482-person primary cohort and validated in 174 independent participants."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"]  # Paper: Samples were taken as whole blood.
model.metadata["predicts"] = ["chronological age"]  # Paper: The model was built to predict participant age.
model.metadata["training_target"] = ["chronological age"]  # Paper: Age was the response in the predictive aging model.
model.metadata["unit"] = ["years"]  # Paper: The packaged linear model returns predicted age directly in years with no postprocessing transform.
model.metadata["model_type"] = "elastic net regression"  # Paper: The predictive model used penalized multivariate regression known as Elastic Net.
model.metadata["platform"] = ["Illumina 450K"]  # Paper: Whole-blood samples were processed on the Infinium HumanMethylation450 BeadChip.
model.metadata["population"] = "adults"  # Paper: Two cohorts totaled 656 participants aged 19–101 years, comprising 426 Caucasian and 230 Hispanic individuals.
model.metadata["journal"] = "Molecular Cell"
model.metadata["last_author"] = "Kang Zhang"
model.metadata["n_features"] = 71
model.metadata["citations"] = 4501
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

Download directly with curl#

[5]:
supplementary_url = "https://ars.els-cdn.com/content/image/1-s2.0-S1097276512008933-mmc2.xlsx"
supplementary_file_name = "coefficients.xlsx"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
[5]:
0

Load features#

From Excel file#

[6]:
df = pd.read_excel('coefficients.xlsx')
df['feature'] = df['Marker']
df['coefficient'] = df['Coefficient']
model.features = df['feature'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(df['coefficient'].tolist()).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': ('Hannum, Gregory, et al. "Genome-wide methylation profiles '
              'reveal quantitative views of human aging rates." Molecular cell '
              '49.2 (2013): 359-367.',),
 'clock_name': 'hannum',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1016/j.molcel.2012.10.016',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2013}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg20822990', 'cg22512670', 'cg25410668', 'cg04400972', 'cg16054275', 'cg10501210', 'cg09809672', 'ch.2.30415474F', 'cg22158769', 'cg02085953', 'cg06639320', 'cg22454769', 'cg24079702', 'cg23606718', 'cg22016779', 'cg04474832', 'cg03607117', 'cg07553761', 'cg00481951', 'cg25478614', 'cg25428494', 'cg02650266', 'cg08234504', 'cg23500537', 'cg20052760', 'cg16867657', 'cg22736354', 'cg06493994', 'cg06685111', 'cg00486113']... [Total elements: 71]
base_model_features: None

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

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

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

base_model.linear.weight: [-15.699999809265137, 1.0499999523162842, 3.869999885559082, 9.619999885559082, -11.100000381469727, -6.460000038146973, -0.7400000095367432, 5.789999961853027, -2.059999942779541, 1.0199999809265137, 8.949999809265137, 4.849999904632568, 2.4800000190734863, 8.350000381469727, 1.7899999618530273, -7.099999904632568, 10.699999809265137, 3.7200000286102295, -2.7200000286102295, 4.010000228881836, -1.809999942779541, 10.199999809265137, -3.1600000858306885, 5.670000076293945, -12.600000381469727, 10.800000190734863, 4.420000076293945, 9.420000076293945, -13.100000381469727, -10.699999809265137]... [Tensor of shape torch.Size([1, 71])]
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([[ 78.6234],
        [  7.5513],
        [172.7843],
        [ 43.1732],
        [145.3521],
        [ 79.6871],
        [ 75.0541],
        [ 41.7890],
        [-12.6555],
        [-78.9716]], 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)
Deleted file: coefficients.xlsx