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. 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.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"] = 'methylation'
model.metadata["species"] = 'multi'
model.metadata["year"] = 2023
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Li, Caesar Z., et al. \"Epigenetic predictors of species maximum lifespan and other life history traits in mammals.\" bioRxiv (2023): 2023-11."
model.metadata["doi"] = "https://doi.org/10.1101/2023.11.02.565286"
model.metadata["research_only"] = None
model.metadata["notes"] = "Pan-mammalian DNA-methylation classifier estimating the probability that a sample is from a female, derived from CpGs conserved across mammalian species."
model.metadata["tissue"] = 'multi-tissue (pan-mammalian; ~15,000 samples across 348 mammalian species, 59 tissue types)'
model.metadata["predicts"] = 'sex (probability that the sample is female)'
model.metadata["unit"] = 'probability (0-1)'
model.metadata["model_type"] = 'Elastic net'
model.metadata["platform"] = 'Mammalian methylation array'
model.metadata["population"] = 'pan-mammalian (multiple mammalian species, all ages)'
model.metadata["journal"] = 'bioRxiv (Cold Spring Harbor Laboratory)'
model.metadata["last_author"] = 'Steve Horvath'
model.metadata["n_features"] = 101
model.metadata["citations"] = 5
model.metadata["citations_date"] = '2026-07-05'

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, Caesar Z., et al. "Epigenetic predictors of species maximum '
             'lifespan and other life history traits in mammals." bioRxiv '
             '(2023): 2023-11.',
 'clock_name': 'mammalianfemale',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1101/2023.11.02.565286',
 'notes': None,
 'research_only': None,
 'species': 'multi',
 'version': None,
 'year': 2023}
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 ====================================%

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([[9.8883e-01],
        [2.9257e-02],
        [7.8139e-01],
        [1.7065e-05],
        [1.3097e-05],
        [1.7472e-01],
        [7.5826e-01],
        [9.9268e-04],
        [5.3222e-03],
        [9.9953e-01]], dtype=torch.float64, grad_fn=<SigmoidBackward0>)

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