MammalianFemale

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. Normal feature ranges

  10. Basic test

  11. Save torch model

  12. Clear directory

Let’s first import some packages:

[1]:
import os
import inspect
import shutil
import json
import math
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.MammalianFemale)
class MammalianFemale(pyagingModel):
    def __init__(self):
        super().__init__()

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        """
        Applies a sigmoid transformation.
        """
        return torch.sigmoid(x)

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

Define clock metadata

[4]:
model.metadata["clock_name"] = "mammalianfemale"
model.metadata["data_type"] = 'DNA methylation'  # Paper: The model is based on DNA methylation measurements.
model.metadata["species"] = 'multiple species'  # Paper: The study samples are multi.
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = 'Li, C. Z., et al. (2024). Epigenetic predictors of species maximum life span and other life-history traits in mammals. Science Advances, 10(23), eadm7273.'
model.metadata["doi"] = 'https://doi.org/10.1126/sciadv.adm7273'
model.metadata["notes"] = 'Pan-mammalian elastic-net sex classifier using conserved CpG methylation. The author package expects SeSAMe-normalized mammalian-array data; its 320K option maps probes to the 40K CpG IDs. Pyaging applies a sigmoid to return female probability; published validation excluded marmosets.'
model.metadata["research_only"] = None
model.metadata["tissue"] = ['multi-tissue']  # Paper: The listed tissue is the model-development sample material.
model.metadata["predicts"] = ['sex']  # Paper: The reported predictor output is probability that the sample is female.
model.metadata["training_target"] = ['sex']  # Paper: The fitting outcome is binary sex (female versus male).
model.metadata["unit"] = ['probability']  # Paper: The returned construct is expressed as probability (0–1).
model.metadata["model_type"] = 'elastic net regression'  # Paper: The clock was fitted using Elastic net.
model.metadata["platform"] = ['mammalian methylation array']  # Paper: Author predictSex helper requires data normalized by the SeSAMe pipeline; 40K or mapped 320K mammalian-array features.
model.metadata["population"] = 'multiple mammalian species'  # Paper: 15,000 samples from 348 mammalian species; universal sex predictor excludes marmosets
model.metadata["journal"] = 'Science Advances'
model.metadata["last_author"] = "Steve Horvath"
model.metadata["n_features"] = 101
model.metadata["citations"] = 36
model.metadata["citations_date"] = '2026-10-02'

Download clock dependencies

Download GitHub repository

[5]:
github_url = "https://github.com/caeseriousli/MammalianMethylationPredictors.git"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")
[5]:
0

Load features

From CSV file

[6]:
df = pd.read_csv('MammalianMethylationPredictors/Predictors/FemalePredictor_Overlap320K40K.csv')
df['feature'] = df['CpG']
df['coefficient'] = df['RegressionCoefficient']
df = df[df.RegressionCoefficient != 0]

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 = 'sigmoid'
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': 'Li, C. Z., et al. (2024). Epigenetic predictors of species '
             'maximum life span and other life-history traits in mammals. '
             'Science Advances, 10(23), eadm7273.',
 'citations': 36,
 'citations_date': '2026-10-02',
 'clock_name': 'mammalianfemale',
 'data_type': 'DNA methylation',
 'doi': 'https://doi.org/10.1126/sciadv.adm7273',
 'journal': 'Science Advances',
 'last_author': 'Steve Horvath',
 'model_type': 'elastic net regression',
 'n_features': 101,
 'notes': 'Pan-mammalian elastic-net sex classifier using conserved CpG '
          'methylation. The author package expects SeSAMe-normalized '
          'mammalian-array data; its 320K option maps probes to the 40K CpG '
          'IDs. Pyaging applies a sigmoid to return female probability; '
          'published validation excluded marmosets.',
 'platform': ['mammalian methylation array'],
 'population': 'multiple mammalian species',
 'postprocess': 'sigmoid',
 'predicts': ['sex'],
 'research_only': None,
 'species': 'multiple species',
 'tissue': ['multi-tissue'],
 'training_target': ['sex'],
 'unit': ['probability'],
 'version': '0.5.7',
 'year': 2024}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'sigmoid'
postprocess_dependencies: None
features: ['cg00563016', 'cg00878023', 'cg01042193', 'cg01145947', 'cg02053792', 'cg02407848', 'cg02812647', 'cg03039483', 'cg03341064', 'cg03860580', 'cg04272551', 'cg04423201', 'cg04487404', 'cg04493740', 'cg05218225', 'cg05848491', 'cg05901294', 'cg06332339', 'cg06758827', 'cg07121495', 'cg07597118', 'cg07998710', 'cg08162897', 'cg08955338', 'cg09509790', 'cg09658710', 'cg09824710', 'cg10723970', 'cg10730492', 'cg10743840']... [Total elements: 101]
base_model_features: None

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

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

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

base_model.linear.weight: [-3.7219111919403076, 0.00039567038766108453, 0.16944003105163574, -0.3170323371887207, 0.09090086817741394, 1.4698140621185303, 0.34378138184547424, 0.37199780344963074, 0.248253732919693, -0.570648729801178, -1.2420387268066406, -0.6031981706619263, 0.2966012954711914, 0.4936045706272125, 1.3543082475662231, -0.5120242834091187, -1.071324110031128, 0.40442875027656555, 0.09175214916467667, -0.3924863040447235, 0.010922560468316078, 0.0004333447141107172, -1.255670428276062, 0.5057510733604431, 0.8768488168716431, -0.12605105340480804, 0.7848129868507385, -2.125744104385376, 0.3008327782154083, -0.014511662535369396]... [Tensor of shape torch.Size([1, 101])]
base_model.linear.bias: tensor([0.7064])

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

Normal feature ranges

[ ]:
# Units and plausibility ranges come from the package registry, keyed by feature name.
feature_ranges = pya.utils.resolve_feature_ranges(model.features, model.metadata["data_type"])
model.feature_units = [record["unit"] for record in feature_ranges]
pd.DataFrame.from_records(feature_ranges).head()

Basic test

[ ]:
# Exercise the clock with values in the middle of each feature's expected range.
records = pya.utils.resolve_feature_ranges(model.features, model.metadata["data_type"])
midpoints = [
    (record["low"] + record["high"]) / 2 if math.isfinite(record["high"]) else max(record["low"], 1.0)
    for record in records
]
input = torch.tensor([midpoints] * 10, dtype=torch.float64)
model.eval()
model.to(torch.float64)
pred = model(input)
pred

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 folder: MammalianMethylationPredictors