Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions docs/api/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ Models

PyHealth models sit between the :doc:`processors` (which turn raw patient data
into tensors) and the :doc:`trainer` (which runs the training loop). Each
model takes a ``SampleDataset`` — the result of ``dataset.set_task()`` — as
dataset-based prediction model takes a ``SampleDataset`` — the result of ``dataset.set_task()`` — as
its first constructor argument, and uses it to automatically build the right
embedding layers and output head for your task.

Expand Down Expand Up @@ -64,10 +64,13 @@ routes each feature type automatically.
- You predict ICD codes from clinical notes (e.g. ``MIMIC3ICD9Coding``) and many codes are rare
- MultiResCNN with label attention, trained level by level down the ICD tree; call ``set_level`` between training stages

For unsupervised code embedding pretraining, see :doc:`models/pyhealth.models.KEEP`.
KEEP accepts sparse co-occurrence triplets rather than a ``SampleDataset``.

How BaseModel Works
--------------------

All PyHealth models inherit from ``BaseModel``, which itself inherits from
PyHealth dataset-based prediction models inherit from ``BaseModel``, which itself inherits from
PyTorch's ``nn.Module``. When you call ``MyModel(dataset=sample_ds)``, the
base class reads the dataset's schemas and automatically sets:

Expand Down Expand Up @@ -316,6 +319,7 @@ API Reference
models/pyhealth.models.RETAIN
models/pyhealth.models.GAMENet
models/pyhealth.models.GraphCare
models/pyhealth.models.KEEP
models/pyhealth.models.MICRON
models/pyhealth.models.SafeDrug
models/pyhealth.models.SHy
Expand Down
484 changes: 484 additions & 0 deletions docs/api/models/pyhealth.models.KEEP.rst

Large diffs are not rendered by default.

40 changes: 40 additions & 0 deletions examples/keep_export_vectors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from pathlib import Path
import argparse
import numpy as np

parser = argparse.ArgumentParser()

parser.add_argument(
"--output-dir", "--dir",
type=Path,
default=None
)

parser.add_argument(
"--methods",
nargs="+",
choices=["glove", "initialized_glove", "keep"],
default=["glove", "initialized_glove", "keep"]
)

parser.add_argument("--root", type=Path, default=Path("outputs/keep"))
args = parser.parse_args()

root = args.root
output_dir = args.output_dir if args.output_dir is not None else root / "reproduction"

vocab = np.load(root / "vocabulary_train.npy", allow_pickle=False)

for method in args.methods:
embeddings = np.load(output_dir / f"{method}_embeddings.npy")

assert embeddings.shape == (len(vocab), 100), method
assert np.isfinite(embeddings).all(), method

path = output_dir / f"{method}_vectors.txt"

with path.open("w", encoding="utf-8") as f:
for code, vector in zip(vocab, embeddings):
f.write(f"10_{code} " + " ".join(map(str, vector)) + "\n")

print(f"Exported {len(vocab):,} vectors to {path}")
48 changes: 48 additions & 0 deletions examples/keep_intrinsic_eval.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import argparse
import json
from pathlib import Path
import numpy as np
import networkx as nx
from scipy.sparse import load_npz
from scipy.stats import spearmanr

parser = argparse.ArgumentParser(description="Evaluate KEEP embedding correlations")
parser.add_argument("--root", type=Path, default=Path("outputs/keep"))
parser.add_argument("--output-dir", type=Path, default=None)
args = parser.parse_args()
root = args.root
vocab = np.load(root / "vocabulary_train.npy", allow_pickle=False)
M = load_npz(root / "cooccurrence_train.npz").tocsr()
with (root / "icd10_subgraph_train.json").open(encoding="utf-8") as f:
data = json.load(f)
G = nx.Graph()
G.add_nodes_from(data["nodes"])
G.add_edges_from(data["edges"])
rng = np.random.default_rng(0)

def dotted(c):
return c[:3] + "." + c[3:] if len(c) > 3 else c

def cos(E, i, j):
a, b = E[i], E[j]
return a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + 1e-12)

def evaluate(path, n_pairs=20000):
E = np.load(path)
onto_d, onto_s, co_c, co_s = [], [], [], []
for _ in range(n_pairs):
i, j = rng.integers(0, len(vocab), 2)
if i == j:
continue
a, b = dotted(vocab[i]), dotted(vocab[j])
if a in G and b in G and nx.has_path(G, a, b):
onto_d.append(nx.shortest_path_length(G, a, b))
onto_s.append(cos(E, i, j))
co_c.append(np.log1p(M[i, j]))
co_s.append(cos(E, i, j))
return (-spearmanr(onto_d, onto_s).correlation,
spearmanr(co_c, co_s).correlation)

for name in ["glove", "initialized_glove", "keep"]:
o, c = evaluate((args.output_dir or root / "reproduction") / f"{name}_embeddings.npy")
print(f"{name:18s} ontology corr={o:.3f} cooccurrence corr={c:.3f}")
179 changes: 179 additions & 0 deletions examples/keep_mimic_preprocessing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@

from pathlib import Path
from collections import Counter
from itertools import combinations
import pandas as pd
from scipy.sparse import coo_matrix
import json
import argparse
import numpy as np
from scipy.sparse import save_npz


def load_diagnoses(mimic_root, root):
path = Path(mimic_root) / "hosp" / "diagnoses_icd.csv.gz"

df = pd.read_csv(
path,
usecols=[
"subject_id",
"hadm_id",
"icd_code",
"icd_version",
],
dtype={"icd_code": str},
)

train_patient_ids = set(
pd.read_csv(
Path(root) / "train_patient_ids.txt",
header=None,
dtype=str,
)[0]
)

df['subject_id'] = df["subject_id"].astype(str)
df = df[df["subject_id"].isin(train_patient_ids)].copy()

print(f"Training diagnosis rows: {len(df):,}")
print(f"Training patients with diagnoses: {df['subject_id'].nunique():,}")

df = df[df["icd_version"] == 10].copy()

# MIMIC stores ICD-10 codes without decimal points.
df["icd_code"] = (
df["icd_code"]
.str.strip()
.str.upper()
.str.replace(".", "", regex=False)
)

print(f"ICD-10 diagnosis rows: {len(df):,}")
print(f"Unique patients: {df.subject_id.nunique():,}")
print(f"Unique codes: {df.icd_code.nunique():,}")

return df


def build_patient_codes(df, min_occurrences=2):
"""
Build patient-level code sets.

A code must appear in at least two distinct admissions
for the same patient.
"""
counts = (
df.groupby(["subject_id", "icd_code"])["hadm_id"]
.nunique()
.reset_index(name="count")
)

counts = counts[counts["count"] >= min_occurrences]

patient_codes = (
counts.groupby("subject_id")["icd_code"]
.agg(lambda x: sorted(set(x)))
)

return patient_codes


def build_cooccurrence(patient_codes):
"""
Build a sparse, symmetric co-occurrence matrix.
"""
vocabulary = sorted(
set(
code
for codes in patient_codes
for code in codes
)
)

code_to_idx = {
code: i for i, code in enumerate(vocabulary)
}

pair_counts = Counter()

for codes in patient_codes:
indices = sorted({
code_to_idx[code] for code in codes
})

for i, j in combinations(indices, 2):
pair_counts[(i, j)] += 1

rows, cols, values = [], [], []

for (i, j), count in pair_counts.items():
rows.extend([i, j])
cols.extend([j, i])
values.extend([count, count])

n = len(vocabulary)

matrix = coo_matrix(
(values, (rows, cols)),
shape=(n, n),
dtype="float32",
).tocsr()

return matrix, vocabulary


def main():
parser = argparse.ArgumentParser(description="Build KEEP training co-occurrences and ontology graph")
parser.add_argument("--mimic-root", type=Path, required=True)
parser.add_argument("--root", type=Path, default=Path("outputs/keep"))
args = parser.parse_args()
from pyhealth.medcode import InnerMap

diagnoses = load_diagnoses(args.mimic_root, args.root)

patient_codes = build_patient_codes(
diagnoses,
min_occurrences=2,
)


matrix, vocabulary = build_cooccurrence(
patient_codes
)


icd = InnerMap.load("ICD10CM")

ontology_codes = {
code.replace(".", ""): code
for code in icd.graph.nodes
}

matched = [c for c in vocabulary if c in ontology_codes]
unmatched = [c for c in vocabulary if c not in ontology_codes]


# Keep matched ICD-10-CM codes and all their ancestors.
relevant_nodes = set()

for code in matched:
ontology_code = ontology_codes[code]
relevant_nodes.add(ontology_code)
relevant_nodes.update(icd.get_ancestors(ontology_code))

subgraph = icd.graph.subgraph(relevant_nodes).copy()
output = args.root
output.mkdir(parents=True, exist_ok=True)

# Explicit node and edge lists preserve isolated nodes without pickle.
graph = subgraph.to_undirected()
with (output / "icd10_subgraph_train.json").open("w", encoding="utf-8") as f:
json.dump({"nodes": list(graph.nodes), "edges": list(graph.edges)}, f)



save_npz(output / "cooccurrence_train.npz", matrix)
np.save(output / "vocabulary_train.npy", vocabulary)

if __name__ == "__main__":
main()
32 changes: 32 additions & 0 deletions examples/keep_prepare_embeddings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
"""Align ontology vectors; zero rows mark missing references for KEEP."""
import argparse
from pathlib import Path
import numpy as np


def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", type=Path, default=Path("outputs/keep"))
args = parser.parse_args()
try:
from gensim.models import KeyedVectors
except ImportError as exc:
raise ImportError("Install the optional Gensim dependency: pip install gensim") from exc
vocab = np.load(args.root / "vocabulary_train.npy", allow_pickle=False)
node2vec = KeyedVectors.load_word2vec_format(str(args.root / "node2vec_embeddings2.txt"))
# KEEP randomizes these sentinel rows and excludes them from anchoring.
embeddings = np.zeros((len(vocab), node2vec.vector_size), dtype=np.float32)
matched = 0
for i, code in enumerate(vocab):
icd_code = code[:3] + "." + code[3:] if len(code) > 3 else code
if icd_code in node2vec and np.any(node2vec[icd_code]):
embeddings[i] = node2vec[icd_code]
matched += 1
np.save(args.root / "node2vec_initial2.npy", embeddings)
print("Shape:", embeddings.shape)
print("Matched:", matched)
print("Unmatched:", len(vocab) - matched)


if __name__ == "__main__":
main()
Loading
Loading