RetroelementAgeV2#
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.RetroelementAgeV2)
class RetroelementAgeV2(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.RetroelementAgeV2()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'retroelementagev2'
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_AgeV2coefficients.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': 'retroelementagev2',
'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: ['cg23728960', 'cg10366786', 'cg08398371', 'cg10973967', 'cg01721313', 'cg25231957', 'cg21992844', 'cg24646803', 'cg16037947', 'cg03468827', 'cg18939097', 'cg01740695', 'cg25593520', 'cg11120551', 'cg01403320', 'cg07821808', 'cg19796584', 'cg27422507', 'cg16033766', 'cg03667422', 'cg18369325', 'cg09373192', 'cg00700455', 'cg20923885', 'cg07644039', 'cg08506585', 'cg12744300', 'cg20051117', 'cg04765439', 'cg03320087']... [Total elements: 1378]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=1378, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.14868102967739105, 0.4319063127040863, -3.2955737113952637, 2.740462303161621, 0.8276747465133667, 2.5161685943603516, -1.4428094625473022, 0.7483506798744202, 0.18299150466918945, -0.6927100419998169, 0.17969781160354614, -0.10440022498369217, -1.5772448778152466, -0.6229540705680847, 0.6904758214950562, 0.16339100897312164, 0.9191771745681763, 3.9579126834869385, 0.0863616093993187, 0.5412383079528809, 0.45451620221138, 0.6237431168556213, 1.284313678741455, 0.9083895683288574, -0.12913724780082703, -0.03379112854599953, 2.2048282623291016, 3.126389503479004, -4.167088508605957, 2.5030527114868164]... [Tensor of shape torch.Size([1, 1378])]
base_model.linear.bias: tensor([62.0742])
%==================================== 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([[ 65.4386],
[ 64.7318],
[ 26.8192],
[ 15.2899],
[ 45.2880],
[ 31.0392],
[ 54.1099],
[ 18.1802],
[128.9012],
[ 50.0440]], 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