VOOZH about

URL: https://www.geeksforgeeks.org/machine-learning/implement-convolutional-autoencoder-in-pytorch-with-cuda/

⇱ Implement Convolutional Autoencoder in PyTorch with CUDA - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implement Convolutional Autoencoder in PyTorch with CUDA

Last Updated : 5 Aug, 2025

A Convolutional Autoencoder (CAE) is a type of neural network that learns to compress and reconstruct images using convolutional layers. It consists of an encoder that reduces the image to a compact feature representation and a decoder that restores the image from this compressed form. CAEs are widely used for image denoising, compression and feature extraction due to their ability to preserve key visual patterns while reducing dimensionality.

Let's see the step-by-step implementation of a Convolutional Autoencoder (CAE) using PyTorch with CUDA/GPU support.

Step 1: Import Required Libraries

Import pytorch and matplotlib.

Step 2: Define the Convolutional Autoencoder Architecture

  • Encoder downsamples and learns spatial features.
  • Decoder upsamples (reconstructs) to the original image shape.
  • Sigmoid() ensures the output pixel values are between 0 and 1.

Step 3: Data Preparation: Transformers and Dataloader

  • Images are resized and converted to tensors.
  • DataLoader batches data and shuffles during training.

Step 4: Set Device to Cuda(GPU)

Uses GPU acceleration if available, speeding up training.

Step 5: Initialize Model, Loss Function and Optimizer

  • Model and optimizer are set up.
  • MSELoss computes pixel-wise reconstruction error.

Step 6: Training Loop

  • For each batch: moves images to device, computes forward pass and loss, updates weights.
  • Tracks loss for monitoring; prints progress every 5 epochs.

Output:

👁 training
Training

Step 7: Save the Model and Visualize

Output:

👁 Result
Output

Here we can see that our Convolutional Autoencoder model is working fine.

You cann download source code from here.

Comment