Mammalian1#
Index#
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.Mammalian1)
class Mammalian1(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
"""
Applies an anti-logarithmic transformation with an offset of -2.
"""
return torch.exp(x) - 2
[3]:
model = pya.models.Mammalian1()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'mammalian1'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'multi'
model.metadata["year"] = 2023
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Lu, A. T., et al. \"Universal DNA methylation age across mammalian tissues.\" Nature aging 3.9 (2023): 1144-1166."
model.metadata["doi"] = "https://doi.org/10.1038/s43587-023-00462-6"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download GitHub repository#
[5]:
github_url = "https://github.com/shorvath/MammalianMethylationConsortium.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('MammalianMethylationConsortium/UniversalPanMammalianClock/ClockParameters/clock1.csv')
df['feature'] = df['var']
df['coefficient'] = df['beta_clock1']
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_logp2'
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': 'Lu, A. T., et al. "Universal DNA methylation age across '
'mammalian tissues." Nature aging 3.9 (2023): 1144-1166.',
'clock_name': 'mammalian1',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1038/s43587-023-00462-6',
'notes': None,
'research_only': None,
'species': 'multi',
'version': None,
'year': 2023}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'anti_logp2'
postprocess_dependencies: None
features: ['cg00249943', 'cg00250826', 'cg00292639', 'cg00362836', 'cg00411555', 'cg00513357', 'cg00587168', 'cg00593462', 'cg00687674', 'cg00694357', 'cg00900456', 'cg00954002', 'cg01009870', 'cg01019040', 'cg01059743', 'cg01136078', 'cg01153166', 'cg01169686', 'cg01246498', 'cg01429475', 'cg01511232', 'cg01656216', 'cg01698540', 'cg01794235', 'cg01975510', 'cg02474352', 'cg02499612', 'cg02532525', 'cg02606236', 'cg02692845']... [Total elements: 335]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=335, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.1527862846851349, 0.0027701049111783504, -0.12989148497581482, 0.048629630357027054, -0.03136558085680008, 0.09142599999904633, 0.055298686027526855, 0.4379110336303711, -0.1408686339855194, -0.808471143245697, -0.03339824452996254, -0.12297524511814117, 0.10108527541160583, -0.004560905043035746, -0.20634084939956665, -0.0016184860141947865, 0.07213742285966873, -0.03695621341466904, 0.052970658987760544, 0.17211447656154633, 0.037939656525850296, 0.04749084636569023, 0.0619727298617363, 0.04738111421465874, 0.05404146388173103, 0.055779341608285904, -0.04102899879217148, 0.1298285871744156, -0.020354116335511208, -0.0109869921579957]... [Tensor of shape torch.Size([1, 335])]
base_model.linear.bias: tensor([1.4314])
%==================================== 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([[-1.9999e+00],
[-1.2721e+00],
[ 6.0199e+00],
[ 1.5016e+00],
[ 3.6253e+02],
[ 1.1582e+01],
[-1.8921e+00],
[ 2.7133e+03],
[ 2.1860e+01],
[ 8.6071e+00]], dtype=torch.float64, grad_fn=<SubBackward0>)
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: MammalianMethylationConsortium