McCartneyTotalCholesterol#
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.McCartneyTotalCholesterol)
class McCartneyTotalCholesterol(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return torch.sigmoid(x)
[3]:
model = pya.models.McCartneyTotalCholesterol()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'mccartneytotalcholesterol'
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 total cholesterol; logistic transform."
Download clock dependencies#
Download coefficient file#
[5]:
coeff_url = "https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/TotalCholesterolMcCartney.csv"
os.system(f"curl -L {coeff_url} -o TotalCholesterolMcCartney.csv")
[5]:
0
Load features#
From CSV file#
[6]:
coeffs = pd.read_csv('TotalCholesterolMcCartney.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': 'mccartneytotalcholesterol',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13059-018-1514-1',
'notes': 'DNAm score for total 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: ['cg26832552', 'cg19631443', 'cg17901584', 'cg01185855', 'cg16000331', 'cg09984392', 'cg25739715', 'cg05119988', 'cg05922723', 'cg20113693', 'cg19201009', 'cg07839457', 'cg02901884', 'cg02823783', 'cg03281139', 'cg16533147', 'cg03639897', 'cg08912317', 'cg06572420', 'cg03443112', 'cg00448707', 'cg00917847', 'cg22813794', 'cg00908766', 'cg01634275', 'cg23594461', 'cg04254198', 'cg12054453', 'cg01242196', 'cg26500914']... [Total elements: 204]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=204, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [1.8702744245529175, 1.7534682750701904, 1.7346389293670654, 1.548874855041504, 1.4452730417251587, 0.9110820889472961, 0.8424054384231567, 0.6070092916488647, 0.577074408531189, 0.5554218888282776, 0.5035273432731628, 0.49849238991737366, 0.4704321622848511, 0.4700091481208801, 0.4278366267681122, 0.41685277223587036, 0.39084771275520325, 0.3782665431499481, 0.36339235305786133, 0.36092403531074524, 0.354301780462265, 0.33795109391212463, 0.32012227177619934, 0.31936484575271606, 0.3117227554321289, 0.31170734763145447, 0.30839231610298157, 0.3047521710395813, 0.28629252314567566, 0.26939573884010315]... [Tensor of shape torch.Size([1, 204])]
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([[6.8740e-02],
[1.6698e-04],
[3.6126e-02],
[9.9174e-01],
[4.1910e-03],
[4.4388e-01],
[9.0027e-03],
[7.6351e-01],
[8.8253e-01],
[1.3288e-05]], 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: TotalCholesterolMcCartney.csv