ProstateCancerKirby#

Index#

  1. Instantiate model class

  2. Define clock metadata

  3. Download clock dependencies

  4. Load features

  5. Load weights into base model

  6. Load reference values

  7. Load preprocess and postprocess objects

  8. Check all clock parameters

  9. Basic test

  10. Save torch model

  11. Clear directory

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.ProstateCancerKirby)
class ProstateCancerKirby(LinearReferenceClock):
    pass

[3]:
model = pya.models.ProstateCancerKirby()

Define clock metadata#

[4]:
model.metadata["clock_name"] = "prostatecancerkirby"
model.metadata["data_type"] = "DNA methylation"  # Paper: The classifier uses methylation beta values at three CpGs.
model.metadata["species"] = "Homo sapiens"  # Paper: Prostate tissues were collected from human patients undergoing radical prostatectomy.
model.metadata["year"] = 2017
model.metadata["approved_by_author"] = "⌛"
model.metadata["citation"] = "Kirby, M. K., et al. “Genome-wide DNA methylation measurements in prostate tissues uncovers novel prostate cancer diagnostic biomarkers and transcription factor binding patterns.” BMC Cancer 17: 273 (2017)."
model.metadata["doi"] = "https://doi.org/10.1186/s12885-017-3252-2"
model.metadata["notes"] = "Three-CpG prostate-tissue diagnostic classifier distinguishing malignant from benign-adjacent tissue; it was trained on 73 tumors and 63 benign-adjacent samples and externally validated in TCGA."
model.metadata["research_only"] = None
model.metadata["tissue"] = ["prostate"]  # Paper: Fresh-frozen prostate cancers and benign-adjacent prostate tissues were profiled.
model.metadata["predicts"] = ["prostate cancer"]  # Paper: The score distinguishes malignant prostate tissue from benign-adjacent tissue.
model.metadata["training_target"] = ["prostate cancer"]  # Paper: Binomial logistic regression was fit to tumor versus benign-adjacent tissue status.
model.metadata["unit"] = ["log odds"]  # Paper: The published classifier is the untransformed binomial-GLM linear predictor 6.52 − 17.04β1 + 24.18β2 − 13.82β3.
model.metadata["model_type"] = "logistic regression"  # Paper: Logistic regression used glm with family=binomial.
model.metadata["platform"] = ["Illumina 450K"]  # Paper: Training tissues were measured with the Illumina HumanMethylation450 BeadChip.
model.metadata["population"] = "adult men"  # Paper: The training cohort had ages 43–73 years and supplied tumor/benign-adjacent prostate tissues.
model.metadata["journal"] = "BMC Cancer"
model.metadata["last_author"] = "Richard M. Myers"
model.metadata["n_features"] = 3
model.metadata["citations"] = 61
model.metadata["citations_date"] = "2026-07-05"

Download clock dependencies#

[5]:
os.system(f"curl -sL -o prostatecancerkirby.xlsx https://static-content.springer.com/esm/art%3A10.1186%2Fs12885-017-3252-2/MediaObjects/12885_2017_3252_MOESM4_ESM.xlsx")
[5]:
0

Load features#

[6]:
raw = pd.read_excel('prostatecancerkirby.xlsx', sheet_name=0, header=None)
hdr_cell = val_cell = None
for i in range(len(raw)):
    for j in range(raw.shape[1]):
        c = str(raw.iloc[i, j])
        if '(Intercept)' in c and 'cg' in c:
            hdr_cell = c
            val_cell = str(raw.iloc[i + 1, j])
            break
    if hdr_cell:
        break
names = hdr_cell.split()
nums = [float(x) for x in val_cell.split()]
intercept_value = 0.0
feats, coefs = [], []
for name, num in zip(names, nums):
    if 'Intercept' in name:
        intercept_value = num
    else:
        feats.append(name)
        coefs.append(num)
model.features = feats
/Users/lucascamillo/pyaging/.venv/lib/python3.13/site-packages/openpyxl/worksheet/_reader.py:329: UserWarning: Unknown extension is not supported and will be removed
  warn(msg)

Load weights into base model#

[7]:
weights = torch.tensor(coefs).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 = 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': 'Kirby, Michael K., et al. "Genome-wide DNA methylation '
             'measurements in prostate tissues uncovers novel prostate cancer '
             'diagnostic biomarkers and predictors of progression." BMC Cancer '
             '17.1 (2017): 273.',
 'clock_name': 'prostatecancerkirby',
 'data_type': 'methylation',
 'doi': 'https://doi.org/10.1186/s12885-017-3252-2',
 'notes': None,
 'research_only': None,
 'species': 'Homo sapiens',
 'version': None,
 'year': 2017}
reference_values: None
preprocess_name: None
preprocess_dependencies: None
postprocess_name: None
postprocess_dependencies: None
features: ['cg00054525', 'cg16794576', 'cg24581650']
base_model_features: None

%==================================== Model Details ====================================%
Model Structure:

base_model: LinearModel(
  (linear): Linear(in_features=3, out_features=1, bias=True)
)

%==================================== Model Details ====================================%
Model Parameters and Weights:

base_model.linear.weight: tensor([[-17.0370,  24.1830, -13.8250]])
base_model.linear.bias: tensor([6.5240])

%==================================== 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([[  3.3665],
        [ 15.9152],
        [ -7.6545],
        [  9.1350],
        [  7.7513],
        [ 24.9928],
        [ -6.7956],
        [ 17.0494],
        [ 17.7305],
        [-18.3624]], 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: prostatecancerkirby.xlsx