LeeRefinedRobust#
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.LeeRefinedRobust)
class LeeRefinedRobust(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.LeeRefinedRobust()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'leerefinedrobust'
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_refined_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': 'leerefinedrobust',
'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', 'cg00056066', 'cg00057476', 'cg00063979', 'cg00073090', 'cg00091483', 'cg00192031', 'cg00239899', 'cg00307685', 'cg00398130', 'cg00400547', 'cg00501482', 'cg00521434', 'cg00639010', 'cg00674365', 'cg00675037', 'cg00705661', 'cg00721170', 'cg00766497', 'cg00896578', 'cg01075918', 'cg01093285', 'cg01118711', 'cg01152073', 'cg01233392', 'cg01272599', 'cg01284448', 'cg01376763', 'cg01508380', 'cg01509843']... [Total elements: 395]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=395, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.8186162114143372, 0.16722442209720612, 0.34937411546707153, -1.067895531654358, -0.8697810173034668, 0.43536683917045593, 0.578291118144989, -0.015465746633708477, -0.7448819279670715, 0.014211648143827915, 0.8834953308105469, -0.11739718168973923, 3.4362940788269043, -1.566601037979126, 1.0341867208480835, -0.7214075326919556, -1.7810513973236084, 0.2575894594192505, 0.8929645419120789, -0.08577913790941238, -1.31065034866333, 0.3212359845638275, 1.0784249305725098, -0.42912325263023376, 1.5435547828674316, 0.47470206022262573, -0.06839500367641449, 0.27191871404647827, 3.9766881465911865, 0.3509693443775177]... [Tensor of shape torch.Size([1, 395])]
base_model.linear.bias: tensor([30.7497])
%==================================== 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([[72.5832],
[35.2669],
[40.0895],
[52.8663],
[14.7698],
[16.9160],
[16.4652],
[37.2609],
[ 0.7917],
[19.2460]], 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