Weidner#

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

    def preprocess(self, x):
        if self.reference_values is None:
            return x
        if isinstance(self.reference_values, torch.Tensor):
            reference = self.reference_values.to(device=x.device, dtype=x.dtype)
        else:
            reference = torch.tensor(self.reference_values, device=x.device, dtype=x.dtype)
        return torch.where(torch.isnan(x), reference, x)

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "weidner"
model.metadata["data_type"] = "DNA methylation"  # Paper: DNA methylation changes at just three CpG sites
model.metadata["species"] = "Homo sapiens"  # Paper: blood samples from healthy human donors
model.metadata["year"] = 2014
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Weidner, C. I., Lin, Q., Koch, C. M., et al. (2014). Aging of blood can be tracked by DNA methylation changes at just three CpG sites. Genome Biology, 15, R24."
model.metadata["doi"] = "https://doi.org/10.1186/gb-2014-15-2-r24"
model.metadata["notes"] = "Three-site whole-blood epigenetic-age estimator. The sites were selected from Illumina 27K blood profiles, and the final multivariate linear equation was fitted on targeted bisulfite-pyrosequencing beta values from 82 blood samples and validated in 69 independent samples."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"]  # Paper: DNAm profiles derived from blood samples; model fitted on blood samples
model.metadata["predicts"] = ["biological age"]  # Paper: signature provides a simple biomarker to estimate the state of aging in blood
model.metadata["training_target"] = ["chronological age"]  # Paper: multivariate linear model to predict donor age
model.metadata["unit"] = ["years"]  # Paper: Predicted age (in years)
model.metadata["model_type"] = "linear regression"  # Paper: multivariate linear regression model
model.metadata["platform"] = ["Illumina 27K", "bisulfite sequencing"]  # Paper: HumanMethylation27 BeadChip feature selection followed by pyrosequencing after bisulfite conversion
model.metadata["population"] = "adults"  # Paper: 82 blood samples for training and independent validation set of 69 blood samples
model.metadata["journal"] = "Genome Biology"
model.metadata["last_author"] = "Wolfgang Wagner"
model.metadata["n_features"] = 3
model.metadata["citations"] = 973
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

[5]:
supplementary_url = "https://raw.githubusercontent.com/bio-learn/biolearn/180852e2bab473303cb85da627178b1695ee9d86/biolearn/data/Weidner.csv"
supplementary_file_name = "Weidner.csv"
os.system(f"curl -sL -o {supplementary_file_name} {supplementary_url}")
[5]:
0

Load features#

[6]:
df = pd.read_csv('Weidner.csv')
model.features = df['CpGmarker'].tolist()

Load weights into base model#

[7]:
weights = torch.tensor(df['CoefficientTraining'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([38.0]).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': 'Weidner, Carola I., et al. "Aging of blood can be tracked by DNA '
             'methylation changes at just three CpG sites." Genome biology '
             '15.2 (2014): R24.',
 'clock_name': 'weidner',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1186/gb-2014-15-2-r24',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2014}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg02228185', 'cg25809905', 'cg17861230']
base_model_features: None

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

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

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

base_model.linear.weight: tensor([[-26.4000, -23.7000, 164.7000]])
base_model.linear.bias: tensor([38.])

%==================================== 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([[ 70.9916],
        [157.0004],
        [155.2728],
        [ 58.9885],
        [ 38.9402],
        [143.5184],
        [396.4215],
        [ 66.8971],
        [130.9565],
        [-26.1560]], 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: Weidner.csv