McCartneyBMI#

Index#

  1. Instantiate model class

  2. Define clock metadata

  3. Download clock dependencies

  4. Load features

  5. Load weights into base model

  6. Load reference values

  7. Load preprocess and postprocess objects

  8. Check all clock parameters

  9. Basic test

  10. Save torch model

  11. Clear directory

Let’s first import some packages:

[3]:
import os
import inspect
import shutil
import json
import torch
import pandas as pd
import pyaging as pya

Instantiate model class#

[4]:
def print_entire_class(cls):
    source = inspect.getsource(cls)
    print(source)

print_entire_class(pya.models.McCartneyBMI)

class McCartneyBMI(pyagingModel):
    def __init__(self):
        super().__init__()

    def preprocess(self, x):
        return x

    def postprocess(self, x):
        return torch.sigmoid(x)

[5]:
model = pya.models.McCartneyBMI()

Define clock metadata#

[6]:
model.metadata["clock_name"] = 'mccartneybmi'
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 BMI; logistic transform."

Download clock dependencies#

Download coefficient file#

[7]:
coeff_url = "https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/BMI_McCartney.csv"
os.system(f"curl -L {coeff_url} -o BMI_McCartney.csv")

[7]:
0

Load features#

From CSV file#

[8]:
coeffs = pd.read_csv('BMI_McCartney.csv')
coeffs['feature'] = coeffs.iloc[:,0]
coeffs['coefficient'] = coeffs.iloc[:,1]

model.features = coeffs['feature'].tolist()

Load weights into base model#

From CSV file#

[9]:
weights = torch.tensor(coeffs['coefficient'].tolist()).unsqueeze(0)
intercept = torch.tensor([0.0])

Linear model#

[10]:
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#

[11]:
model.reference_values = None

Load preprocess and postprocess objects#

[12]:
model.preprocess_name = None
model.preprocess_dependencies = None

[13]:
model.postprocess_name = "sigmoid"
model.postprocess_dependencies = None

Check all clock parameters#

[14]:
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': 'mccartneybmi',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1186/s13059-018-1514-1',
 'notes': 'DNAm score for BMI; 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', 'cg06192883', 'cg22130834', 'cg25158622', 'cg06822952', 'cg12216054', 'cg05468843', 'cg26033520', 'cg09249494', 'cg17287155', 'cg10144104', 'cg07814318', 'cg18752987', 'cg19338222', 'cg14712058', 'cg09037581', 'cg03546163', 'cg13556604', 'cg11202345', 'cg26542214', 'cg11347311', 'cg15574924', 'cg24687805', 'cg24009074', 'cg02810156', 'cg02780017', 'cg18896032', 'cg12025996', 'cg16544989', 'cg20054939']... [Total elements: 1109]
base_model_features: None

%==================================== Model Details ====================================%
Model Structure:

base_model: LinearModel(
  (linear): Linear(in_features=1109, out_features=1, bias=True)
)

%==================================== Model Details ====================================%
Model Parameters and Weights:

base_model.linear.weight: [0.44655197858810425, 0.2729908227920532, 0.2687903344631195, 0.26774629950523376, 0.26645758748054504, 0.26494982838630676, 0.22834864258766174, 0.22350949048995972, 0.18826699256896973, 0.18071416020393372, 0.18054333329200745, 0.180099219083786, 0.17618653178215027, 0.17354176938533783, 0.16253916919231415, 0.16172534227371216, 0.15112605690956116, 0.1494721919298172, 0.1454235017299652, 0.14240235090255737, 0.14202243089675903, 0.1400214433670044, 0.13216516375541687, 0.1319931447505951, 0.13121949136257172, 0.12723617255687714, 0.12720559537410736, 0.1271865963935852, 0.12628355622291565, 0.12562835216522217]... [Tensor of shape torch.Size([1, 1109])]
base_model.linear.bias: tensor([0.])

%==================================== Model Details ====================================%

Basic Test#

[15]:
torch.manual_seed(42)
input = torch.randn(10, len(model.features), dtype=float)
model.eval()
model.to(float)
pred = model(input)
pred
[15]:
tensor([[0.7759],
        [0.9969],
        [0.8333],
        [0.1892],
        [0.4980],
        [0.0078],
        [0.4152],
        [0.0465],
        [0.9905],
        [0.0217]], dtype=torch.float64, grad_fn=<SigmoidBackward0>)

Save torch model#

[16]:
torch.save(model, f"../weights/{model.metadata['clock_name']}.pt")

Clear directory#

[17]:
# 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: BMI_McCartney.csv