YingAdaptAge#
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.YingAdaptAge)
class YingAdaptAge(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.YingAdaptAge()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'yingadaptage'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Ying, Kejun, et al. \"Causality-enriched epigenetic age uncouples damage and adaptation.\" Nature Aging (2024): 1-16.",
model.metadata["doi"] = "https://doi.org/10.1038/s43587-023-00557-0"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1038%2Fs43587-023-00557-0/MediaObjects/43587_2023_557_MOESM6_ESM.zip"
supplementary_file_name = "43587_2023_557_MOESM6_ESM.zip"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
os.system(f'unzip {supplementary_file_name}')
[5]:
0
Load features#
From CSV file#
[6]:
df = pd.read_csv('YingAdaptAge.csv')
df['feature'] = df['term']
df['coefficient'] = df['estimate']
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 = None
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': ('Ying, Kejun, et al. "Causality-enriched epigenetic age '
'uncouples damage and adaptation." Nature Aging (2024): 1-16.',),
'clock_name': 'yingadaptage',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1038/s43587-023-00557-0',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2024}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00008671', 'cg00017970', 'cg00048759', 'cg00050402', 'cg00089550', 'cg00099240', 'cg00108164', 'cg00131893', 'cg00158122', 'cg00223715', 'cg00229508', 'cg00277334', 'cg00290758', 'cg00295744', 'cg00316485', 'cg00335735', 'cg00342891', 'cg00344422', 'cg00346145', 'cg00388262', 'cg00492070', 'cg00505045', 'cg00513984', 'cg00539174', 'cg00544337', 'cg00552753', 'cg00561903', 'cg00577578', 'cg00589581', 'cg00638945']... [Total elements: 999]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=999, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.013709170743823051, -0.00010836099681910127, 33.802955627441406, -0.0494624599814415, -0.026015829294919968, -0.00015495899424422532, 16.04678726196289, 1.9626444578170776, -0.0002919970138464123, 0.582930862903595, -7.09550004103221e-05, -0.0010870120022445917, -6.861089786980301e-05, 1.4208452701568604, -0.0016144789988175035, -5.526280074263923e-05, -0.003765339031815529, -0.00011124699813080952, 3.404261589050293, -0.000265667011262849, -0.00037762499414384365, 7.503885746002197, -9.961259638657793e-05, 0.08913462609052658, -0.007147847209125757, -0.0005405130214057863, -0.00011664799967547879, -0.00048649401287548244, -0.01120647694915533, -0.015965329483151436]... [Tensor of shape torch.Size([1, 999])]
base_model.linear.bias: tensor([-511.9743])
%==================================== 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([[-687.2641],
[-498.8554],
[-377.1122],
[-518.4170],
[-423.5536],
[-665.6058],
[-152.4022],
[-335.6033],
[-560.6229],
[-359.5644]], dtype=torch.float64, grad_fn=<AddmmBackward0>)
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: 43587_2023_557_MOESM6_ESM.zip
Deleted file: YingCausAge.csv
Deleted file: YingDamAge.csv
Deleted file: YingAdaptAge.csv