LeeControl#
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.LeeControl)
class LeeControl(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.LeeControl()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'leecontrol'
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_CPC']
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': 'leecontrol',
'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: ['cg00056066', 'cg00057476', 'cg00073090', 'cg00083059', 'cg00091483', 'cg00108098', 'cg00112465', 'cg00173659', 'cg00173799', 'cg00253398', 'cg00307685', 'cg00378510', 'cg00400547', 'cg00419702', 'cg00423969', 'cg00451105', 'cg00466827', 'cg00521434', 'cg00530564', 'cg00604454', 'cg00639010', 'cg00705661', 'cg00896578', 'cg00898013', 'cg00971110', 'cg01075918', 'cg01079860', 'cg01152073', 'cg01164202', 'cg01233392']... [Total elements: 546]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=546, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.019747359678149223, 0.7828122973442078, -0.14498105645179749, -0.14913348853588104, 0.9398415088653564, 0.1055426299571991, -0.08062367886304855, -0.5368783473968506, 0.014656665734946728, -0.26146650314331055, 0.1337740123271942, 0.20334802567958832, 0.850095808506012, -0.04680880531668663, 0.20182037353515625, -0.23556417226791382, 0.16915300488471985, 2.17164945602417, 1.0525552034378052, 0.19726672768592834, -2.901245594024658, -2.70284104347229, -0.3479940891265869, 0.15078707039356232, 0.08475268632173538, -0.9259878993034363, 0.03768037632107735, -5.494863033294678, 0.0004355729906819761, 0.8516144752502441]... [Tensor of shape torch.Size([1, 546])]
base_model.linear.bias: tensor([13.0618])
%==================================== 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([[ 45.2733],
[ 18.0971],
[ 46.8906],
[ 10.3302],
[ 14.8084],
[ 1.2032],
[ -3.7268],
[-42.4389],
[ 57.3741],
[ 8.4126]], 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