GrimAge2LogA1C#
Index#
Let’s first import some packages:
[17]:
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#
[18]:
def print_entire_class(cls):
source = inspect.getsource(cls)
print(source)
print_entire_class(pya.models.GrimAge2LogA1C)
class GrimAge2LogA1C(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[19]:
model = pya.models.GrimAge2LogA1C()
Define clock metadata#
[20]:
model.metadata["clock_name"] = 'grimage2loga1c'
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#
[21]:
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#
[22]:
df = pd.read_csv('grimage2_subcomponents.csv', index_col=0)
df['Y.pred'].unique()
[22]:
array(['DNAmGDF_15', 'DNAmB2M', 'DNAmCystatin_C', 'DNAmTIMP_1', 'DNAmadm',
'DNAmpai_1', 'DNAmleptin', 'DNAmPACKYRS', 'DNAmlog.CRP',
'DNAmlog.A1C'], dtype=object)
[23]:
df = df[df['Y.pred'] == 'DNAmlog.A1C']
df['feature'] = df['var']
df['coefficient'] = df['beta']
model.features = ['age'] + df['feature'][2:].tolist()
[24]:
df.head()
[24]:
| Y.pred | var | beta | feature | coefficient | |
|---|---|---|---|---|---|
| 1929 | DNAmlog.A1C | Intercept | 1.613356 | Intercept | 1.613356 |
| 1930 | DNAmlog.A1C | Age | 0.000048 | Age | 0.000048 |
| 1931 | DNAmlog.A1C | cg14260002 | 0.205684 | cg14260002 | 0.205684 |
| 1932 | DNAmlog.A1C | cg07592681 | -0.132551 | cg07592681 | -0.132551 |
| 1933 | DNAmlog.A1C | cg06959205 | -0.008526 | cg06959205 | -0.008526 |
Load weights into base model#
Linear model#
[25]:
weights = torch.tensor(df['coefficient'][1:].tolist()).unsqueeze(0)
intercept = torch.tensor([df['coefficient'].iloc[0]])
Linear model#
[26]:
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#
[27]:
reference_df = pd.read_csv('datMiniAnnotation3_Gold.csv', index_col=0)
model.reference_values = [65] + reference_df.loc[model.features[1:]]['gold'].tolist()
Load preprocess and postprocess objects#
[28]:
model.preprocess_name = None
model.preprocess_dependencies = None
[29]:
model.postprocess_name = None
model.postprocess_dependencies = None
Check all clock parameters#
[30]:
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': 'grimage2loga1c',
'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: [65, 0.931162975482825, 0.902618842256319, 0.526434127110235, 0.809605421222521, 0.836130800392971, 0.0600816991722836, 0.332104407846093, 0.0512855773762465, 0.805395132732413, 0.565221968837601, 0.0752133473674328, 0.0979220649321982, 0.702649834869793, 0.0701168220050587, 0.733082005089516, 0.182279578592817, 0.768742491924122, 0.0587619174529237, 0.36823650486503, 0.812900664876887, 0.0463349565573039, 0.769921114503612, 0.442744708206467, 0.323099124395025, 0.0672194476736834, 0.732325325233028, 0.296671896347774, 0.830024180811995, 0.190899351132785]... [Total elements: 87]
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'cox_to_years'
postprocess_dependencies: None
features: ['age', 'cg14260002', 'cg07592681', 'cg06959205', 'cg01130991', 'cg02193806', 'cg17058475', 'cg01517384', 'cg11333189', 'cg24420742', 'cg19719391', 'cg13620770', 'cg23777956', 'cg22650271', 'cg08074820', 'cg03574306', 'cg20686207', 'cg07660627', 'cg22277972', 'cg17543884', 'cg03259703', 'cg14073590', 'cg23842572', 'cg04323814', 'cg26403843', 'cg06560379', 'cg13842421', 'cg11444009', 'cg00684178', 'cg26009035']... [Total elements: 87]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=87, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [4.8407757276436314e-05, 0.2056836038827896, -0.13255050778388977, -0.008526227436959743, 0.05746829882264137, 0.012243995442986488, -0.09515052288770676, -0.006345819681882858, 0.016126316040754318, 0.0014027197612449527, 0.11271747201681137, -0.0036691571585834026, -0.012557895854115486, 0.08038703352212906, 0.02936549112200737, 0.0017015821067616343, 0.00732465973123908, 0.014937152154743671, -0.21280202269554138, 0.012396476231515408, -0.03226955980062485, 0.007510123774409294, 0.03052537515759468, 0.007964993827044964, 0.044394396245479584, -0.16780716180801392, -0.00614670105278492, 0.04923776164650917, -0.020067188888788223, 0.003006122075021267]... [Tensor of shape torch.Size([1, 87])]
base_model.linear.bias: tensor([1.6134])
%==================================== Model Details ====================================%
Basic test#
[31]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float).double()
model.eval()
model.to(float)
pred = model(input)
pred
[31]:
tensor([[1.1562],
[1.7227],
[2.0204],
[1.3346],
[1.3498],
[1.7763],
[2.2459],
[2.1019],
[1.3236],
[1.4237]], dtype=torch.float64, grad_fn=<AddmmBackward0>)
Save torch model#
[32]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")
Clear directory#
[33]:
# 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