McCartneyEducation#
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.McCartneyEducation)
class McCartneyEducation(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return torch.sigmoid(x)
[3]:
model = pya.models.McCartneyEducation()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'mccartneyeducation'
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 educational attainment; logistic transform."
Download clock dependencies#
Download coefficient file#
[5]:
coeff_url = "https://raw.githubusercontent.com/bio-learn/biolearn/master/biolearn/data/EducationMcCartney.csv"
os.system(f"curl -L {coeff_url} -o EducationMcCartney.csv")
[5]:
0
Load features#
From CSV file#
[6]:
coeffs = pd.read_csv('EducationMcCartney.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': 'mccartneyeducation',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1186/s13059-018-1514-1',
'notes': 'DNAm score for educational attainment; 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: ['cg06807993', 'cg13244241', 'cg12047012', 'cg11902777', 'cg07063853', 'cg13213923', 'cg10953131', 'cg09991298', 'cg17519650', 'cg22750243', 'cg07384165', 'cg23475278', 'cg16699331', 'cg21871465', 'cg16697775', 'cg26960896', 'cg05124614', 'cg01145653', 'cg13808420', 'cg01962969', 'cg00871215', 'cg09969830', 'cg05575921', 'cg21566642', 'cg01904410', 'cg23244761', 'cg11977139', 'cg09188212', 'cg00459953', 'cg13042926']... [Total elements: 373]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=373, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [3.125317096710205, 2.300844192504883, 1.972651720046997, 1.720637321472168, 1.6760412454605103, 1.6369305849075317, 1.3301490545272827, 1.2093710899353027, 1.190836787223816, 1.1478432416915894, 1.073359727859497, 0.9826802015304565, 0.961870014667511, 0.8983024954795837, 0.8883466720581055, 0.8363032341003418, 0.8301376104354858, 0.8120859861373901, 0.7989017963409424, 0.7501415014266968, 0.7479488849639893, 0.735051155090332, 0.6983904242515564, 0.6171315312385559, 0.6136239767074585, 0.5947673916816711, 0.49705418944358826, 0.4550599753856659, 0.45332401990890503, 0.4409250319004059]... [Tensor of shape torch.Size([1, 373])]
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.7208e-01],
[1.0000e+00],
[2.9588e-02],
[5.0295e-01],
[9.9997e-01],
[9.8214e-01],
[1.0123e-02],
[5.1157e-09],
[9.7709e-01],
[1.6943e-03]], 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: EducationMcCartney.csv