EnsembleAgeHumanMouse#

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.EnsembleAgeHumanMouse)
class EnsembleAgeHumanMouse(LinearReferenceClock):
    pass

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = 'ensembleagehumanmouse'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2025
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Haghani, Amin, et al. \"EnsembleAge: an ensemble of epigenetic clocks for robust age estimation.\" GeroScience (2025)."
model.metadata["doi"] = "https://doi.org/10.1007/s11357-025-01808-1"
model.metadata["research_only"] = None
model.metadata["notes"] = "Cross-species ensemble epigenetic clock that aggregates predictions from multiple penalized DNA-methylation models to robustly estimate age across both human and mouse samples, enabling translational comparison of aging and rejuvenation interventions."
model.metadata["tissue"] = 'multi-tissue (mouse and human; blood and multiple organs)'
model.metadata["predicts"] = 'chronological age (cross-species)'
model.metadata["unit"] = 'years'
model.metadata["model_type"] = 'ensemble'
model.metadata["platform"] = 'Mammalian methylation array'
model.metadata["population"] = 'pan-age, cross-species (human and mouse)'
model.metadata["journal"] = 'GeroScience'
model.metadata["last_author"] = 'Steve Horvath'
model.metadata["n_features"] = 2252
model.metadata["citations"] = 3
model.metadata["citations_date"] = '2026-07-05'

Download clock dependencies#

[5]:
supplementary_url = "https://raw.githubusercontent.com/Duzhaozhen/OmniAge/c10fbe8cb92957520fbff1d55ae1def0691252e5/OmniAgePy/src/omniage/data/EnsembleAge/EnsembleAge_HumanMouse_HumanMouse_coefs.csv"
supplementary_file_name = "coefficients.csv"
os.system(f"curl -sL -o {supplementary_file_name} {supplementary_url}")
[5]:
0

Load features#

[6]:
df = pd.read_csv('coefficients.csv')
if str(df.columns[0]).startswith('Unnamed'):
    df = df.iloc[:, 1:]
mask = df['probe'].astype(str).str.lower().isin(['intercept', '(intercept)'])
intercept_value = float(df.loc[mask, 'coef'].iloc[0]) if mask.any() else 0.0
coef_df = df.loc[~mask].reset_index(drop=True)
model.features = coef_df['probe'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(coef_df['coef'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([intercept_value]).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 = 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': 'Haghani, Amin, et al. "EnsembleAge: an ensemble of epigenetic '
             'clocks for robust age estimation." GeroScience (2025).',
 'clock_name': 'ensembleagehumanmouse',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1007/s11357-025-01808-1',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2025}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00001364', 'cg00001582', 'cg00003994', 'cg00005112', 'cg00051782', 'cg00060304', 'cg00066554', 'cg00067884', 'cg00073543', 'cg00079224', 'cg00084577', 'cg00091964', 'cg00096922', 'cg00109076', 'cg00109300', 'cg00116234', 'cg00146676', 'cg00158333', 'cg00159243', 'cg00167491', 'cg00187380', 'cg00211337', 'cg00216659', 'cg00247020', 'cg00271154', 'cg00272971', 'cg00297075', 'cg00314427', 'cg00323965', 'cg00331096']... [Total elements: 2252]
base_model_features: None

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

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

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

base_model.linear.weight: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.02849973551928997, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -0.27547580003738403, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]... [Tensor of shape torch.Size([1, 2252])]
base_model.linear.bias: tensor([-0.5651])

%==================================== 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([[-1.0967],
        [ 0.8136],
        [-3.3391],
        [-0.1142],
        [-1.4556],
        [ 2.6708],
        [-3.5248],
        [-2.2007],
        [-4.3380],
        [-1.6859]], 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.csv