Lin#

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

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return x

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "lin"
model.metadata["data_type"] = "DNA methylation"  # Paper: The model uses DNA methylation beta values at age-associated CpGs.
model.metadata["species"] = "Homo sapiens"  # Paper: Training and evaluation used human blood cohorts.
model.metadata["year"] = 2016
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Lin, Q., et al. “DNA methylation levels at individual age-associated CpG sites can be indicative for life expectancy.” Aging 8(2): 394–401 (2016)."
model.metadata["doi"] = "https://doi.org/10.18632/aging.100908"
model.metadata["notes"] = "Whole-blood 99-CpG multivariate age estimator trained to predict chronological age; age acceleration from the model was secondarily tested for association with all-cause mortality."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["whole blood"]  # Paper: The 99-CpG model was trained on blood DNA methylation profiles.
model.metadata["predicts"] = ["chronological age"]  # Paper: The model produces predicted age and was validated against chronological age.
model.metadata["training_target"] = ["chronological age"]  # Paper: The age predictor was trained on donor ages in the Hannum blood dataset.
model.metadata["unit"] = ["years"]  # Paper: The paper explicitly reports predicted age in years.
model.metadata["model_type"] = "linear regression"  # Paper: The packaged 99-CpG estimator is a single linear layer with an intercept.
model.metadata["platform"] = ["Illumina 27K", "Illumina 450K"]  # Paper: CpGs were discovered on HumanMethylation27 data and the 99-CpG model was trained/applied using HumanMethylation450 data.
model.metadata["population"] = "adults"  # Paper: The Hannum training dataset comprised 656 blood profiles with ages 19–101 years.
model.metadata["journal"] = "Aging"
model.metadata["last_author"] = "Wolfgang Wagner"
model.metadata["n_features"] = 99
model.metadata["citations"] = 256
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

[5]:
# from https://www.aging-us.com/article/100908/text supplement
cpg_sites = [
    "(Intercept)", "cg05228408", "cg16352283", "cg05436231", "cg19046959",
    "cg17791651", "cg07388493", "cg04036898", "cg07810156", "cg21448423",
    "cg18660898", "cg25256723", "cg21870884", "cg25947945", "cg09462576",
    "cg09809672", "cg27553955", "cg27320127", "cg15297650", "cg05331214",
    "cg24178740", "cg18182399", "cg25431974", "cg24768561", "cg26614073",
    "cg23320649", "cg12554573", "cg04474832", "cg17421623", "cg22919728",
    "cg14456683", "cg08209133", "cg16744741", "cg00059225", "cg00489401",
    "cg02844545", "cg22736354", "cg06493994", "cg03340878", "cg03958979",
    "cg15804973", "cg13870866", "cg00503840", "cg25762706", "cg25538571",
    "cg08598221", "cg19724470", "cg07211259", "cg13870494", "cg16386080",
    "cg00563932", "cg21120249", "cg26581729", "cg17431739", "cg13129046",
    "cg01560871", "cg06291867", "cg26610808", "cg07621046", "cg13807496",
    "cg20654468", "cg21992250", "cg15538427", "cg08012287", "cg01820374",
    "cg19722847", "cg12883767", "cg04123409", "cg22580512", "cg25268718",
    "cg21296230", "cg21801378", "cg10917602", "cg15195412", "cg20264732",
    "cg22947000", "cg02228185", "cg01739167", "cg14918082", "cg05379350",
    "cg08468689", "cg08090640", "cg25809905", "cg05294455", "cg06638433",
    "cg20366832", "cg19761273", "cg26927807", "cg17471102", "cg02489552",
    "cg05488632", "cg16363586", "cg17861230", "cg24713204", "cg23679724",
    "cg03224418", "cg15379633", "cg02994956", "cg23124451", "cg26394940"
]
coefficients = [
    12.2169841, 0.47636173, -5.3124138, 17.7305146, -13.367066, 8.72680959, -4.7759575,
    10.162153, 15.3892025, -4.4621797, 13.2543665, -11.802998, 22.9981412, -8.2387336,
    6.3124836, -14.950409, -0.7884001, 48.9368049, -34.306553, 9.83640629, -27.476107,
    -4.1527608, -1.048605, -4.5917403, -11.443446, 8.70555476, 1.81880164, -26.556597,
    2.4399993, 0.99214006, 13.1457167, 30.500322, -9.5846721, 36.8195086, 1.98682848,
    0.38022482, 36.9317174, 66.1611861, 5.95485236, -16.016804, -15.214138, -39.104364,
    31.2113275, 1.5340163, 10.2956593, 2.62080161, -5.5537073, -12.424324, 19.7417678,
    -29.24993, -3.5009711, -8.6074197, -7.9914389, 8.22589722, -5.1368284, 13.5034883,
    13.0769424, -21.374356, 13.6468199, -8.3931276, 8.14605552, 10.5216611, -19.93487,
    -18.989957, -30.896866, -13.06341, 8.45912249, -10.767354, -0.8383178, 4.06576438,
    28.1787443, 44.7163476, -6.0293979, 20.050343, -20.618882, -13.217155, -8.6363427,
    33.8101434, 15.5554908, 17.340667, -16.062905, 8.31318309, -6.0974732, 2.71073045,
    10.6229217, 2.97899616, -16.331359, 16.5195276, -18.063487, 6.09699424, -11.249025,
    13.6452671, 17.5027126, -32.487323, 0.25793126, 8.07556639, 15.4139903, -6.4516149,
    -13.361462, 0.89292205
]

Load features#

[6]:
df = pd.DataFrame({
    'feature': cpg_sites,
    'coefficient': coefficients
})

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

Load weights into base model#

[7]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'][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': 'Lin, Qiong, et al. "DNA methylation levels at individual '
             'age-associated CpG sites can be indicative for life expectancy." '
             'Aging (Albany NY) 8.2 (2016): 394.',
 'clock_name': 'lin',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.18632/aging.100908',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2016}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg05228408', 'cg16352283', 'cg05436231', 'cg19046959', 'cg17791651', 'cg07388493', 'cg04036898', 'cg07810156', 'cg21448423', 'cg18660898', 'cg25256723', 'cg21870884', 'cg25947945', 'cg09462576', 'cg09809672', 'cg27553955', 'cg27320127', 'cg15297650', 'cg05331214', 'cg24178740', 'cg18182399', 'cg25431974', 'cg24768561', 'cg26614073', 'cg23320649', 'cg12554573', 'cg04474832', 'cg17421623', 'cg22919728', 'cg14456683']... [Total elements: 99]
base_model_features: None

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

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

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

base_model.linear.weight: [0.4763617217540741, -5.312413692474365, 17.730514526367188, -13.367066383361816, 8.72680950164795, -4.7759575843811035, 10.162153244018555, 15.389202117919922, -4.462179660797119, 13.254366874694824, -11.802997589111328, 22.998140335083008, -8.238733291625977, 6.312483787536621, -14.950408935546875, -0.7884001135826111, 48.936805725097656, -34.30655288696289, 9.836406707763672, -27.476106643676758, -4.152760982513428, -1.048604965209961, -4.591740131378174, -11.443446159362793, 8.705554962158203, 1.8188016414642334, -26.556596755981445, 2.4399993419647217, 0.9921400547027588, 13.145716667175293]... [Tensor of shape torch.Size([1, 99])]
base_model.linear.bias: tensor([12.2170])

%==================================== 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([[ 305.0711],
        [ 247.5204],
        [ 118.7530],
        [  22.4327],
        [ -22.3631],
        [ 186.0485],
        [-195.4503],
        [ 222.6908],
        [  25.2435],
        [ 281.9471]], 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)