GrimAge2LogCRP#
Index#
Let’s first import some packages:
[34]:
import os
import inspect
import shutil
import json
import torch
import pandas as pd
import pyaging as pya
import numpy as np
Instantiate model class#
[35]:
def print_entire_class(cls):
source = inspect.getsource(cls)
print(source)
print_entire_class(pya.models.GrimAge2LogCRP)
class GrimAge2LogCRP(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[36]:
model = pya.models.GrimAge2LogCRP()
Define clock metadata#
[37]:
model.metadata["clock_name"] = 'grimage2logcrp'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2022
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Lu, Ake T., et al. \"DNA methylation GrimAge version 2.\" Aging (Albany NY) 14.23 (2022): 9484."
model.metadata["doi"] = "https://doi.org/10.18632/aging.204434"
model.metadata["research_only"] = True
model.metadata["notes"] = None
Download clock dependencies#
[38]:
logger = pya.logger.Logger()
urls = [
"https://pyaging.s3.amazonaws.com/supporting_files/grimage2_subcomponents.csv",
"https://pyaging.s3.amazonaws.com/supporting_files/grimage2.csv",
"https://pyaging.s3.amazonaws.com/supporting_files/datMiniAnnotation3_Gold.csv",
]
dir = "."
for url in urls:
pya.utils.download(url, dir, logger, indent_level=1)
|-----------> Downloading data to ./grimage2_subcomponents.csv
|-----------> in progress: 100.0000%
|-----------> Downloading data to ./grimage2.csv
|-----------> in progress: 100.0000%%
|-----------> Downloading data to ./datMiniAnnotation3_Gold.csv
|-----------> in progress: 100.0000%
Load features#
From CSV#
[39]:
df = pd.read_csv('grimage2_subcomponents.csv', index_col=0)
df['Y.pred'].unique()
[39]:
array(['DNAmGDF_15', 'DNAmB2M', 'DNAmCystatin_C', 'DNAmTIMP_1', 'DNAmadm',
'DNAmpai_1', 'DNAmleptin', 'DNAmPACKYRS', 'DNAmlog.CRP',
'DNAmlog.A1C'], dtype=object)
[40]:
df = df[df['Y.pred'] == 'DNAmlog.CRP']
df['feature'] = df['var']
df['coefficient'] = df['beta']
model.features = df['feature'][1:].tolist()
[41]:
df.head()
[41]:
| Y.pred | var | beta | feature | coefficient | |
|---|---|---|---|---|---|
| 1796 | DNAmlog.CRP | Intercept | -0.231448 | Intercept | -0.231448 |
| 1797 | DNAmlog.CRP | cg01391867 | -0.238114 | cg01391867 | -0.238114 |
| 1798 | DNAmlog.CRP | cg06298190 | 0.137911 | cg06298190 | 0.137911 |
| 1799 | DNAmlog.CRP | cg03110633 | 0.397843 | cg03110633 | 0.397843 |
| 1800 | DNAmlog.CRP | cg05303999 | 0.445975 | cg05303999 | 0.445975 |
Load weights into base model#
Linear model#
[42]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'].iloc[0]])
Linear model#
[43]:
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#
[44]:
reference_df = pd.read_csv('datMiniAnnotation3_Gold.csv', index_col=0)
model.reference_values = reference_df.loc[model.features[0:]]['gold'].tolist()
Load preprocess and postprocess objects#
[45]:
model.preprocess_name = None
model.preprocess_dependencies = None
[46]:
model.postprocess_name = None
model.postprocess_dependencies = None
Check all clock parameters#
[47]:
pya.utils.print_model_details(model)
%==================================== Model Details ====================================%
Model Attributes:
training: True
metadata: {'approved_by_author': '⌛',
'citation': 'Lu, Ake T., et al. "DNA methylation GrimAge version 2." Aging '
'(Albany NY) 14.23 (2022): 9484.',
'clock_name': 'grimage2logcrp',
'data_type': 'methylation',
'doi': 'https://doi.org/10.18632/aging.204434',
'notes': None,
'research_only': True,
'species': 'Homo sapiens',
'version': None,
'year': 2022}
reference_values: [0.0229199108411034, 0.18157609704669, 0.0145712286188007, 0.913922509481157, 0.809605421222521, 0.703858551128724, 0.828079343471397, 0.8354705752375, 0.945562513470214, 0.219544227570287, 0.628295804305801, 0.0556920557050531, 0.883510168741842, 0.80868027489568, 0.942843729694158, 0.175324342316158, 0.873109700042845, 0.0947894779919567, 0.733082005089516, 0.883065598559295, 0.127222466210419, 0.846006900277736, 0.323099124395025, 0.0672194476736834, 0.919339370837926, 0.0989639070730932, 0.932356263376567, 0.0528287534203248, 0.219316986390691, 0.92697340543759]... [Total elements: 132]
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'cox_to_years'
postprocess_dependencies: None
features: ['cg01391867', 'cg06298190', 'cg03110633', 'cg05303999', 'cg01130991', 'cg13316619', 'cg20747455', 'cg26471058', 'cg02135821', 'cg18376497', 'cg12035880', 'cg02713068', 'cg02495445', 'cg03788610', 'cg08055490', 'cg06975311', 'cg22163406', 'cg22455450', 'cg03574306', 'cg13155421', 'cg22902266', 'cg09566331', 'cg26403843', 'cg06560379', 'cg13565994', 'cg07989867', 'cg21658515', 'cg05313771', 'cg12363682', 'cg19647685']... [Total elements: 132]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=132, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-0.2381139099597931, 0.13791120052337646, 0.3978428244590759, 0.44597509503364563, 0.06502892822027206, -0.11037616431713104, 0.0026236912235617638, 0.13811077177524567, -1.9391815662384033, 0.02908332832157612, 0.28280875086784363, 0.9672318696975708, -0.09226538240909576, -0.20673252642154694, -0.8090327382087708, 3.308124303817749, 0.3115508258342743, 0.24958042800426483, 0.009494591504335403, -0.5394561886787415, 0.852174699306488, 0.03074250929057598, 0.02842751331627369, -1.275362491607666, 2.463428497314453, 0.08571851998567581, -0.8256807923316956, -1.2374017238616943, 0.29840514063835144, -0.22478485107421875]... [Tensor of shape torch.Size([1, 132])]
base_model.linear.bias: tensor([-0.2314])
%==================================== Model Details ====================================%
Basic test#
[48]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float).double()
model.eval()
model.to(float)
pred = model(input)
pred
[48]:
tensor([[ -1.5050],
[ -5.0319],
[ 1.0132],
[-24.1760],
[ -8.6024],
[ -5.2143],
[ 13.2554],
[ -3.3618],
[-10.8422],
[ -6.0286]], dtype=torch.float64, grad_fn=<AddmmBackward0>)
Save torch model#
[49]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")
Clear directory#
[50]:
# 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: grimage2_subcomponents.csv
Deleted file: datMiniAnnotation3_Gold.csv
Deleted file: grimage2.csv