StocZ#
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.StocZ)
class StocZ(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.StocZ()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'stocz'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2024
model.metadata["approved_by_author"] = '✅'
model.metadata["citation"] = "Tong, Huige, et al. \"Quantifying the stochastic component of epigenetic aging.\" Nature Aging (2024): 1-16."
model.metadata["doi"] = "https://doi.org/10.1038/s43587-024-00600-8"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download directly with curl#
[5]:
supplementary_url = "https://figshare.com/ndownloader/files/42406308"
supplementary_file_name = "glmStocAll.Rd"
os.system(f"curl -L -o {supplementary_file_name} {supplementary_url}")
[5]:
0
Download from R package#
[6]:
%%writefile download.r
options(repos = c(CRAN = "https://cloud.r-project.org/"))
# Function to extract and save coefficients and intercepts
ExtractCoefficients <- function(){
load("glmStocALL.Rd") # Load in stochastic clock information
# Check the loaded object structure
if (!exists("glmStocALL.lo")) {
stop("The object glmStocALL.lo was not found in the loaded .Rd file.")
}
# List to store coefficients and intercepts for each clock
coefficients_list <- list()
for (c in 1:length(glmStocALL.lo)) {
glm.o <- glmStocALL.lo[[c]]
# Ensure glm.o is a glmnet object
if (!inherits(glm.o, "glmnet")) {
warning(paste("Object at index", c, "is not a glmnet object. Skipping."))
next
}
# Extract the coefficients and intercept from the final iteration
intercept <- glm.o$a0[length(glm.o$a0)]
coefficients <- as.matrix(glm.o$beta)[, length(glm.o$lambda)]
print(length(coefficients))
print(length(rownames(coefficients)))
# Create a data frame with feature names and coefficients
coef_df <- data.frame(
Feature = rownames(as.matrix(glm.o$beta)),
Coefficient = as.numeric(coefficients),
Intercept = rep(intercept, length(coefficients))
)
# Save each clock's coefficients to a CSV file
write.csv(coef_df, file = paste0("Coefficients_Clock_", c, ".csv"), row.names = FALSE)
# Append to the list
coefficients_list[[c]] <- coef_df
}
return(coefficients_list) # Return the list for further inspection if needed
}
# Run the function
coefficients_list <- ExtractCoefficients()
Writing download.r
[7]:
os.system("Rscript download.r")
[7]:
0
Load features#
From CSV file#
[8]:
df = pd.read_csv('Coefficients_Clock_2.csv')
df['feature'] = df['Feature']
df['coefficient'] = df['Coefficient']
model.features = df['feature'].tolist()
Load weights into base model#
[9]:
weights = torch.tensor(df['coefficient'].tolist()).unsqueeze(0)
intercept = torch.tensor([df['Intercept'][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 = None
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': 'Tong, Huige, et al. "Quantifying the stochastic component of '
'epigenetic aging." Nature Aging (2024): 1-16.',
'clock_name': 'stocz',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1038/s43587-024-00600-8',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2024}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg24611351', 'cg24173182', 'cg09604333', 'cg13617776', 'cg09432590', 'cg05516505', 'cg12757684', 'cg23606718', 'cg20050761', 'cg22452230', 'cg05898618', 'cg01620164', 'cg06758350', 'cg23615741', 'cg09692396', 'cg02046143', 'cg08540945', 'cg11714320', 'cg22708738', 'cg21567504', 'cg08313880', 'cg03527802', 'cg23995914', 'cg04027548', 'cg07077459', 'cg03025830', 'cg07978099', 'cg24349631', 'cg04218760', 'cg24788483']... [Total elements: 514]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=514, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [-3.350179433822632, -0.036642078310251236, -0.05118434131145477, 0.13607171177864075, -0.6929044127464294, -8.596583366394043, -0.023057660087943077, 22.69631576538086, 0.00651215435937047, -1.4592914581298828, -0.09501103311777115, -0.12129057198762894, -0.08514729142189026, -0.0008293375140056014, 0.4517977833747864, -0.3498646914958954, 15.742756843566895, -0.005218011327087879, -0.37894847989082336, -0.02003936469554901, 0.29712849855422974, -0.18342454731464386, -0.31919535994529724, -2.756777286529541, -2.310011625289917, 0.009594087488949299, 0.0197058767080307, 0.18678680062294006, 0.004259498789906502, -3.520700216293335]... [Tensor of shape torch.Size([1, 514])]
base_model.linear.bias: tensor([64.8077])
%==================================== 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([[ -65.2707],
[-228.6931],
[ 81.9692],
[ 186.4775],
[ -30.6134],
[ 20.5118],
[ 50.0692],
[ 127.1051],
[ 150.1440],
[ -14.1187]], dtype=torch.float64, grad_fn=<AddmmBackward0>)
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: glmStocAll.Rd
Deleted file: download.r
Deleted folder: .ipynb_checkpoints
Deleted file: Coefficients_Clock_3.csv
Deleted file: Coefficients_Clock_2.csv
Deleted file: Coefficients_Clock_1.csv