Thompson#
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.Thompson)
class Thompson(pyagingModel):
def __init__(self):
super().__init__()
def preprocess(self, x):
return x
def postprocess(self, x):
return x
[3]:
model = pya.models.Thompson()
Define clock metadata#
[4]:
model.metadata["clock_name"] = 'thompson'
model.metadata["data_type"] = 'methylation'
model.metadata["species"] = 'Mus musculus'
model.metadata["year"] = 2018
model.metadata["approved_by_author"] = '✅'
model.metadata["citation"] = "Thompson, Michael J., et al. \"A multi-tissue full lifespan epigenetic clock for mice.\" Aging (Albany NY) 10.10 (2018): 2832."
model.metadata["doi"] = "https://doi.org/10.18632/aging.101590"
model.metadata["research_only"] = None
model.metadata["notes"] = None
Download clock dependencies#
Download GitHub repository#
[5]:
github_url = "https://github.com/kerepesi/MouseAgingClocks.git"
github_folder_name = github_url.split('/')[-1].split('.')[0]
os.system(f"git clone {github_url}")
[5]:
0
Load features#
From CSV file#
[6]:
df = pd.read_table('MouseAgingClocks/ClockData/Thompson2018-ElasticNet_aging_clock.txt', skiprows=1)
intercept = df['Coefficient'].iloc[0]
df = df[1:]
df['feature'] = df['Chromosome'].astype(str) + ':' + df['Coordinate'].astype(int).astype(str)
df['coefficient'] = df['Coefficient']
model.features = df['feature'].tolist()
Load weights into base model#
[7]:
weights = torch.tensor(df['coefficient'].tolist()).unsqueeze(0)
intercept = torch.tensor([intercept])
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': 'Thompson, Michael J., et al. "A multi-tissue full lifespan '
'epigenetic clock for mice." Aging (Albany NY) 10.10 (2018): '
'2832.',
'clock_name': 'thompson',
'data_type': 'methylation',
'doi': 'https://doi.org/10.18632/aging.101590',
'notes': None,
'research_only': None,
'species': 'Mus musculus',
'version': None,
'year': 2018}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['chr1:9967422', 'chr1:9967428', 'chr1:13126576', 'chr1:15286937', 'chr1:46800385', 'chr1:55087536', 'chr1:63273286', 'chr1:63273288', 'chr1:64690282', 'chr1:71603645', 'chr1:79761546', 'chr1:79858375', 'chr1:84695279', 'chr1:84934769', 'chr1:89455649', 'chr1:92848744', 'chr1:92848748', 'chr1:95666316', 'chr1:103479589', 'chr1:105270925', 'chr1:106758726', 'chr1:118310888', 'chr1:118311288', 'chr1:119648512', 'chr1:120602265', 'chr1:120602331', 'chr1:128359556', 'chr1:132331689', 'chr1:132937328', 'chr1:135374481']... [Total elements: 582]
base_model_features: None
%==================================== Model Details ====================================%
Model Structure:
base_model: LinearModel(
(linear): Linear(in_features=582, out_features=1, bias=True)
)
%==================================== Model Details ====================================%
Model Parameters and Weights:
base_model.linear.weight: [0.7605000138282776, 0.12610000371932983, 4.3765997886657715, 5.6855998039245605, -0.5194000005722046, -0.6355000138282776, 0.41659998893737793, 1.2926000356674194, 5.576700210571289, -0.9544000029563904, -5.0493998527526855, -0.2711000144481659, 0.24879999458789825, -0.8901000022888184, 0.7444000244140625, 0.03920000046491623, 0.40560001134872437, -2.0560998916625977, 0.5519000291824341, -0.663100004196167, -0.8413000106811523, -3.921999931335449, -3.1031999588012695, -1.9629000425338745, 2.824700117111206, -0.3255000114440918, 1.7187999486923218, -1.5643999576568604, -0.7063000202178955, -2.196000099182129]... [Tensor of shape torch.Size([1, 582])]
base_model.linear.bias: tensor([30.3172])
%==================================== 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([[102.1936],
[ 83.5008],
[ 61.2582],
[-60.8014],
[-27.0123],
[ 77.8211],
[ 51.7655],
[ 57.8975],
[167.7028],
[ 52.8332]], 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 folder: MouseAgingClocks