McCartneyHDLCholesterol#
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.McCartneyHDLCholesterol)
class McCartneyHDLCholesterol(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return torch.sigmoid(x)
[3]:
model = pya.models.McCartneyHDLCholesterol()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'mccartneyhdlcholesterol'
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 HDL cholesterol; logistic transform."
Download clock dependencies#
Download coefficient file#
[5]:
coeff_url = "https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/HDLCholesterolMcCartney.csv"
os.system(f"curl -L {coeff_url} -o HDLCholesterolMcCartney.csv")
[5]:
0
Load features#
From CSV file#
[6]:
coeffs = pd.read_csv('HDLCholesterolMcCartney.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': 'mccartneyhdlcholesterol',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13059-018-1514-1',
'notes': 'DNAm score for HDL 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: ['cg08461397', 'cg03966449', 'cg00574958', 'cg03819713', 'cg17901584', 'cg06933816', 'cg21420474', 'cg25732961', 'cg15107724', 'cg05484949', 'cg08577384', 'cg12437873', 'cg20396385', 'cg02075454', 'cg02311374', 'cg06767142', 'cg11082362', 'cg20493718', 'cg00467244', 'cg03477609', 'cg24730871', 'cg04330884', 'cg13676763', 'cg10166888', 'cg01930746', 'cg23839792', 'cg02071579', 'cg06572420', 'cg24002003', 'cg15037541']... [Total elements: 737]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=737, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [1.2764034271240234, 1.1563647985458374, 1.151691198348999, 0.9696499705314636, 0.8932946920394897, 0.8755561113357544, 0.6930485367774963, 0.6715324521064758, 0.6511539816856384, 0.5719676613807678, 0.49284738302230835, 0.47472161054611206, 0.4651602804660797, 0.4606964886188507, 0.44631731510162354, 0.43104445934295654, 0.4300815761089325, 0.4224322736263275, 0.4066919684410095, 0.37325549125671387, 0.3681565225124359, 0.35287514328956604, 0.3447624146938324, 0.34371402859687805, 0.341357946395874, 0.32900702953338623, 0.31925708055496216, 0.306514710187912, 0.3057454824447632, 0.2942475974559784]... [Tensor of shape torch.Size([1, 737])]
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([[0.9916],
[0.0043],
[0.9954],
[0.0554],
[0.9549],
[0.9950],
[0.0022],
[0.0187],
[0.1916],
[0.9975]], 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: HDLCholesterolMcCartney.csv