SmokingMcCartney#
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.McCartneySmoking)
class McCartneySmoking(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.McCartneySmoking()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'mccartneysmoking'
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"] = "Linear CpG score; higher values indicate smoking exposure."
Download clock dependencies#
Download coefficient file#
[5]:
coeff_url = "https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/Smoking.csv"
os.system(f"curl -L {coeff_url} -o Smoking.csv")
[5]:
0
Load features#
From CSV file#
[6]:
coeffs = pd.read_csv('Smoking.csv')
coeffs['feature'] = coeffs['CpGmarker']
coeffs['coefficient'] = coeffs['CoefficientTraining']
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 = None
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': 'mccartneysmoking',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13059-018-1514-1',
'notes': 'Linear CpG score; higher values indicate smoking exposure.',
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2018}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg10573386', 'cg13560072', 'cg11084015', 'cg10321266', 'cg07597069', 'cg05218653', 'cg00077898', 'cg11207515', 'cg18392085', 'cg06088918', 'cg20077343', 'cg24169820', 'cg17833862', 'cg23079012', 'cg10696199', 'cg05442408', 'cg08038054', 'cg26775087', 'cg22371743', 'cg04136748', 'cg23288337', 'cg04561727', 'cg09648091', 'cg14142965', 'cg14708990', 'cg01558110', 'cg11704876', 'cg03616722', 'cg24714011', 'cg00231810']... [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: [1.5160139799118042, 1.3958498239517212, 1.2834880352020264, 1.2621612548828125, 0.9191465377807617, 0.8301234841346741, 0.8246065378189087, 0.8208099007606506, 0.7282519936561584, 0.7219155430793762, 0.6905287504196167, 0.6882893443107605, 0.6189409494400024, 0.5594330430030823, 0.49723178148269653, 0.48923414945602417, 0.47508591413497925, 0.4401831328868866, 0.36066848039627075, 0.3536936938762665, 0.3378012776374817, 0.3341846168041229, 0.33264631032943726, 0.318849116563797, 0.31472083926200867, 0.308366596698761, 0.30539241433143616, 0.3030904531478882, 0.302953839302063, 0.28863614797592163]... [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([[ -1.4350],
[ -4.1281],
[-10.1821],
[ -5.1272],
[-11.3244],
[ -3.2461],
[ 8.5989],
[ 3.6743],
[ 6.9403],
[-17.4587]], dtype=torch.float64, grad_fn=<AddmmBackward0>)
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: Smoking.csv