CVDWesterman#
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.CVDWesterman)
class CVDWesterman(LinearReferenceClock):
def postprocess(self, x):
"""Logistic transform to a CVD risk probability."""
return torch.sigmoid(x)
[3]:
model = pya.models.CVDWesterman()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'cvdwesterman'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Homo sapiens'
model.metadata["year"] = 2020
model.metadata["approved_by_author"] = '⌛'
model.metadata["citation"] = "Westerman, Kenneth, et al. \"Epigenomic assessment of cardiovascular disease risk and interactions with traditional risk metrics.\" Journal of the American Heart Association 9.8 (2020): e015299."
model.metadata["doi"] = "https://doi.org/10.1161/JAHA.119.015299"
model.metadata["research_only"] = None
model.metadata["notes"] = "Blood DNA-methylation risk score for incident cardiovascular disease, trained as a cross-study ensemble of Cox proportional-hazards elastic-net models across multiple cohorts to predict CVD events independent of traditional risk factors."
model.metadata["tissue"] = 'whole blood'
model.metadata["predicts"] = 'incident cardiovascular disease (CVD) risk / time-to-event'
model.metadata["unit"] = 'score (arbitrary)'
model.metadata["model_type"] = 'Cox regression'
model.metadata["platform"] = 'Illumina 450K'
model.metadata["population"] = 'adults (middle-aged/older; WHI, Framingham Offspring, Lothian Birth Cohorts)'
model.metadata["journal"] = 'Journal of the American Heart Association'
model.metadata["last_author"] = 'José M. Ordovás'
model.metadata["n_features"] = 235
model.metadata["citations"] = 53
model.metadata["citations_date"] = '2026-07-05'
Download clock dependencies#
[5]:
os.system(f"curl -sL -o coefficients.csv https://raw.githubusercontent.com/bio-learn/biolearn/180852e2bab473303cb85da627178b1695ee9d86/biolearn/data/CVD_Westermann.csv")
[5]:
0
Load features#
[6]:
df = pd.read_csv('coefficients.csv')
mask = df['CpGmarker'].astype(str).str.lower().isin(['intercept', '(intercept)'])
intercept_value = float(df.loc[mask, 'CoefficientTraining'].iloc[0]) if mask.any() else 0.0
coef_df = df.loc[~mask].reset_index(drop=True)
model.features = coef_df['CpGmarker'].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(coef_df['CoefficientTraining'].tolist()).unsqueeze(0).float()
intercept = torch.tensor([intercept_value]).float()
[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': 'Westerman, Kenneth, et al. "Epigenomic assessment of '
'cardiovascular disease risk and interactions with traditional '
'risk metrics." Journal of the American Heart Association 9.8 '
'(2020): e015299.',
'clock_name': 'cvdwesterman',
'data_type': 'methylation',
'doi': 'https://doi.org/10.1161/JAHA.119.015299',
'notes': None,
'research_only': None,
'species': 'Homo sapiens',
'version': None,
'year': 2020}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: 'sigmoid'
postprocess_dependencies: None
features: ['cg13077366', 'cg13679303', 'cg19214707', 'cg18593317', 'cg03463778', 'cg26626449', 'cg05630272', 'cg23522872', 'cg12588880', 'cg13074055', 'cg02655711', 'cg12624197', 'cg05843457', 'cg10963061', 'cg12121643', 'cg23613051', 'cg26504835', 'cg23063825', 'cg25188006', 'cg00887153', 'cg16574737', 'cg25283121', 'cg23239574', 'cg25564433', 'cg10612096', 'cg13903421', 'cg16268165', 'cg00600477', 'cg10516993', 'cg03930209']... [Total elements: 235]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=235, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.0023171070497483015, 0.0011196619598194957, -0.013891435228288174, -0.002025559078902006, -0.009562727063894272, 0.06509598344564438, -0.020258523523807526, 0.0033463360741734505, -0.007966549135744572, -0.010243932716548443, -0.01568872109055519, 0.028809623792767525, 0.002753776963800192, 0.019885685294866562, 0.047365110367536545, 0.037816889584064484, 0.0031414860859513283, -0.004254682920873165, 0.002840817905962467, 0.002047969028353691, 0.0016441689804196358, 0.010059863328933716, 0.013813807629048824, 0.002602970926091075, 0.0023500178940594196, 0.004787160083651543, -0.006558055058121681, 0.01796160265803337, 0.016836676746606827, 0.0022038749884814024]... [Tensor of shape torch.Size([1, 235])]
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([[0.3971],
[0.6197],
[0.7023],
[0.5075],
[0.5564],
[0.5077],
[0.5431],
[0.4493],
[0.6137],
[0.3952]], 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: coefficients.csv