McCartneyLDLCholesterol#
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.McCartneyLDLCholesterol)
class McCartneyLDLCholesterol(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return torch.sigmoid(x)
[3]:
model = pya.models.McCartneyLDLCholesterol()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'mccartneyldlcholesterol'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2018
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "McCartney, Daniel L., et al. \"Epigenetic prediction of complex traits and death.\" Genome biology 19.1 (2018): 136."
model.metadata["doi"] = "https://doi.org/10.1186/s13059-018-1514-1"
model.metadata["research_only"] = None
model.metadata["notes"] = "DNAm score for LDL with remnant cholesterol; logistic transform."
Download clock dependencies#
Download coefficient file#
[5]:
coeff_url = "https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/LDLCholesterolMcCartney.csv"
os.system(f"curl -L {coeff_url} -o LDLCholesterolMcCartney.csv")
[5]:
0
Load features#
From CSV file#
[6]:
coeffs = pd.read_csv('LDLCholesterolMcCartney.csv')
coeffs['feature'] = coeffs.iloc[:,0]
coeffs['coefficient'] = coeffs.iloc[:,1]
model.features = coeffs['feature'].tolist()
Load weights into base model#
From CSV file#
[7]:
weights = torch.tensor(coeffs['coefficient'].tolist()).unsqueeze(0)
intercept = torch.tensor([0.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 = "sigmoid"
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': 'McCartney, Daniel L., et al. "Epigenetic prediction of complex '
'traits and death." Genome biology 19.1 (2018): 136.',
'clock_name': 'mccartneyldlcholesterol',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13059-018-1514-1',
'notes': 'DNAm score for LDL with remnant cholesterol; logistic transform.',
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2018}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'sigmoid'
postprocess_dependencies: None
features: ['cg17140673', 'cg16000331', 'cg26832552', 'cg01185855', 'cg09984392', 'cg02823783', 'cg05922723', 'cg03281139', 'cg25158622', 'cg13899478', 'cg03639897', 'cg04816311', 'cg22813794', 'cg08912317', 'cg08864105', 'cg01959050', 'cg00908766', 'cg16533147', 'cg23594461', 'cg01242196', 'cg01041239', 'cg18997433', 'cg01634275', 'cg07015911', 'cg00917847', 'cg03546163', 'cg09397900', 'cg26500914', 'cg19631443', 'cg14262937']... [Total elements: 233]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=233, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [2.3404996395111084, 1.773403525352478, 1.4230562448501587, 1.208232045173645, 1.0788904428482056, 0.9202911257743835, 0.6753129363059998, 0.5701111555099487, 0.5084759593009949, 0.4510941505432129, 0.4501569867134094, 0.44724032282829285, 0.4422180950641632, 0.40404877066612244, 0.39743274450302124, 0.39364108443260193, 0.380549818277359, 0.38022148609161377, 0.37155863642692566, 0.3543321490287781, 0.32864290475845337, 0.32437676191329956, 0.324343204498291, 0.31292271614074707, 0.3106697201728821, 0.2984561622142792, 0.2978762984275818, 0.2949866056442261, 0.29482847452163696, 0.286639541387558]... [Tensor of shape torch.Size([1, 233])]
base_model.linear.bias: tensor([0.])
%==================================== 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([[3.3513e-01],
[5.1082e-06],
[1.5130e-08],
[1.7122e-01],
[6.2656e-09],
[9.6703e-04],
[1.0000e+00],
[9.9589e-01],
[9.9999e-01],
[9.0386e-11]], dtype=torch.float64, grad_fn=<SigmoidBackward0>)
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: LDLCholesterolMcCartney.csv