LeeRobust#
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.LeeRobust)
class LeeRobust(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.LeeRobust()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'leerobust'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2019
model.metadata["approved_by_author"] = '✅'
model.metadata["citation"] = "Lee, Yunsung, et al. \"Placental epigenetic clocks: estimating gestational age using placental DNA methylation levels.\" Aging (Albany NY) 11.12 (2019): 4238."
model.metadata["doi"] = "https://doi.org/10.18632/aging.102049"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://www.aging-us.com/article/102049/supplementary/SD2/0/aging-v11i12-102049-supplementary-material-SD2.csv"
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')
df['feature'] = df['CpGs']
df['coefficient'] = df['Coefficient_RPC']
df = df[df.coefficient != 0]
model.features = 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': 'Lee, Yunsung, et al. "Placental epigenetic clocks: estimating '
'gestational age using placental DNA methylation levels." Aging '
'(Albany NY) 11.12 (2019): 4238.',
'clock_name': 'leerobust',
'data_type': 'methylation',
'doi': 'https://doi.org/10.18632/aging.102049',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2019}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00009871', 'cg00035630', 'cg00056066', 'cg00057476', 'cg00063979', 'cg00073090', 'cg00091483', 'cg00173659', 'cg00192031', 'cg00239899', 'cg00307685', 'cg00398130', 'cg00400547', 'cg00419702', 'cg00466827', 'cg00469856', 'cg00501482', 'cg00521434', 'cg00595223', 'cg00639010', 'cg00674365', 'cg00675037', 'cg00705661', 'cg00721170', 'cg00766497', 'cg00896578', 'cg01075918', 'cg01093285', 'cg01118711', 'cg01152073']... [Total elements: 558]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=558, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.12465698271989822, -0.00647827098146081, 0.8594600558280945, 0.3723226487636566, -0.5090286135673523, -0.1893170177936554, 0.7658786773681641, -0.17820455133914948, 0.7639460563659668, -0.22348295152187347, 0.22304490208625793, 0.2099320888519287, 0.9854989051818848, -0.08535578846931458, 0.009702717885375023, -0.07904969155788422, -0.37377262115478516, 1.6936191320419312, -0.004757361952215433, -1.933017611503601, 0.007646538782864809, -0.18009760975837708, -2.810021162033081, 0.04612048342823982, 0.25931477546691895, -0.006801355164498091, -0.9294152855873108, 0.2601521909236908, 0.5462681651115417, -3.372469425201416]... [Tensor of shape torch.Size([1, 558])]
base_model.linear.bias: tensor([24.9977])
%==================================== 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([[42.0170],
[55.4254],
[49.9402],
[36.4192],
[45.8815],
[10.6421],
[32.3821],
[38.4876],
[24.5012],
[70.2651]], 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