.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/self-supervised-learning/demo_r2r_denoising.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note New to DeepInverse? Get started with the basics with the :ref:`5 minute quickstart tutorial `.. .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_self-supervised-learning_demo_r2r_denoising.py: Self-supervised denoising with the Generalized R2R loss. ==================================================================================================== This example shows you how to train a denoiser network in a fully self-supervised way, using noisy images only via the Generalized Recorrupted2Recorrupted (GR2R) loss :footcite:t:`monroy2025generalized`, which exploits knowledge about the noise distribution. You can change the noise distribution by selecting from predefined noise models such as Gaussian, Poisson, and Gamma noise. .. GENERATED FROM PYTHON SOURCE LINES 10-21 .. code-block:: Python from pathlib import Path import torch from torch.utils.data import DataLoader from torchvision import transforms, datasets import deepinv as dinv from deepinv.utils import get_data_home from deepinv.models.utils import get_weights_url .. GENERATED FROM PYTHON SOURCE LINES 22-25 Setup paths for data loading and results. --------------------------------------------------------------- .. GENERATED FROM PYTHON SOURCE LINES 25-37 .. code-block:: Python BASE_DIR = Path(".") DATA_DIR = BASE_DIR / "measurements" CKPT_DIR = BASE_DIR / "ckpts" ORIGINAL_DATA_DIR = get_data_home() # Set the global random seed from pytorch to ensure reproducibility of the example. torch.manual_seed(0) device = dinv.utils.get_freer_gpu() if torch.cuda.is_available() else "cpu" print(device) .. rst-class:: sphx-glr-script-out .. code-block:: none Selected GPU 0 with 3114.125 MiB free memory cuda:0 .. GENERATED FROM PYTHON SOURCE LINES 38-42 Load base image datasets ---------------------------------------------------------------------------------- In this example, we use the MNIST dataset as the base image dataset. .. GENERATED FROM PYTHON SOURCE LINES 42-55 .. code-block:: Python operation = "denoising" train_dataset_name = "MNIST" transform = transforms.Compose([transforms.ToTensor()]) train_dataset = datasets.MNIST( root=ORIGINAL_DATA_DIR, train=True, transform=transform, download=True ) test_dataset = datasets.MNIST( root=ORIGINAL_DATA_DIR, train=False, transform=transform, download=True ) .. rst-class:: sphx-glr-script-out .. code-block:: none 0%| | 0.00/9.91M [00:000` in the trainer. .. GENERATED FROM PYTHON SOURCE LINES 157-194 .. code-block:: Python verbose = True # print training information train_dataloader = DataLoader( train_dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False ) test_dataloader = DataLoader( test_dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False ) # Initialize the trainer trainer = dinv.Trainer( model=model, physics=physics, epochs=epochs, scheduler=scheduler, losses=loss, optimizer=optimizer, device=device, metrics=None, # no supervised metrics train_dataloader=train_dataloader, eval_dataloader=test_dataloader, early_stop=2, # early stop using the self-supervised loss on the test set compute_eval_losses=True, # use self-supervised loss for evaluation early_stop_on_losses=True, # stop using self-supervised eval loss plot_images=True, save_path=str(CKPT_DIR / operation), verbose=verbose, show_progress_bar=False, # disable progress bar for better vis in sphinx gallery. ) # Train the network model = trainer.train() .. rst-class:: sphx-glr-horizontal * .. image-sg:: /auto_examples/self-supervised-learning/images/sphx_glr_demo_r2r_denoising_001.png :alt: Ground truth, Measurement, Reconstruction :srcset: /auto_examples/self-supervised-learning/images/sphx_glr_demo_r2r_denoising_001.png :class: sphx-glr-multi-img * .. image-sg:: /auto_examples/self-supervised-learning/images/sphx_glr_demo_r2r_denoising_002.png :alt: Ground truth, Measurement, Reconstruction :srcset: /auto_examples/self-supervised-learning/images/sphx_glr_demo_r2r_denoising_002.png :class: sphx-glr-multi-img .. rst-class:: sphx-glr-script-out .. code-block:: none /local/jtachell/deepinv/deepinv/deepinv/training/trainer.py:1337: UserWarning: non_blocking_transfers=True but DataLoader.pin_memory=False; set pin_memory=True to overlap host-device copies with compute. self.setup_train() The model has 444737 trainable parameters Train epoch 0: TotalLoss=0.418 Eval epoch 0: TotalLoss=0.412 Best model saved at epoch 1 .. GENERATED FROM PYTHON SOURCE LINES 195-200 Test the network -------------------------------------------- We now assume that we have access to a small test set of clean images to evaluate the performance of the trained network. and we compute the PSNR between the denoised images and the clean ground truth images. .. GENERATED FROM PYTHON SOURCE LINES 200-202 .. code-block:: Python trainer.test(test_dataloader, metrics=dinv.metric.PSNR()) .. image-sg:: /auto_examples/self-supervised-learning/images/sphx_glr_demo_r2r_denoising_003.png :alt: Ground truth, Measurement, No learning, Reconstruction :srcset: /auto_examples/self-supervised-learning/images/sphx_glr_demo_r2r_denoising_003.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none /local/jtachell/deepinv/deepinv/deepinv/training/trainer.py:1529: UserWarning: non_blocking_transfers=True but DataLoader.pin_memory=False; set pin_memory=True to overlap host-device copies with compute. self.setup_train(train=False) Eval epoch 0: TotalLoss=0.393, PSNR=20.526, PSNR no learning=12.573 Test results: PSNR no learning: 12.573 +- 1.723 PSNR: 20.526 +- 1.702 {'PSNR no learning': 12.572514038085938, 'PSNR no learning_std': 1.7226337202107147, 'PSNR': 20.526483154296876, 'PSNR_std': 1.7016975267704162} .. GENERATED FROM PYTHON SOURCE LINES 203-206 :References: .. footbibliography:: .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 6.932 seconds) .. _sphx_glr_download_auto_examples_self-supervised-learning_demo_r2r_denoising.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: demo_r2r_denoising.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: demo_r2r_denoising.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: demo_r2r_denoising.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_