SkinAndBlood#
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.SkinAndBlood)
class SkinAndBlood(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.SkinAndBlood()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'skinandblood'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2018
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Horvath, Steve, et al. \"Epigenetic clock for skin and blood cells applied to Hutchinson Gilford Progeria Syndrome and ex vivo studies.\" Aging (Albany NY) 10.7 (2018): 1758."
model.metadata["doi"] = "https://doi.org/10.18632/aging.101508"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://www.aging-us.com/article/101508/supplementary/SD5/0/aging-v10i7-101508-supplementary-material-SD5.csv"
supplementary_file_name = "coefficients.csv"
os.system(f"curl -o {supplementary_file_name} {supplementary_url}")
[5]:
0
Load features#
From CSV file#
[6]:
df = pd.read_csv('coefficients.csv')
df['feature'] = df['ID']
df['coefficient'] = df['Coef']
model.features = df['feature'][1:].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'][0]])
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 = 'anti_log_linear'
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': 'Horvath, Steve, et al. "Epigenetic clock for skin and blood '
'cells applied to Hutchinson Gilford Progeria Syndrome and ex '
'vivo studies." Aging (Albany NY) 10.7 (2018): 1758.',
'clock_name': 'skinandblood',
'data_type': 'methylation',
'doi': 'https://doi.org/10.18632/aging.101508',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2018}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'anti_log_linear'
postprocess_dependencies: None
features: ['cg12140144', 'cg26933021', 'cg20822990', 'cg07312601', 'cg09993145', 'cg23605843', 'cg25410668', 'cg17879376', 'cg14962509', 'cg24375409', 'cg22851420', 'cg24107728', 'cg14614643', 'cg00257455', 'cg23045908', 'cg15201877', 'cg18933331', 'cg05675373', 'cg19269039', 'cg16008966', 'cg14565725', 'cg05940231', 'cg03984502', 'cg25256723', 'cg16054275', 'cg01459453', 'cg16599143', 'cg02275294', 'cg21870884', 'cg10501210']... [Total elements: 391]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=391, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.3631811738014221, -0.09050008654594421, -0.007025233935564756, -0.13509239256381989, -0.042639341205358505, 0.07938723266124725, 0.2780052423477173, -0.2027093917131424, 0.1823105365037918, -0.02380458638072014, 0.09719781577587128, -0.10654273629188538, -0.04339298605918884, -0.1616985946893692, 0.13732706010341644, 0.3920976221561432, -0.2317628413438797, 0.024479255080223083, -0.017557984218001366, -0.20390775799751282, -0.03556407615542412, -0.10670483857393265, 0.22212129831314087, -0.12098140269517899, -0.23396819829940796, 0.041907940059900284, 0.1419801115989685, -0.14286929368972778, -0.012681434862315655, -0.3165263533592224]... [Tensor of shape torch.Size([1, 391])]
base_model.linear.bias: tensor([-0.4471])
%==================================== 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([[-0.7403],
[-0.9991],
[-0.5375],
[48.3885],
[-0.1838],
[-0.3993],
[15.9029],
[58.4267],
[ 0.6595],
[22.1512]], dtype=torch.float64, grad_fn=<IndexPutBackward0>)
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 file: coefficients.csv