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
4 changes: 3 additions & 1 deletion docs/api/models/pyhealth.models.VAE.rst
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
pyhealth.models.VAE
===================================

The VAE model (treated as a regression task).
A convolutional variational autoencoder for image generation. It reads the image
shape from the dataset's ``ImageProcessor``, trains with the standard ``Trainer``,
and reports reconstruction error as regression metrics such as ``mse`` and ``mae``.

.. autoclass:: pyhealth.models.VAE
:members:
Expand Down
1 change: 1 addition & 0 deletions docs/api/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@ Available Tasks
MIMIC-III ICD-9 Coding <tasks/pyhealth.tasks.MIMIC3ICD9Coding>
Cardiology Detection <tasks/pyhealth.tasks.cardiology_detect>
COVID-19 CXR Classification <tasks/pyhealth.tasks.COVID19CXRClassification>
COVID-19 CXR Image Generation <tasks/pyhealth.tasks.COVID19CXRImageGeneration>
DKA Prediction (MIMIC-IV) <tasks/pyhealth.tasks.dka>
Drug Recommendation <tasks/pyhealth.tasks.drug_recommendation>
EHR Generation <tasks/pyhealth.tasks.generate_ehr>
Expand Down
7 changes: 7 additions & 0 deletions docs/api/tasks/pyhealth.tasks.COVID19CXRImageGeneration.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
pyhealth.tasks.COVID19CXRImageGeneration
========================================

.. autoclass:: pyhealth.tasks.covid19_cxr_generation.COVID19CXRImageGeneration
:members:
:undoc-members:
:show-inheritance:
152 changes: 59 additions & 93 deletions examples/cxr/chextXray_image_generation_VAE.py
Original file line number Diff line number Diff line change
@@ -1,100 +1,66 @@
from pyhealth.datasets import split_by_visit, get_dataloader
from pyhealth.trainer import Trainer
from pyhealth.datasets import COVID19CXRDataset
from pyhealth.models import VAE
from torchvision import transforms

import torch
import numpy as np

# step 1: load signal data
root = "/srv/local/data/COVID-19_Radiography_Dataset"
base_dataset = COVID19CXRDataset(root)

# step 2: set task
sample_dataset = base_dataset.set_task()

# the transformation automatically normalize the pixel intensity into [0, 1]
transform = transforms.Compose([
transforms.Lambda(lambda x: x if x.shape[0] == 3 else x.repeat(3, 1, 1)), # only use the first channel
transforms.Resize((128, 128)),
])

def encode(sample):
sample["path"] = transform(sample["path"])
return sample

sample_dataset.set_transform(encode)


# split dataset
train_dataset, val_dataset, test_dataset = split_by_visit(
sample_dataset, [0.6, 0.2, 0.2]
)
train_dataloader = get_dataloader(train_dataset, batch_size=256, shuffle=True)
val_dataloader = get_dataloader(val_dataset, batch_size=256, shuffle=False)
test_dataloader = get_dataloader(test_dataset, batch_size=256, shuffle=False)

data = next(iter(train_dataloader))
print (data)

print (data["path"][0].shape)

print(
"loader size: train/val/test",
len(train_dataset),
len(val_dataset),
len(test_dataset),
)

# STEP 3: define model
model = VAE(
dataset=sample_dataset,
input_channel=3,
input_size=128,
feature_keys=["path"],
label_key="path",
mode="regression",
hidden_dim = 128,
)

# STEP 4: define trainer
trainer = Trainer(model=model, device="cuda:4", metrics=["kl_divergence", "mse", "mae"])
trainer.train(
train_dataloader=train_dataloader,
val_dataloader=val_dataloader,
epochs=10,
monitor="kl_divergence",
monitor_criterion="min",
optimizer_params={"lr": 1e-3},
)

# # STEP 5: evaluate
# print(trainer.evaluate(test_dataloader))
"""Train a VAE on chest X-rays and generate new ones.

Uses the COVID-19 Radiography Database. Set ``root`` to the folder that holds
its four class folders and their metadata spreadsheets.
"""

import matplotlib.pyplot as plt

# EXP 1: check the real chestxray image and the reconstructed image
X, X_rec, _ = trainer.inference(test_dataloader)
from pyhealth.datasets import COVID19CXRDataset, get_dataloader, split_by_sample
from pyhealth.models import VAE
from pyhealth.tasks import COVID19CXRImageGeneration
from pyhealth.trainer import Trainer

plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(X[0].reshape(128, 128), cmap="gray")
plt.subplot(1, 2, 2)
plt.imshow(X_rec[0].reshape(128, 128), cmap="gray")
plt.savefig("chestxray_vae_comparison.png")

# EXP 2: random images
model = trainer.model

model.eval()
with torch.no_grad():
x = np.random.normal(0, 1, 128)
x = x.astype(np.float32)
x = torch.from_numpy(x).to(trainer.device)
rec = model.decoder(x).detach().cpu().numpy()
rec = rec.reshape((128, 128))
def main(root: str = "/srv/local/data/COVID-19_Radiography_Dataset") -> None:
# step 1: load the dataset
base_dataset = COVID19CXRDataset(root)

# step 2: one grayscale 128 x 128 image per sample, with no label
sample_dataset = base_dataset.set_task(COVID19CXRImageGeneration())
train_dataset, val_dataset, test_dataset = split_by_sample(
sample_dataset, [0.8, 0.1, 0.1], seed=0
)
train_dataloader = get_dataloader(train_dataset, batch_size=64, shuffle=True)
val_dataloader = get_dataloader(val_dataset, batch_size=64, shuffle=False)
test_dataloader = get_dataloader(test_dataset, batch_size=64, shuffle=False)

# step 3: the model reads the image shape from the task
model = VAE(dataset=sample_dataset, hidden_dim=128)

# step 4: train, keeping the epoch with the lowest validation reconstruction
# error
trainer = Trainer(model=model, metrics=["mse", "mae"])
trainer.train(
train_dataloader=train_dataloader,
val_dataloader=val_dataloader,
epochs=10,
monitor="mse",
monitor_criterion="min",
optimizer_params={"lr": 1e-3},
)
print(trainer.evaluate(test_dataloader))

# step 5: a real X-ray next to its reconstruction
y_true, y_prob, _ = trainer.inference(test_dataloader)
plt.figure()
plt.subplot(1, 2, 1)
plt.imshow(y_true[0, 0], cmap="gray")
plt.title("real")
plt.subplot(1, 2, 2)
plt.imshow(y_prob[0, 0], cmap="gray")
plt.title("reconstructed")
plt.savefig("chestxray_vae_comparison.png")

# step 6: new X-rays decoded from random points of the latent space
images = model.generate(num_samples=4).cpu()
plt.figure()
plt.imshow(rec, cmap="gray")
plt.savefig("chestxray_vae_synthetic.png")
for i, image in enumerate(images):
plt.subplot(1, 4, i + 1)
plt.imshow(image[0], cmap="gray")
plt.axis("off")
plt.savefig("chestxray_vae_synthetic.png")


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