cABEC#
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.cABEC)
class cABEC(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.cABEC()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'cabec'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2020
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Lee, Yunsung, et al. \"Blood-based epigenetic estimators of chronological age in human adults using DNA methylation data from the Illumina MethylationEPIC array.\" BMC genomics 21 (2020): 1-13."
model.metadata["doi"] = "https://doi.org/10.1186/s12864-020-07168-8"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://static-content.springer.com/esm/art%3A10.1186%2Fs12864-020-07168-8/MediaObjects/12864_2020_7168_MOESM1_ESM.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', index_col=0)
df = df[~df['cABEC_coefficient'].isna()]
df['feature'] = df.index.tolist()
df['coefficient'] = df['cABEC_coefficient']
model.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]])
<ipython-input-7-232b7c74dbf3>:2: FutureWarning: Series.__getitem__ treating keys as positions is deprecated. In a future version, integer keys will always be treated as labels (consistent with DataFrame behavior). To access a value by position, use `ser.iloc[pos]`
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. "Blood-based epigenetic estimators of '
'chronological age in human adults using DNA methylation data '
'from the Illumina MethylationEPIC array." BMC genomics 21 '
'(2020): 1-13.',
'clock_name': 'cabec',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s12864-020-07168-8',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2020}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00000165', 'cg00001687', 'cg00004257', 'cg00012238', 'cg00015770', 'cg00018181', 'cg00039864', 'cg00053073', 'cg00071360', 'cg00074086', 'cg00112685', 'cg00116092', 'cg00156551', 'cg00172812', 'cg00193490', 'cg00199846', 'cg00231483', 'cg00260883', 'cg00262681', 'cg00265788', 'cg00290373', 'cg00314660', 'cg00347882', 'cg00370293', 'cg00381684', 'cg00387658', 'cg00397859', 'cg00406023', 'cg00448707', 'cg00456672']... [Total elements: 1892]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=1892, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.5071440935134888, 3.8805794715881348, -0.004386255983263254, -0.3082602918148041, 0.7501303553581238, -0.07783860713243484, -0.03706755116581917, -3.0622639656066895, -0.27626731991767883, -0.4478277266025543, 0.7638550400733948, 1.4799879789352417, -0.9727926254272461, -0.08195030689239502, -2.9534730911254883, 1.5299639701843262, -0.09737197309732437, 0.12180330604314804, -0.06913822144269943, -0.36189907789230347, -0.07744547724723816, -0.7775667309761047, -1.5537751913070679, -0.0737200528383255, 0.02495921030640602, -0.2793864905834198, 0.4901841878890991, 0.8282898664474487, 1.9143801927566528, -0.2619211971759796]... [Tensor of shape torch.Size([1, 1892])]
base_model.linear.bias: tensor([42.8285])
%==================================== 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([[ 35.7819],
[ 48.6824],
[-73.2872],
[141.0891],
[ 49.2925],
[-72.9852],
[213.5275],
[ 64.9323],
[ 80.0819],
[-44.4303]], 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