McCartneyBodyFat#
Index#
Let’s first import some packages:
[5]:
import os
import inspect
import shutil
import json
import torch
import pandas as pd
import pyaging as pya
Instantiate model class#
[6]:
def print_entire_class(cls):
source = inspect.getsource(cls)
print(source)
print_entire_class(pya.models.McCartneyBodyFat)
class McCartneyBodyFat(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return torch.sigmoid(x)
[7]:
model = pya.models.McCartneyBodyFat()
Define clock metadata#
[8]:
model.metadata["clock_name"] = 'mccartneybodyfat'
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 body fat percentage; logistic transform."
Download clock dependencies#
Download coefficient file#
[9]:
coeff_url = "https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/BodyFatMcCartney.csv"
os.system(f"curl -L {coeff_url} -o BodyFatMcCartney.csv")
[9]:
0
Load features#
From CSV file#
[10]:
coeffs = pd.read_csv('BodyFatMcCartney.csv')
coeffs['feature'] = coeffs.iloc[:,0]
coeffs['coefficient'] = coeffs.iloc[:,1]
model.features = coeffs['feature'].tolist()
Load weights into base model#
From CSV file#
[11]:
weights = torch.tensor(coeffs['coefficient'].tolist()).unsqueeze(0)
intercept = torch.tensor([0.0])
Linear model#
[12]:
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#
[13]:
model.reference_values = None
Load preprocess and postprocess objects#
[14]:
model.preprocess_name = None
model.preprocess_dependencies = None
[15]:
model.postprocess_name = "sigmoid"
model.postprocess_dependencies = None
Check all clock parameters#
[16]:
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': 'mccartneybodyfat',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13059-018-1514-1',
'notes': 'DNAm score for body fat percentage; 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: ['cg06500161', 'cg05744675', 'cg06568506', 'cg06192883', 'cg25158622', 'cg21176130', 'cg04086445', 'cg26033520', 'cg05468843', 'cg20347986', 'cg17500119', 'cg00701514', 'cg09848445', 'cg11202345', 'cg20495962', 'cg03234777', 'cg17150306', 'cg18853935', 'cg19887178', 'cg17287155', 'cg01937601', 'cg17473923', 'cg20054939', 'cg00799631', 'cg10409248', 'cg26983874', 'cg10196309', 'cg25921813', 'cg27396655', 'cg08858160']... [Total elements: 968]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=968, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [17.009260177612305, 13.952584266662598, 13.8219633102417, 12.232629776000977, 12.198307037353516, 12.024375915527344, 10.987481117248535, 10.905646324157715, 10.629822731018066, 10.109126091003418, 9.78788948059082, 9.1156005859375, 8.941770553588867, 8.878946304321289, 8.463309288024902, 7.700728416442871, 7.354093551635742, 6.861233234405518, 6.658877849578857, 6.449416160583496, 6.411191940307617, 6.20827054977417, 6.0269551277160645, 5.763856410980225, 5.442668914794922, 5.3892903327941895, 5.105152130126953, 4.995013236999512, 4.9773173332214355, 4.972265720367432]... [Tensor of shape torch.Size([1, 968])]
base_model.linear.bias: tensor([0.])
%==================================== Model Details ====================================%
Basic Test#
[17]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[17]:
tensor([[4.7729e-13],
[1.0000e+00],
[9.8856e-01],
[5.2320e-71],
[1.0000e+00],
[1.0000e+00],
[1.0431e-36],
[1.0000e+00],
[2.3326e-63],
[1.0000e+00]], dtype=torch.float64, grad_fn=<SigmoidBackward0>)
Save torch model#
[18]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")
Clear directory#
[19]:
# 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: BodyFatMcCartney.csv