PhenoAge#

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

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        """
        Applies a convertion from a CDF of the mortality score from a Gompertz
        distribution to phenotypic age.
        """
        # lambda
        l = torch.tensor(0.0192, device=x.device, dtype=x.dtype)
        mortality_score = 1 - torch.exp(-torch.exp(x) * (torch.exp(120 * l) - 1) / l)
        age = (
            141.50225 + torch.log(-0.00553 * torch.log(1 - mortality_score)) / 0.090165
        )
        return age

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "phenoage"
model.metadata["data_type"] = "clinical biomarkers"  # Paper: blood chemistry
model.metadata["species"] = "Homo sapiens"  # Paper: Homo sapiens
model.metadata["year"] = 2018
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Levine, M. E., et al. \"An epigenetic biomarker of aging for lifespan and healthspan.\" Aging 10.4 (2018): 573-591."
model.metadata["doi"] = "https://doi.org/10.18632/aging.101414"
model.metadata["notes"] = "Clinical Phenotypic Age combines chronological age with nine blood biomarkers selected by penalized mortality regression and expresses mortality risk as an equivalent age in years."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["blood"]  # Paper: blood
model.metadata["predicts"] = ["phenotypic age"]  # Paper: phenotypic age
model.metadata["training_target"] = ["mortality"]  # Paper: all-cause mortality
model.metadata["unit"] = ["years"]  # Paper: years
model.metadata["model_type"] = "penalized hazards regression with Gompertz calibration"  # Paper: Penalized proportional hazards regression with Gompertz calibration
model.metadata["platform"] = ["clinical laboratory assays"]  # Paper: clinical laboratory assays
model.metadata["population"] = "adults"  # Paper: NHANES III adults aged 20 years or older (n=9,926)
model.metadata["journal"] = "Aging"
model.metadata["last_author"] = "Steve Horvath"
model.metadata["n_features"] = 10
model.metadata["citations"] = 3594
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

[5]:
features = [
    "albumin",
    "creatinine",
    "glucose",
    "log_crp",
    "lymphocyte_percent",
    "mean_cell_volume",
    "red_cell_distribution_width",
    "alkaline_phosphatase",
    "white_blood_cell_count",
    "age"
]

coefs = [
    -0.0336,
    0.0095,
    0.1953,
    0.0954,
    -0.0120,
    0.0268,
    0.3306,
    0.0019,
    0.0554,
    0.0804,
]

Load features#

[6]:
model.features = features

Load weights into base model#

[7]:
weights = torch.tensor(coefs).unsqueeze(0)
intercept = torch.tensor([-19.9067])

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 = 'mortality_to_phenoage'
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': 'Levine, Morgan E., et al. "An epigenetic biomarker of aging for '
             'lifespan and healthspan." Aging (albany NY) 10.4 (2018): 573.',
 'clock_name': 'phenoage',
 'data_type': 'blood chemistry',
 'doi': 'https://doi.org/10.18632%2Faging.101414',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2018}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'mortality_to_phenoage'
postprocess_dependencies: None
features: ['albumin',
 'creatinine',
 'glucose',
 'log_crp',
 'lymphocyte_percent',
 'mean_cell_volume',
 'red_cell_distribution_width',
 'alkaline_phosphatase',
 'white_blood_cell_count',
 'age']
base_model_features: None

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

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

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

base_model.linear.weight: tensor([[-0.0336,  0.0095,  0.1953,  0.0954, -0.0120,  0.0268,  0.3306,  0.0019,
          0.0554,  0.0804]])
base_model.linear.bias: tensor([-19.9067])

%==================================== 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([[-74.5299],
        [-69.6854],
        [-69.2747],
        [-59.3164],
        [-64.4732],
        [-62.6114],
        [-72.9975],
        [-65.8399],
        [-69.8485],
        [-69.8503]], dtype=torch.float64, grad_fn=<AddBackward0>)

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)