YingCausAge#
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.YingCausAge)
class YingCausAge(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.YingCausAge()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'yingcausage'
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('YingCausAge.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': 'yingcausage',
'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: ['cg00027162', 'cg00048759', 'cg00200653', 'cg00347863', 'cg00505045', 'cg00563845', 'cg00603274', 'cg00614360', 'cg00655552', 'cg00663739', 'cg00715290', 'cg00879155', 'cg00910168', 'cg00962755', 'cg01035616', 'cg01048752', 'cg01105058', 'cg01274524', 'cg01321673', 'cg01329511', 'cg01334432', 'cg01399860', 'cg01421252', 'cg01454752', 'cg01503516', 'cg01538166', 'cg01557754', 'cg01579218', 'cg01597480', 'cg01762785']... [Total elements: 585]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=585, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [1.6678526401519775, 5.419585227966309, -0.2697699964046478, 4.103872299194336, 12.006643295288086, -0.5450900197029114, 0.14688290655612946, 1.1880619525909424, -0.965871274471283, 3.5483784675598145, -10.219189643859863, 0.6130169034004211, -1.1934856176376343, 1.0630154609680176, 1.8167389631271362, -1.1464102268218994, 5.109470367431641, 0.2968243360519409, 0.8408879041671753, 3.6986474990844727, -1.898300051689148, -0.3860916793346405, -0.8981965780258179, 5.881424903869629, 1.8310381174087524, -4.833215236663818, -4.612349987030029, -2.4021832942962646, -2.8061323165893555, 0.24915219843387604]... [Tensor of shape torch.Size([1, 585])]
base_model.linear.bias: tensor([86.8082])
%==================================== 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([[177.3734],
[327.3683],
[158.4421],
[157.5365],
[131.7594],
[ 7.4059],
[117.2152],
[168.9700],
[123.9884],
[257.4784]], 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