ENCen100#
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.ENCen100)
class ENCen100(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.ENCen100()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'encen100'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2023
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Dec, Eric, et al. \"Centenarian clocks: epigenetic clocks for validating claims of exceptional longevity.\" GeroScience (2023): 1-19."
model.metadata["doi"] = 'https://doi.org/10.1007/s11357-023-00731-7'
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download GitHub repository#
[5]:
github_url = "https://github.com/victorychain/Centenarian-Clock.git"
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('Centenarian-Clock/clocks/final_clocks.csv', index_col=0).T
df = df[df['ENCen100+'] != 0]
df = df.reset_index()
model.features = df['index'][1:].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(df['ENCen100+'][1:].tolist()).unsqueeze(0).float()
intercept = torch.tensor([df['ENCen100+'][0]]).float()
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': 'Dec, Eric, et al. "Centenarian clocks: epigenetic clocks for '
'validating claims of exceptional longevity." GeroScience (2023): '
'1-19.',
'clock_name': 'encen100',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1007/s11357-023-00731-7',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2023}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg19923810', 'cg06727198', 'cg13587552', 'cg12278474', 'cg00944884', 'cg02309594', 'cg26131911', 'cg01918888', 'cg22748573', 'cg03557698', 'cg02008416', 'cg01909487', 'cg22215192', 'cg19490266', 'cg22041635', 'cg03265671', 'cg16054275', 'cg11908570', 'cg11314684', 'cg21825027', 'cg10881225', 'cg27072387', 'cg10198837', 'cg19910382', 'cg15903395', 'cg22854546', 'cg22774472', 'cg08147886', 'cg24938727', 'cg06613840']... [Total elements: 198]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=198, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.09928683191537857, 0.49298134446144104, 0.4511302411556244, -0.7807422280311584, -1.8210344314575195, 0.5576984882354736, -7.65609884262085, -1.0797690153121948, -1.6125882863998413, -0.5077138543128967, 0.6321693062782288, 2.269329309463501, 0.48257339000701904, 2.2945704460144043, 17.37386703491211, 0.8210453987121582, -0.1428677886724472, 20.877824783325195, -0.7569608688354492, -4.292027950286865, 1.1173136234283447, 3.3253836631774902, 2.960419178009033, 0.7145973443984985, 1.6346321105957031, -20.96908950805664, 0.020137546584010124, -2.13246488571167, 0.9701406955718994, 3.8667945861816406]... [Tensor of shape torch.Size([1, 198])]
base_model.linear.bias: tensor([73.9947])
%==================================== 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([[ 38.4278],
[126.9503],
[180.1369],
[153.0248],
[-29.4523],
[ 8.3359],
[-21.7442],
[165.3959],
[204.0825],
[ 83.8679]], 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 folder: Centenarian-Clock