SkinAndBlood#

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

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        """
        Applies an anti-logarithmic linear transformation to a PyTorch tensor.
        """
        adult_age = 20

        # Create a mask for negative and non-negative values
        mask_negative = x < 0
        mask_non_negative = ~mask_negative

        # Initialize the result tensor
        age_tensor = torch.empty_like(x)

        # Exponential transformation for negative values
        age_tensor[mask_negative] = (1 + adult_age) * torch.exp(x[mask_negative]) - 1

        # Linear transformation for non-negative values
        age_tensor[mask_non_negative] = (1 + adult_age) * x[
            mask_non_negative
        ] + adult_age

        return age_tensor

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

Define clock metadata#

[4]:
model.metadata["clock_name"] = "skinandblood"
model.metadata["data_type"] = "DNA methylation"  # Paper: The estimator regresses age on CpG DNA methylation states.
model.metadata["species"] = "Homo sapiens"  # Paper: DNA was extracted from human tissues and cultured human cell types.
model.metadata["year"] = 2018
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Horvath, S., et al. “Epigenetic clock for skin and blood cells applied to Hutchinson Gilford Progeria Syndrome and ex vivo studies.” Aging 10(7), 1758–1775 (2018)."
model.metadata["doi"] = "https://doi.org/10.18632/aging.101508"
model.metadata["notes"] = "Multi-tissue 391-CpG elastic-net chronological-age clock optimized with training data from buccal cells, whole blood, epithelium, fibroblasts, skin and cord blood; it is particularly accurate for skin-derived and cultured cells."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["buccal epithelium", "whole blood", "epithelium", "cultured fibroblasts", "skin", "cord blood"]  # Paper: Table 1 designates buccal, whole blood, epithelium, fibroblast, skin and cord-blood datasets as training data.
model.metadata["predicts"] = ["chronological age"]  # Paper: The estimator predicts the chronological ages of human donors.
model.metadata["training_target"] = ["chronological age"]  # Paper: A transformed version of chronological age was regressed on CpG methylation states.
model.metadata["unit"] = ["years"]  # Paper: pyaging applies the inverse Horvath age transformation and returns age in years.
model.metadata["model_type"] = "elastic net regression"  # Paper: The glmnet alpha parameter was 0.5 and lambda was selected by cross-validation.
model.metadata["platform"] = ["Illumina 450K", "Illumina EPIC"]  # Paper: The analysis used 450K and EPIC data and restricted candidate CpGs to probes present on both platforms.
model.metadata["population"] = "all ages"  # Paper: The ten training datasets sum to 896 samples and span cord blood through donors aged 94 years.
model.metadata["journal"] = "Aging"
model.metadata["last_author"] = "Kenneth Raj"
model.metadata["n_features"] = 391
model.metadata["citations"] = 853
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

Download directly with curl#

[5]:
supplementary_url = "https://www.aging-us.com/article/101508/supplementary/SD5/0/aging-v10i7-101508-supplementary-material-SD5.csv"
supplementary_file_name = "coefficients.csv"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
[5]:
0

Load features#

From CSV file#

[6]:
df = pd.read_csv('coefficients.csv')
df['feature'] = df['ID']
df['coefficient'] = df['Coef']

model.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 = 'anti_log_linear'
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': 'Horvath, Steve, et al. "Epigenetic clock for skin and blood '
             'cells applied to Hutchinson Gilford Progeria Syndrome and ex '
             'vivo studies." Aging (Albany NY) 10.7 (2018): 1758.',
 'clock_name': 'skinandblood',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.18632/aging.101508',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2018}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'anti_log_linear'
postprocess_dependencies: None
features: ['cg12140144', 'cg26933021', 'cg20822990', 'cg07312601', 'cg09993145', 'cg23605843', 'cg25410668', 'cg17879376', 'cg14962509', 'cg24375409', 'cg22851420', 'cg24107728', 'cg14614643', 'cg00257455', 'cg23045908', 'cg15201877', 'cg18933331', 'cg05675373', 'cg19269039', 'cg16008966', 'cg14565725', 'cg05940231', 'cg03984502', 'cg25256723', 'cg16054275', 'cg01459453', 'cg16599143', 'cg02275294', 'cg21870884', 'cg10501210']... [Total elements: 391]
base_model_features: None

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

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

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

base_model.linear.weight: [0.3631811738014221, -0.09050008654594421, -0.007025233935564756, -0.13509239256381989, -0.042639341205358505, 0.07938723266124725, 0.2780052423477173, -0.2027093917131424, 0.1823105365037918, -0.02380458638072014, 0.09719781577587128, -0.10654273629188538, -0.04339298605918884, -0.1616985946893692, 0.13732706010341644, 0.3920976221561432, -0.2317628413438797, 0.024479255080223083, -0.017557984218001366, -0.20390775799751282, -0.03556407615542412, -0.10670483857393265, 0.22212129831314087, -0.12098140269517899, -0.23396819829940796, 0.041907940059900284, 0.1419801115989685, -0.14286929368972778, -0.012681434862315655, -0.3165263533592224]... [Tensor of shape torch.Size([1, 391])]
base_model.linear.bias: tensor([-0.4471])

%==================================== 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([[-0.7403],
        [-0.9991],
        [-0.5375],
        [48.3885],
        [-0.1838],
        [-0.3993],
        [15.9029],
        [58.4267],
        [ 0.6595],
        [22.1512]], dtype=torch.float64, grad_fn=<IndexPutBackward0>)

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