PipekRetrainedH#
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.PipekRetrainedH)
class PipekRetrainedH(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.PipekRetrainedH()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'pipekretrainedh'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2022
model.metadata["approved_by_author"] = '✅'
model.metadata["citation"] = "Pipek, Orsolya Anna, and István Csabai. \"A revised multi-tissue, multi-platform epigenetic clock model for methylation array data.\" Journal of Mathematical Chemistry 61.2 (2023): 376-388."
model.metadata["doi"] = "https://doi.org/10.1007/s10910-022-01381-4"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
github_url = "https://github.com/pipekorsi/MepiClock.git"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")
[5]:
0
Load features#
From CSV file#
[7]:
df = pd.read_csv('MepiClock/resources/model_coefficients.csv', sep=';')
df['feature'] = df['probeID']
df['coefficient'] = df['retrained H (308)']
df = df[df['coefficient'] != 0]
model.features = df['feature'][1:].tolist()
Load weights into base model#
[8]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'][0]])
Linear model#
[9]:
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#
From CSV file#
[10]:
model.reference_values = None
Load preprocess and postprocess objects#
[11]:
model.preprocess_name = None
model.preprocess_dependencies = None
[12]:
model.postprocess_name = 'anti_log_linear'
model.postprocess_dependencies = None
Check all clock parameters#
[13]:
pya.utils.print_model_details(model)
%==================================== Model Details ====================================%
Model Attributes:
training: True
metadata: {'approved_by_author': '✅',
'citation': 'Pipek, Orsolya Anna, and István Csabai. "A revised multi-tissue, '
'multi-platform epigenetic clock model for methylation array '
'data." Journal of Mathematical Chemistry 61.2 (2023): 376-388.',
'clock_name': 'pipekretrainedh',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1007/s10910-022-01381-4',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2022}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'anti_log_linear'
postprocess_dependencies: None
features: ['cg00075967', 'cg00091693', 'cg00168942', 'cg00374717', 'cg00431549', 'cg00436603', 'cg00864867', 'cg00945507', 'cg01027739', 'cg01027805', 'cg01262913', 'cg01353448', 'cg01407797', 'cg01459453', 'cg01485645', 'cg01511567', 'cg01560871', 'cg01570885', 'cg01584473', 'cg01644850', 'cg01656216', 'cg01820374', 'cg01873645', 'cg01968178', 'cg02047577', 'cg02071305', 'cg02154074', 'cg02217159', 'cg02275294', 'cg02331561']... [Total elements: 308]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=308, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.15507809817790985, -0.29187604784965515, -0.36055922508239746, 0.14677272737026215, -0.04881210997700691, 0.12088847160339355, 0.7062472105026245, 0.1599520444869995, 0.07841434329748154, 0.007295766845345497, -0.42229509353637695, 0.10807087272405624, -0.049479518085718155, -0.35953179001808167, -0.4458913207054138, -0.19224964082241058, -0.20533110201358795, -0.11849058419466019, -0.01124870590865612, 0.08635646849870682, 0.015325155109167099, -0.13382241129875183, -1.4644325971603394, 0.6810423731803894, -3.380617618560791, -0.04927511513233185, 0.22624434530735016, -0.09974532574415207, 0.3166675567626953, 0.033049389719963074]... [Tensor of shape torch.Size([1, 308])]
base_model.linear.bias: tensor([0.6322])
%==================================== Model Details ====================================%
Basic test#
[14]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[14]:
tensor([[ 36.4307],
[ -0.9986],
[ -0.8102],
[ -0.9982],
[ 63.8602],
[ -1.0000],
[ -1.0000],
[237.1113],
[247.2407],
[229.1479]], dtype=torch.float64, grad_fn=<IndexPutBackward0>)
Save torch model#
[15]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")
Clear directory#
[16]:
# 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: reference_feature_values.csv
Deleted folder: MepiClock