HRSInCHPhenoAge#
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.HRSInCHPhenoAge)
class HRSInCHPhenoAge(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.HRSInCHPhenoAge()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'hrsinchphenoage'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2022
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Higgins-Chen, Albert T., et al. \"A computational solution for bolstering reliability of epigenetic clocks: Implications for clinical trials and longitudinal tracking.\" Nature aging 2.7 (2022): 644-661."
model.metadata["doi"] = "https://doi.org/10.1038/s43587-022-00248-2"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download GitHub repository#
[5]:
github_url = "https://github.com/MorganLevineLab/methylCIPHER.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('methylCIPHER/data-raw/HRSInChPhenoAge_CpG.csv')
df['feature'] = df['CpG']
df['coefficient'] = df['Weight']
model.features = df['feature'].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(df['coefficient'].tolist()).unsqueeze(0)
intercept = torch.tensor([52.8334080])
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': 'Higgins-Chen, Albert T., et al. "A computational solution for '
'bolstering reliability of epigenetic clocks: Implications for '
'clinical trials and longitudinal tracking." Nature aging 2.7 '
'(2022): 644-661.',
'clock_name': 'hrsinchphenoage',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1038/s43587-022-00248-2',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2022}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00025138', 'cg00036347', 'cg00043599', 'cg00049440', 'cg00056497', 'cg00059225', 'cg00066239', 'cg00067518', 'cg00101154', 'cg00135293', 'cg00137209', 'cg00211115', 'cg00238295', 'cg00276799', 'cg00282953', 'cg00312921', 'cg00376639', 'cg00401091', 'cg00417823', 'cg00448560', 'cg00481159', 'cg00495693', 'cg00503840', 'cg00509996', 'cg00551910', 'cg00574958', 'cg00593462', 'cg00602811', 'cg00615241', 'cg00618626']... [Total elements: 959]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=959, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-12.598388671875, 2.0095407962799072, 3.08774995803833, 1.5167790651321411, 0.20355011522769928, 1.68230140209198, -1.249173879623413, -0.8185797333717346, 0.4907846450805664, 0.5390154123306274, 15.449186325073242, -1.285083293914795, -0.7427912354469299, 1.5232256650924683, 0.5885316729545593, 2.078218936920166, 3.4780304431915283, -10.69495964050293, 2.9323976039886475, -5.428037166595459, 0.2791459858417511, -0.285178542137146, 0.9086608290672302, -0.1606019139289856, 1.7213571071624756, -5.501366138458252, 0.08092798292636871, -2.233879566192627, -1.4966527223587036, -4.973464488983154]... [Tensor of shape torch.Size([1, 959])]
base_model.linear.bias: tensor([52.8334])
%==================================== 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([[ 319.0174],
[ -70.3330],
[ 49.5369],
[ -66.2511],
[ -99.2095],
[-165.9214],
[ 160.0792],
[ 293.2276],
[ 181.4062],
[-175.9353]], 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: methylCIPHER