A complete implementation of a Quantum Convolutional Neural Network (QCNN) for binary dermoscopy image classification, comparing quantum vs classical deep learning on the DermaMNIST dataset.
An 8-qubit Quantum Convolutional Neural Network (QCNN) implementation for binary skin lesion classification on the DermaMNIST dataset, distinguishing Actinic Keratoses and Intraepithelial Carcinoma (AKIEC) from Basal Cell Carcinoma (BCC).
Implemented using PennyLane on a noiseless statevector simulator, with a compact PyTorch autoencoder for dimensionality reduction and Angle-compact quantum data embedding.
๐ Companion repository (Classical CNN Baseline): [Link to your CNN repo]
| Property | Details |
|---|---|
| Task | Binary classification โ AKIEC (Class 0) vs BCC (Class 1) |
| Dataset | DermaMNIST (MedMNIST v2) |
| Image size | 28ร28 pixels, grayscale โ compressed to 16-dim latent vector |
| Framework | PennyLane + PyTorch |
| Quantum device | default.qubit (noiseless statevector simulator) |
| Number of qubits | 8 |
| Total parameters | 51 |
| Test accuracy | ~60% |
| Training steps | 200 |
| Batch size | 16 |
| Platform | Google Colab (CPU runtime) |
DermaMNIST is part of the MedMNIST v2 benchmark collection, derived from the HAM10000 dermoscopy dataset (Tschandl et al., 2018). Images are 28ร28 pixels in RGB format, standardised across 7 lesion categories.
This project uses a binary subset of two classes:
| Label | Class | Description |
|---|---|---|
| 0 | AKIEC | Actinic Keratoses & Intraepithelial Carcinoma โ precancerous lesion |
| 1 | BCC | Basal Cell Carcinoma โ most common skin cancer |
Class imbalance is handled through hard structural balancing โ equal counts per class via random subsampling before training.
Raw DermaMNIST image (28ร28 grayscale) โ โผ Normalise to [โ1, 1] using transforms.Normalize(mean=0.5, std=0.5) โ โผ Filter for AKIEC (0) and BCC (1) only โ โผ Hard class balancing โ equal AKIEC and BCC counts โ โผ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ Autoencoder Compression (PyTorch) โ โ Flatten โ Linear(784โ16) โ ReLU โ โ 784 dimensions โ 16 dimensions โ โ Trained: 10 epochs, MSE loss, Adam โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โผ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ Angle-Compact Quantum Embedding โ โ AngleEmbedding(x[0:8], rot='X') โ โ AngleEmbedding(x[8:16], rot='Y') โ โ 2 values per qubit ร 8 qubits = 16 โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โผ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ QCNN Circuit (8 qubits, PennyLane) โ โ Conv Layer 1 โ Pool Layer 1 (8โ4) โ โ Conv Layer 2 โ Pool Layer 2 (4โ2) โ โ Conv Layer 3 โ Pool Layer 3 (2โ1) โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โผ qml.probs(wires=4) โ [P(AKIEC), P(BCC)]
Each convolutional layer applies the U_SU4 unitary โ the most expressive possible two-qubit gate, spanning the full SU(4) group with 15 trainable parameters per layer. Gate sequence:
U3 โ U3 โ CNOT โ RY, RZ โ reverse CNOT โ RY โ CNOT โ U3 โ U3
This implements the Cartan KAK decomposition of SU(4), requiring the minimum of 3 CNOT gates for a general two-qubit unitary.
Each pooling layer uses 2 trainable parameters:
CRZ(params[0]) โ PauliX โ CRX(params[1])
Transfers quantum information from the discarded qubit to the retained qubit before removal.
| Stage | Active Qubits | Count |
|---|---|---|
| After embedding | 0, 1, 2, 3, 4, 5, 6, 7 | 8 |
| After Pool Layer 1 | 0, 2, 4, 6 | 4 |
| After Pool Layer 2 | 0, 4 | 2 |
| After Pool Layer 3 | 4 | 1 |
| Measurement | qml.probs(wires=4) | โ |
| Component | Layers | Parameters |
|---|---|---|
| Conv Layer 1 | U_SU4 ร 12 pairs (shared) | 15 |
| Conv Layer 2 | U_SU4 ร 4 pairs (shared) | 15 |
| Conv Layer 3 | U_SU4 ร 1 pair | 15 |
| Pool Layer 1 | Pooling_ansatz1 ร 4 (shared) | 2 |
| Pool Layer 2 | Pooling_ansatz1 ร 2 (shared) | 2 |
| Pool Layer 3 | Pooling_ansatz1 ร 1 | 2 |
| Total | 51 |
A compact self-supervised PyTorch autoencoder compresses each 784-dimensional image to a 16-dimensional latent vector.
Encoder: nn.Flatten() โ nn.Linear(784, 16) โ nn.ReLU() Decoder: nn.Linear(16, 784) โ nn.Sigmoid() [training only]
| Property | Value |
|---|---|
| Input dimension | 784 (28ร28 flattened) |
| Latent dimension | 16 |
| Compression ratio | 49ร |
| Loss function | MSE reconstruction loss |
| Training epochs | 10 |
| Batch size | 32 |
| Optimiser | Adam (lr=1e-3) |
| Encoder parameters | 12,560 |
| Decoder parameters | 13,328 |
| Total parameters | 25,888 |
The decoder is discarded after training. Only the encoder is used for quantum encoding.
The 16-dimensional autoencoder output is loaded into the 8-qubit register using two successive AngleEmbedding layers:
AngleEmbedding(X[:8], wires=range(8), rotation='X') # RX on qubits 0โ7
AngleEmbedding(X[8:16], wires=range(8), rotation='Y') # RY on qubits 0โ7State of qubit i after embedding:
|ฯแตขโฉ = RY(X[i+8]) ยท RX(X[i]) ยท |0โฉ
| Strategy | Values encoded | Qubits | Values/qubit |
|---|---|---|---|
| Standard Angle | 8 | 8 | 1 |
| Angle-compact (used) | 16 | 8 | 2 |
| Amplitude | 256 | 8 | 32 |
| Parameter | Value |
|---|---|
| Optimiser | PennyLane AdamOptimizer |
| Learning rate | 0.0005 |
| Training steps | 200 |
| Batch size | 16 |
| Loss function | Cross-entropy |
| Gradient method | Parameter-shift rule |
| Initialisation | 0.01 ร N(0,1) โ near-zero (barren plateau avoidance) |
| Circuit evaluations/step | 51 ร 2 ร 16 = 1,632 |
Exact analytic gradients computed without finite-difference approximation:
โโจOโฉ/โฮธ = ยฝ [โจOโฉ{ฮธ+ฯ/2} โ โจOโฉ{ฮธโฯ/2}]
Requires 2 circuit evaluations per parameter per sample.
All 51 parameters initialised as 0.01 * np.random.randn(51) โ
near-zero Gaussian initialisation keeps the circuit close to the identity
transformation where gradients are non-negligible.
| Metric | Value |
|---|---|
| Test Accuracy | ~60% |
| Chance baseline | 50% |
| Above chance | +10 percentage points |
| CNN baseline accuracy | ~55% |
| Improvement over CNN | +5 pp (~9.1% relative improvement) |
| Parameters vs CNN | 51 vs 420,610 (8,247ร fewer) |
| Property | QCNN (This repo) | CNN (Companion repo) |
|---|---|---|
| Framework | PennyLane + PyTorch | TensorFlow / Keras |
| Input | 16-dim autoencoder latent vector | Raw 28ร28ร1 image |
| Trainable parameters | 51 | 420,610 |
| Test accuracy | ~60% | ~55% |
| Gradient method | Parameter-shift rule | Backpropagation |
| Training duration | 200 steps | 60 epochs |
| Batch size | 16 | 64 |
| Class imbalance | Hard balancing | Loss reweighting |
| Data augmentation | None | Rotation, flip, zoom |
| Hardware | CPU (Colab) | GPU (Colab) |
| Quantum device | default.qubit (noiseless) | โ |
Click the badge below to open directly in Colab:
Step 1 โ Clone the repository
git clone https://github.com/your-username/your-repo-name.git
cd your-repo-nameStep 2 โ Install dependencies
pip install pennylane pennylane-lightning torch torchvision
pip install medmnist scikit-learn numpy matplotlib tqdmStep 3 โ Run the notebook
jupyter notebook Msc_QCNN_corrected_dermaMNIST.ipynb
โ ๏ธ Note: QCNN training is computationally intensive on CPU due to the parameter-shift rule requiring 1,632 circuit evaluations per training step. Google Colab is strongly recommended.
pennylane>=0.36.0 pennylane-lightning torch>=2.0 torchvision medmnist scikit-learn numpy matplotlib tqdm
โโโ Msc_QCNN_corrected_dermaMNIST.ipynb # Main Colab notebook โ โโโ data.py # Dataset loading and autoencoder โ โโโ embedding.py # Quantum embedding strategies โ โโโ unitary.py # Convolutional ansatz definitions โ โโโ QCNN_circuit.py # QCNN circuit and measurement โ โโโ Training.py # Training loop and cost function โ โโโ Benchmarking.py # Encoding-to-embedding mapping โโโ README.md # This file
The codebase implements 9 convolutional unitary ansรคtze and 7 quantum embedding strategies, all benchmarkable via the same pipeline:
| Ansatz | Parameters | Key property |
|---|---|---|
| U_TTN | 2 | Tree Tensor Network โ minimal entanglement |
| U_5 | 10 | Symmetric CRZ entangling |
| U_6 | 10 | Symmetric CRX entangling |
| U_9 | 2 | Hadamard-based superposition |
| U_13 | 6 | Two-round CRZ |
| U_14 | 6 | Two-round CRX |
| U_15 | 4 | Two-round CNOT |
| U_SO4 | 6 | SO(4) subgroup โ real-valued |
| U_SU4 | 15 | Full SU(4) โ maximal expressibility (used) |
| Strategy | Values encoded | Description |
|---|---|---|
| Amplitude | 256 | Mรถttรถnen state preparation |
| Angle | 8 | Single RY per qubit |
| Angle-compact | 16 | RX + RY per qubit (used) |
| Amplitude-Hybrid4 | 32 | 4-qubit block amplitude embedding |
| Amplitude-Hybrid2 | 16 | 2-qubit block amplitude embedding |
| Angular-Hybrid4 | 30 | Custom multi-gate angle encoding |
| Angular-Hybrid2 | 12 | Custom controlled rotation encoding |
- Results are from a noiseless statevector simulator (
default.qubit). Real NISQ hardware would introduce gate errors and decoherence. - Single experimental run โ no multi-seed statistical averaging.
- Information asymmetry: QCNN receives 16-dim compressed features while CNN receives raw 784-dim pixel values.
- Small test set (~130 samples) โ results should be interpreted with caution.
- Noise-aware simulation using
default.mixedwith depolarising noise - Deployment on real NISQ hardware (IBM Quantum / IonQ)
- Multi-class DermaMNIST extension (all 7 lesion classes)
- Systematic benchmarking of all 9 ansรคtze and 7 embedding strategies
- Hybrid classical-quantum architectures (pre-trained backbone + QCNN classifier)
-
I. Cong, S. Choi, M. D. Lukin, "Quantum convolutional neural networks," Nature Physics, vol. 15, pp. 1273โ1278, 2019.
-
J. Yang et al., "MedMNIST v2 โ a large-scale lightweight benchmark for 2D and 3D biomedical image classification," Scientific Data, vol. 10, p. 41, 2023.
-
E. Hassan et al., "A quantum convolutional network and ResNet(50)-based classification architecture for the MNIST medical dataset," Biomed. Signal Process. Control, vol. 87, p. 105560, 2024.
-
V. Bergholm et al., "PennyLane: Automatic differentiation of hybrid quantum-classical computations," arXiv:1811.04968, 2022.
-
J. R. McClean et al., "Barren plateaus in quantum neural network training landscapes," Nature Communications, vol. 9, p. 4812, 2018.