ZhangBLUP#
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.ZhangBLUP)
class ZhangBLUP(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
"""
Scales the input PyTorch tensor per row with mean 0 and std 1.
"""
row_means = torch.mean(x, dim=1, keepdim=True)
row_stds = torch.std(x, dim=1, keepdim=True)
# Avoid division by zero in case of a row with constant value
row_stds = torch.where(row_stds == 0, torch.ones_like(row_stds), row_stds)
x_scaled = (x - row_means) / row_stds
return x_scaled
def postprocess(self, x):
return x
[3]:
model = pya.models.ZhangBLUP()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'zhangblup'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2019
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Zhang, Qian, et al. \"Improved precision of epigenetic clock estimates across tissues and its implication for biological ageing.\" Genome medicine 11 (2019): 1-11."
model.metadata["doi"] = 'https://doi.org/10.1186/s13073-019-0667-1'
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download GitHub repository#
[5]:
github_url = "https://github.com/qzhang314/DNAm-based-age-predictor.git"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")
[5]:
0
Download from R package#
[6]:
%%writefile download.r
data = readRDS("DNAm-based-age-predictor/data.rds")
write.csv(data, "example_data.csv")
Writing download.r
[7]:
os.system("Rscript download.r")
[7]:
0
Load features#
From CSV file#
[8]:
df = pd.read_table('DNAm-based-age-predictor/blup.coef', sep=' ')
df['feature'] = df['probe']
df['coefficient'] = df['coef']
model.features = df['feature'][1:].tolist()
Load weights into base model#
[9]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'][0]])
Linear model#
[10]:
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#
[11]:
reference_feature_values_df = pd.read_csv('example_data.csv', index_col=0)
reference_feature_values_df = reference_feature_values_df.loc[:, model.features]
model.reference_values = reference_feature_values_df.mean().tolist()
Load preprocess and postprocess objects#
[12]:
model.preprocess_name = 'scale_row'
model.preprocess_dependencies = None
[13]:
model.postprocess_name = None
model.postprocess_dependencies = None
Check all clock parameters#
[14]:
pya.utils.print_model_details(model)
%==================================== Model Details ====================================%
Model Attributes:
training: True
metadata: {'approved_by_author': '⌛',
'citation': 'Zhang, Qian, et al. "Improved precision of epigenetic clock '
'estimates across tissues and its implication for biological '
'ageing." Genome medicine 11 (2019): 1-11.',
'clock_name': 'zhangblup',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13073-019-0667-1',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2019}
reference_values: [0.05946290980445651, 0.9016779859564634, 0.8511621554128406, 0.07497523935546724, 0.08079601941558237, 0.13789119095690058, 0.959990162673912, 0.054840405638908254, 0.11271586156940745, 0.06867464793155438, 0.04092332774669377, 0.03122014881875939, 0.12091171597794977, 0.8626077673429406, 0.02002095456899887, 0.037161243530447204, 0.5228131230887364, 0.025038065219011623, 0.03411737762225109, 0.023966201717807785, 0.13213191286915785, 0.03613520841142101, 0.11053625925027737, 0.09303164766153527, 0.07697707482010466, 0.040677518106921974, 0.016422537053260692, 0.01646509240082735, 0.9634930275356334, 0.8664078943468241]... [Total elements: 319607]
preprocess_name: 'scale_row'
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg18478105', 'cg14361672', 'cg01763666', 'cg02115394', 'cg13417420', 'cg12480843', 'cg26724186', 'cg24133276', 'cg19607165', 'cg11073926', 'cg08770523', 'cg24040570', 'cg15998406', 'cg11947782', 'cg11945228', 'cg14361409', 'cg00376553', 'cg12898275', 'cg21650422', 'cg24176744', 'cg08360726', 'cg07469408', 'cg08730728', 'cg22782271', 'cg26846647', 'cg24568647', 'cg01415275', 'cg00172270', 'cg27548741', 'cg09659208']... [Total elements: 319607]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=319607, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.011127361096441746, 0.0005570068024098873, -0.01769556663930416, 0.009089098311960697, -0.016315005719661713, -0.012607994489371777, -0.006776333786547184, 0.005497894249856472, -0.031007202342152596, 0.007024446967989206, 0.0072049410082399845, 0.006631432566791773, -0.028644423931837082, -0.0067995828576385975, -0.003207291942089796, -0.010230086743831635, 0.002228884259238839, -0.0012665422400459647, 0.010415713302791119, -0.0016215209616348147, 0.015202521346509457, -0.0019047950627282262, -0.01444777101278305, 0.01679779589176178, -0.0016255266964435577, -0.0027738267090171576, -0.0028552687726914883, 0.0026693870313465595, 0.0018644158262759447, 0.004981260746717453]... [Tensor of shape torch.Size([1, 319607])]
base_model.linear.bias: tensor([91.1540])
%==================================== Model Details ====================================%
Basic test#
[15]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[15]:
tensor([[107.0536],
[ 90.5363],
[ 81.2531],
[ 97.2001],
[ 91.7565],
[ 95.9860],
[ 97.9471],
[ 97.2143],
[107.3615],
[ 90.4772]], dtype=torch.float64, grad_fn=<AddmmBackward0>)
Save torch model#
[16]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")
Clear directory#
[17]:
# 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: download.r
Deleted folder: DNAm-based-age-predictor
Deleted file: example_data.csv