RetroelementAgeV1#
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.RetroelementAgeV1)
class RetroelementAgeV1(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.RetroelementAgeV1()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'retroelementagev1'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Ndhlovu, Lishomwa C., et al. \"Retro‐age: A unique epigenetic biomarker of aging captured by DNA methylation states of retroelements.\" Aging Cell (2024): e14288.",
model.metadata["doi"] = "https://doi.org/10.1111/acel.14288"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://zenodo.org/records/11099870/files/Retroelement_AgeV1coefficients.csv?download=1"
supplementary_file_name = "coefficients.csv"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
[5]:
0
Load features#
From CSV file#
[6]:
df = pd.read_csv('coefficients.csv', index_col=0)
df['feature'] = df['name']
model.features = df['feature'].tolist()[1:]
Load weights into base model#
[7]:
weights = torch.tensor(df['coefficient'].tolist()[1:]).unsqueeze(0)
intercept = torch.tensor([df['coefficient'].tolist()[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': ('Ndhlovu, Lishomwa C., et al. "Retro‐age: A unique epigenetic '
'biomarker of aging captured by DNA methylation states of '
'retroelements." Aging Cell (2024): e14288.',),
'clock_name': 'retroelementagev1',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1111/acel.14288',
'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: ['cg22006408', 'cg25231957', 'cg18158970', 'cg19246944', 'cg18515940', 'cg02688359', 'cg12451887', 'cg10621809', 'cg25811448', 'cg06655097', 'cg12786023', 'cg06922212', 'cg16905434', 'cg15851164', 'cg06059332', 'cg04134193', 'cg24634009', 'cg06159896', 'cg21814996', 'cg27433764', 'cg07416187', 'cg00995689', 'cg13292984', 'cg12121166', 'cg11544647', 'cg25292140', 'cg10960147', 'cg10136168', 'cg16912512', 'cg15366524']... [Total elements: 1317]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=1317, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [2.552152395248413, 1.2862745523452759, 3.9165291786193848, 7.276383876800537, -0.7971858978271484, -0.7952958345413208, 2.0488688945770264, 0.4890359044075012, 0.3316255509853363, 0.11408211290836334, -0.19781948626041412, 0.08929739892482758, 0.6588783264160156, 0.10985901951789856, -0.2538025975227356, -0.11299397051334381, -5.241518020629883, 0.6423152089118958, -10.09760856628418, -0.17259803414344788, -3.927119731903076, 0.06528078764677048, 0.03197569400072098, -2.1564865112304688, 0.19085198640823364, -6.1964287757873535, 1.167095422744751, 3.6051061153411865, -1.0168722867965698, -0.029270412400364876]... [Tensor of shape torch.Size([1, 1317])]
base_model.linear.bias: tensor([78.1362])
%==================================== 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([[159.9747],
[ -3.6259],
[142.4391],
[ 5.3667],
[114.5559],
[ 30.8754],
[-16.2213],
[230.4298],
[ 50.1820],
[113.8849]], 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: coefficients.csv
Deleted folder: .ipynb_checkpoints