eABEC#
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.eABEC)
class eABEC(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.eABEC()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'eabec'
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['eABEC_coefficient'].isna()]
df['feature'] = df.index.tolist()
df['coefficient'] = df['eABEC_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': 'eabec',
'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: ['cg00004257', 'cg00008488', 'cg00011943', 'cg00065598', 'cg00085420', 'cg00089915', 'cg00108554', 'cg00112685', 'cg00116092', 'cg00148464', 'cg00156551', 'cg00172672', 'cg00172812', 'cg00193490', 'cg00203466', 'cg00262681', 'cg00277039', 'cg00314660', 'cg00331334', 'cg00358895', 'cg00370293', 'cg00397859', 'cg00403955', 'cg00406023', 'cg00433107', 'cg00433147', 'cg00448707', 'cg00451649', 'cg00462994', 'cg00464640']... [Total elements: 1791]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=1791, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.13636688888072968, 0.4104917645454407, -0.1868274211883545, -0.6996904015541077, 0.06039871275424957, -1.105724573135376, -0.6053839325904846, 0.257280170917511, 1.429580807685852, -0.3176504671573639, -1.394605278968811, 0.5383281707763672, -0.20417840778827667, -0.24422131478786469, 0.39952561259269714, -0.7541750073432922, -0.4692278504371643, -0.41090691089630127, -0.31093716621398926, -1.232325792312622, -0.17881448566913605, 0.1435064822435379, 0.12202632427215576, 0.4819614887237549, 1.965001106262207, 0.4566323161125183, 0.6106359362602234, -0.11658059060573578, 0.16059798002243042, 0.3613723814487457]... [Tensor of shape torch.Size([1, 1791])]
base_model.linear.bias: tensor([66.6889])
%==================================== 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([[121.0829],
[-18.7480],
[ 52.5807],
[108.6319],
[160.1949],
[-13.6727],
[ 85.8163],
[161.8762],
[ 6.2744],
[ 14.7447]], 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