PipekFilteredH#
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.PipekFilteredH)
class PipekFilteredH(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.PipekFilteredH()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'pipekfilteredh'
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['filtered H (272)']
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': 'pipekfilteredh',
'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', 'cg01262913', 'cg01353448', 'cg01407797', 'cg01459453', 'cg01485645', 'cg01511567', 'cg01560871', 'cg01570885', 'cg01584473', 'cg01644850', 'cg01656216', 'cg01820374', 'cg01873645', 'cg01968178', 'cg02047577', 'cg02071305', 'cg02154074', 'cg02217159', 'cg02331561', 'cg02332492', 'cg02335441']... [Total elements: 272]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=272, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.22881552577018738, -0.2377861887216568, -0.24946625530719757, 0.17744497954845428, -0.06299065053462982, 0.08542506396770477, 0.7163512110710144, 0.16196946799755096, 0.20421390235424042, -0.326388955116272, 0.20446790754795074, -0.23128832876682281, -0.37111058831214905, -0.4445556700229645, -0.43028509616851807, -0.12531816959381104, -0.12910425662994385, 0.045132577419281006, 0.12630127370357513, 0.07573168724775314, -0.1765550971031189, -0.7539004683494568, 1.0425814390182495, -3.9124810695648193, -0.08756565302610397, 0.272698312997818, -0.09734031558036804, 0.10432395339012146, 0.2949163019657135, -0.606216311454773]... [Tensor of shape torch.Size([1, 272])]
base_model.linear.bias: tensor([0.6936])
%==================================== 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([[ 15.1563],
[ 1.8620],
[336.2259],
[ 91.3016],
[294.5217],
[ -0.9924],
[ -0.9725],
[ 64.7511],
[ 17.1090],
[ 9.7820]], 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