PedBE#
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.PedBE)
class PedBE(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
"""
Applies an anti-logarithmic linear transformation to a PyTorch tensor.
"""
adult_age = 20
# Create a mask for negative and non-negative values
mask_negative = x < 0
mask_non_negative = ~mask_negative
# Initialize the result tensor
age_tensor = torch.empty_like(x)
# Exponential transformation for negative values
age_tensor[mask_negative] = (1 + adult_age) * torch.exp(x[mask_negative]) - 1
# Linear transformation for non-negative values
age_tensor[mask_non_negative] = (1 + adult_age) * x[
mask_non_negative
] + adult_age
return age_tensor
[3]:
model = pya.models.PedBE()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'pedbe'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2019
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "McEwen, Lisa M., et al. \"The PedBE clock accurately estimates DNA methylation age in pediatric buccal cells.\" Proceedings of the National Academy of Sciences 117.38 (2020): 23329-23335."
model.metadata["doi"] = "https://doi.org/10.1073/pnas.1820843116"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download GitHub repository#
[5]:
github_url = "https://github.com/kobor-lab/Public-Scripts"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")
[5]:
0
Load features#
From CSV file#
[6]:
df = pd.read_csv('Public-Scripts/datcoefInteresting94.csv')
df['feature'] = df['ID']
df['coefficient'] = df['Coef']
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]])
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 = 'anti_log_linear'
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': 'McEwen, Lisa M., et al. "The PedBE clock accurately estimates '
'DNA methylation age in pediatric buccal cells." Proceedings of '
'the National Academy of Sciences 117.38 (2020): 23329-23335.',
'clock_name': 'pedbe',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1073/pnas.1820843116',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2019}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'anti_log_linear'
postprocess_dependencies: None
features: ['cg00059225', 'cg00085493', 'cg00095976', 'cg00609333', 'cg01287592', 'cg01704999', 'cg02209075', 'cg02310103', 'cg02426178', 'cg02821342', 'cg02980055', 'cg03020208', 'cg03466124', 'cg03473016', 'cg03493146', 'cg03555227', 'cg04221461', 'cg04452203', 'cg04937184', 'cg04948475', 'cg05024939', 'cg05271255', 'cg05923197', 'cg05928290', 'cg06048436', 'cg06144905', 'cg06198384', 'cg06416491', 'cg06430061', 'cg06455149']... [Total elements: 94]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=94, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.021960020065307617, -0.10039610415697098, 0.007872418500483036, 0.022823642939329147, -0.055414702743291855, -0.09757450968027115, 0.13820089399814606, -0.08401073515415192, -0.3583613932132721, -0.13026674091815948, -0.1387656182050705, 0.21038542687892914, -0.022311074659228325, 0.00015541094762738794, -0.1624089926481247, 0.6385841369628906, 0.03457474708557129, -0.026989279314875603, -0.05423707515001297, -0.0008215174311771989, 0.14885476231575012, -0.1249200701713562, 0.039291542023420334, 0.15890249609947205, -0.1548999398946762, 0.31524088978767395, 0.003525394480675459, -0.19241906702518463, -0.017204945906996727, 0.08637607842683792]... [Tensor of shape torch.Size([1, 94])]
base_model.linear.bias: tensor([-2.0973])
%==================================== 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([[-0.8260],
[-0.4025],
[ 2.6240],
[-0.3707],
[-0.8111],
[-0.4591],
[16.2847],
[ 8.2621],
[ 2.4227],
[ 4.0783]], dtype=torch.float64, grad_fn=<IndexPutBackward0>)
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 folder: Public-Scripts