Horvath2013#

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.Horvath2013)
class Horvath2013(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.Horvath2013()

Define clock metadata#

[4]:
model.metadata["clock_name"] = "horvath2013"
model.metadata["data_type"] = "DNA methylation"  # Paper: The predictor uses CpG DNA-methylation levels.
model.metadata["species"] = "Homo sapiens"  # Paper: The predictor was trained on human tissues and cell types.
model.metadata["year"] = 2013
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Horvath, S. DNA methylation age of human tissues and cell types. Genome Biology 14, R115 (2013)."
model.metadata["doi"] = "https://doi.org/10.1186/gb-2013-14-10-r115"
model.metadata["notes"] = "Pan-tissue DNAm-age predictor fitted by elastic net to a transformed chronological-age outcome and returned to the year scale; it uses 353 CpGs shared between the 27K and 450K arrays."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["multi-tissue"]  # Paper: Training datasets represented a wide spectrum among 51 healthy tissues and cell types.
model.metadata["predicts"] = ["chronological age"]  # Paper: The model returns DNA-methylation age calibrated to chronological age.
model.metadata["training_target"] = ["chronological age"]  # Paper: A transformed version of chronological age was the elastic-net outcome.
model.metadata["unit"] = ["years"]  # Paper: DNAm age and prediction error are reported in years after inverse transformation.
model.metadata["model_type"] = "elastic net regression"  # Paper: The paper identifies the penalized regression model as elastic net.
model.metadata["platform"] = ["Illumina 27K", "Illumina 450K"]  # Paper: Training used CpGs shared by the Illumina 27K and 450K platforms.
model.metadata["population"] = "all ages"  # Paper: The training and validation collection spans many tissues and ages, including newborn and centenarian-range samples.
model.metadata["journal"] = "Genome Biology"
model.metadata["last_author"] = "Steve Horvath"
model.metadata["n_features"] = 353
model.metadata["citations"] = 7318
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

Download directly with curl#

[5]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1186%2Fgb-2013-14-10-r115/MediaObjects/13059_2013_3156_MOESM3_ESM.csv"
supplementary_file_name = "coefficients.csv"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
[5]:
0
[6]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1186%2Fgb-2013-14-10-r115/MediaObjects/13059_2013_3156_MOESM22_ESM.csv"
supplementary_file_name = "reference_feature_values.csv"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
[6]:
0

Load features#

From CSV file#

[7]:
df = pd.read_csv('coefficients.csv', skiprows=2)
df['feature'] = df['CpGmarker']
df['coefficient'] = df['CoefficientTraining']
model.features = df['feature'][1:].tolist()

Load weights into base model#

[8]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'][0]])

Linear model#

[9]:
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#

From CSV file#

[10]:
reference_feature_values_df = pd.read_csv('reference_feature_values.csv', index_col=0)
reference_feature_values_df = reference_feature_values_df.loc[model.features]
model.reference_values = reference_feature_values_df['goldstandard2'].tolist()

Load preprocess and postprocess objects#

[11]:
model.preprocess_name = None
model.preprocess_dependencies = None
[12]:
model.postprocess_name = 'anti_log_linear'
model.postprocess_dependencies = None

Check all clock parameters#

[13]:
pya.utils.print_model_details(model)

%==================================== Model Details ====================================%
Model Attributes:

training: True
metadata: {'approved_by_author': '⌛',
 'citation': 'Horvath, Steve. "DNA methylation age of human tissues and cell '
             'types." Genome biology 14.10 (2013): 1-20.',
 'clock_name': 'horvath2013',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1186/gb-2013-14-10-r115',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2013}
reference_values: [0.790221397, 0.89001929, 0.059106387, 0.23651937, 0.073668777, 0.563295909, 0.864999404, 0.027047887, 0.660721193, 0.033420176, 0.047913033, 0.517283973, 0.050756537, 0.072267723, 0.014877693, 0.876157036, 0.187082703, 0.170303406, 0.019217238, 0.560726569, 0.845964086, 0.447995921, 0.055406903, 0.059821557, 0.533869814, 0.065190933, 0.896227421, 0.090932158, 0.032431793, 0.480007151]... [Total elements: 353]
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'anti_log_linear'
postprocess_dependencies: None
features: ['cg00075967', 'cg00374717', 'cg00864867', 'cg00945507', 'cg01027739', 'cg01353448', 'cg01584473', 'cg01644850', 'cg01656216', 'cg01873645', 'cg01968178', 'cg02085507', 'cg02154074', 'cg02217159', 'cg02331561', 'cg02332492', 'cg02364642', 'cg02388150', 'cg02479575', 'cg02489552', 'cg02580606', 'cg02654291', 'cg02827112', 'cg02972551', 'cg03103192', 'cg03167275', 'cg03270204', 'cg03565323', 'cg03588357', 'cg03760483']... [Total elements: 353]
base_model_features: None

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

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

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

base_model.linear.weight: [0.12933661043643951, 0.005017857067286968, 1.599764108657837, 0.056852418929338455, 0.10286285728216171, 0.23856045305728912, 0.08862839639186859, 0.1599487066268921, 0.04280552640557289, -0.6040563583374023, 1.1692458391189575, 0.006127551198005676, 0.04475700482726097, -0.08651260286569595, 0.12692885100841522, 0.06277134269475937, -0.024270255118608475, 0.42597126960754395, 1.8754462003707886, 0.0737413838505745, 0.34927448630332947, 0.14058348536491394, 0.05064608156681061, 0.4739460051059723, 0.02353634312748909, -0.5510412454605103, 0.013544725254178047, -0.2076532244682312, -0.8588430285453796, 0.014946399256587029]... [Tensor of shape torch.Size([1, 353])]
base_model.linear.bias: tensor([0.6955])

%==================================== Model Details ====================================%

Basic test#

[14]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[14]:
tensor([[ -0.9718],
        [  1.8615],
        [ -0.9980],
        [ 67.1194],
        [253.6647],
        [ 61.3025],
        [ -0.9928],
        [ -0.6078],
        [ -0.9995],
        [ -0.7832]], dtype=torch.float64, grad_fn=<IndexPutBackward0>)

Save torch model#

[15]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")

Clear directory#

[16]:
# 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
Deleted file: reference_feature_values.csv
Deleted file: coefficients.xlsx