DNAmPhenoAge#
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.DNAmPhenoAge)
class DNAmPhenoAge(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.DNAmPhenoAge()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'dnamphenoage'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2018
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Levine, Morgan E., et al. \"An epigenetic biomarker of aging for lifespan and healthspan.\" Aging (albany NY) 10.4 (2018): 573."
model.metadata["doi"] = 'https://doi.org/10.18632%2Faging.101414'
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5940111/bin/aging-10-101414-s002.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')
model.features = df['CpG'][1:].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(df['Weight'][1:].tolist()).unsqueeze(0).float()
intercept = torch.tensor([df['Weight'][0]]).float()
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 = None
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': 'Levine, Morgan E., et al. "An epigenetic biomarker of aging for '
'lifespan and healthspan." Aging (albany NY) 10.4 (2018): 573.',
'clock_name': 'dnamphenoage',
'data_type': 'methylation',
'doi': 'https://doi.org/10.18632%2Faging.101414',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2018}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg15611364', 'cg17605084', 'cg26382071', 'cg12743894', 'cg19287114', 'cg12985418', 'cg19398783', 'cg15963417', 'cg27187881', 'cg09892203', 'cg00943950', 'cg18996776', 'cg16340918', 'cg23832061', 'cg22736354', 'cg04084157', 'cg07265300', 'cg02503970', 'cg11426590', 'cg23710218', 'cg02802055', 'cg13631913', 'cg06493994', 'cg24304712', 'cg01131735', 'cg24208206', 'cg01930621', 'cg19104072', 'cg07850604', 'cg27493997']... [Total elements: 513]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=513, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [63.124149322509766, -44.00939178466797, 40.42085266113281, 36.788185119628906, -36.49384307861328, -35.900089263916016, 35.83308410644531, -34.698429107666016, -33.54555892944336, -33.48234558105469, 33.47697830200195, 33.05057144165039, 32.14665603637695, -31.902469635009766, 31.842193603515625, 31.62165641784668, 28.398008346557617, 25.585140228271484, -24.78579330444336, 24.158702850341797, -24.117156982421875, 23.838054656982422, 23.372079849243164, 23.300357818603516, -22.9146671295166, 22.540685653686523, -21.787927627563477, -21.598669052124023, 21.31021499633789, -21.20072364807129]... [Tensor of shape torch.Size([1, 513])]
base_model.linear.bias: tensor([60.6640])
%==================================== 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([[ 134.9219],
[ 396.0094],
[-309.7721],
[ 77.3113],
[-209.0913],
[-141.9328],
[ 424.4550],
[-125.9833],
[-119.9547],
[-250.8203]], dtype=torch.float64, grad_fn=<AddmmBackward0>)
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