PipekElasticNet#
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.PipekElasticNet)
class PipekElasticNet(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.PipekElasticNet()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'pipekelasticnet'
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]:
32768
Load features#
From CSV file#
[7]:
df = pd.read_csv('MepiClock/resources/model_coefficients.csv', sep=';')
df['feature'] = df['probeID']
df['coefficient'] = df['elasticNet (239)']
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': 'pipekelasticnet',
'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: ['cg00027083', 'cg00059225', 'cg00075967', 'cg00168942', 'cg00290506', 'cg00343092', 'cg00528967', 'cg00651216', 'cg00812502', 'cg00864867', 'cg01222684', 'cg01262913', 'cg01294695', 'cg01353448', 'cg01407797', 'cg01459453', 'cg01485645', 'cg01507173', 'cg01511567', 'cg01570885', 'cg01580568', 'cg01580888', 'cg01860753', 'cg01968793', 'cg01994328', 'cg02217159', 'cg02275294', 'cg02332492', 'cg02335441', 'cg02388150']... [Total elements: 239]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=239, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.1439734548330307, 1.4801537990570068, 0.03225376456975937, -0.0058419122360646725, -0.9698857665061951, -0.02445327118039131, -0.25678759813308716, -0.1429552286863327, -0.45733991265296936, 0.03336525335907936, 0.06893794238567352, -0.016240336000919342, -0.028347602114081383, 0.08623908460140228, -0.006927416194230318, -0.4072648584842682, -0.11168642342090607, 0.0335581935942173, -1.1504876613616943, -0.18203186988830566, 0.06303419172763824, 0.7362451553344727, -0.01122856605798006, -0.1645817756652832, -0.3766438066959381, -0.22185027599334717, -0.14580827951431274, 0.11524636298418045, -0.07323136180639267, 0.19775758683681488]... [Tensor of shape torch.Size([1, 239])]
base_model.linear.bias: tensor([0.3361])
%==================================== 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([[ 26.4756],
[ 69.0214],
[ -0.9994],
[ -0.9954],
[ 9.0836],
[204.6643],
[146.1240],
[ -0.9388],
[ 94.5212],
[ 54.5029]], 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