PennyLane
Install
Install

Related materials

  • Related contentTurning quantum nodes into Torch Layers
  • Related contentQuantum GANs
  • Related contentQuanvolutional Neural Networks

Contents

  1. Introduction
  2. Classical-to-quantum transfer learning
  3. General setup
  4. Setting of the main hyper-parameters of the model
  5. Dataset loading
  6. Variational quantum circuit
  7. Dressed quantum circuit
  8. Hybrid classical-quantum model
  9. Training and results
  10. Visualizing the model predictions
  11. References
  12. About the author

Downloads

  • Download Python script
  • Download Notebook
  • View on GitHub
  1. Demos/
  2. Quantum Machine Learning/
  3. Quantum transfer learning

Quantum transfer learning

Andrea Mari

Andrea Mari

Published: December 18, 2019. Last updated: April 17, 2026.

In this tutorial we apply a machine learning method, known as transfer learning, to an image classifier based on a hybrid classical-quantum network.

This example follows the general structure of the PyTorch tutorial on transfer learning by Sasank Chilamkurthy, with the crucial difference of using a quantum circuit to perform the final classification task.

More details on this topic can be found in the research paper [1] (Mari et al. (2019)).

Introduction

Transfer learning is a well-established technique for training artificial neural networks (see e.g., Ref. [2]), which is based on the general intuition that if a pre-trained network is good at solving a given problem, then, with just a bit of additional training, it can be used to also solve a different but related problem.

As discussed in Ref. [1], this idea can be formalized in terms of two abstract networks \(A\) and \(B,\) independently from their quantum or classical physical nature.


transfer_general

As sketched in the above figure, one can give the following general definition of the transfer learning method:

  1. Take a network \(A\) that has been pre-trained on a dataset \(D_A\) and for a given task \(T_A.\)

  2. Remove some of the final layers. In this way, the resulting truncated network \(A'\) can be used as a feature extractor.

  3. Connect a new trainable network \(B\) at the end of the pre-trained network \(A'.\)

  4. Keep the weights of \(A'\) constant, and train the final block \(B\) with a new dataset \(D_B\) and/or for a new task of interest \(T_B.\)

When dealing with hybrid systems, depending on the physical nature (classical or quantum) of the networks \(A\) and \(B,\) one can have different implementations of transfer learning as

summarized in following table:


Network A

Network B

Transfer learning scheme

Classical

Classical

CC - Standard classical method. See e.g., Ref. [2].

Classical

Quantum

CQ - Hybrid model presented in this tutorial.

Quantum

Classical

QC - Model studied in Ref. [1].

Quantum

Quantum

QQ - Model studied in Ref. [1].

Classical-to-quantum transfer learning

We focus on the CQ transfer learning scheme discussed in the previous section and we give a specific example.

  1. As pre-trained network \(A\) we use ResNet18, a deep residual neural network introduced by Microsoft in Ref. [3], which is pre-trained on the ImageNet dataset.

  2. After removing its final layer we obtain \(A',\) a pre-processing block which maps any input high-resolution image into 512 abstract features.

  3. Such features are classified by a 4-qubit “dressed quantum circuit” \(B,\) i.e., a variational quantum circuit sandwiched between two classical layers.

  4. The hybrid model is trained, keeping \(A'\) constant, on the Hymenoptera dataset (a small subclass of ImageNet) containing images of ants and bees.

A graphical representation of the full data processing pipeline is given in the figure below.

transfer_c2q

General setup

Note

To use the PyTorch interface in PennyLane, you must first install PyTorch.

In addition to PennyLane, we will also need some standard PyTorch libraries and the plotting library matplotlib.

# Some parts of this code are based on the Python script:
# https://github.com/pytorch/tutorials/blob/master/beginner_source/transfer_learning_tutorial.py
# License: BSD

import time
import os
import copy
import urllib.request
import shutil

# PyTorch
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import torchvision
from torchvision import datasets, transforms

# Pennylane
import pennylane as qp
from pennylane import numpy as np

torch.manual_seed(42)
np.random.seed(42)

# Plotting
import matplotlib.pyplot as plt

# OpenMP: number of parallel threads.
os.environ["OMP_NUM_THREADS"] = "1"

Setting of the main hyper-parameters of the model

Note

To reproduce the results of Ref. [1], num_epochs should be set to 30 which may take a long time. We suggest to first try with num_epochs=1 and, if everything runs smoothly, increase it to a larger value.

n_qubits = 4                # Number of qubits
step = 0.0004               # Learning rate
batch_size = 4              # Number of samples for each training step
num_epochs = 3              # Number of training epochs
q_depth = 6                 # Depth of the quantum circuit (number of variational layers)
gamma_lr_scheduler = 0.1    # Learning rate reduction applied every 10 epochs.
q_delta = 0.01              # Initial spread of random quantum weights
start_time = time.time()    # Start of the computation timer

We initialize a PennyLane device with a default.qubit backend.

dev = qp.device("default.qubit", wires=n_qubits)

We configure PyTorch to use CUDA only if available. Otherwise the CPU is used.

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

Dataset loading

Note

The dataset containing images of ants and bees can be downloaded here and should be extracted in the subfolder ../_data/hymenoptera_data.

This is a very small dataset (roughly 250 images), too small for training from scratch a classical or quantum model, however it is enough when using transfer learning approach.

The PyTorch packages torchvision and torch.utils.data are used for loading the dataset and performing standard preliminary image operations: resize, center, crop, normalize, etc.

data_transforms = {
    "train": transforms.Compose(
        [
            # transforms.RandomResizedCrop(224),     # uncomment for data augmentation
            # transforms.RandomHorizontalFlip(),     # uncomment for data augmentation
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            # Normalize input channels using mean values and standard deviations of ImageNet.
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
        ]
    ),
    "val": transforms.Compose(
        [
            transforms.Resize(256),
            transforms.CenterCrop(224),
            transforms.ToTensor(),
            transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
        ]
    ),
}

data_dir = "hymenoptera_data"
if not os.path.exists(data_dir):
    urllib.request.urlretrieve(
        "https://download.pytorch.org/tutorial/hymenoptera_data.zip", f"{data_dir}.zip"
    )
    shutil.unpack_archive(f"{data_dir}.zip")

image_datasets = {
    x if x == "train" else "validation": datasets.ImageFolder(
        os.path.join(data_dir, x), data_transforms[x]
    )
    for x in ["train", "val"]
}
dataset_sizes = {x: len(image_datasets[x]) for x in ["train", "validation"]}
class_names = image_datasets["train"].classes

# Initialize dataloader
dataloaders = {
    x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True)
    for x in ["train", "validation"]
}

# function to plot images
def imshow(inp, title=None):
    """Display image from tensor."""
    inp = inp.numpy().transpose((1, 2, 0))
    # Inverse of the initial normalization operation.
    mean = np.array([0.485, 0.456, 0.406])
    std = np.array([0.229, 0.224, 0.225])
    inp = std * inp + mean
    inp = np.clip(inp, 0, 1)
    plt.imshow(inp)
    if title is not None:
        plt.title(title)

Let us show a batch of the test data, just to have an idea of the classification problem.

# Get a batch of training data
inputs, classes = next(iter(dataloaders["validation"]))

# Make a grid from batch
out = torchvision.utils.make_grid(inputs)

imshow(out, title=[class_names[x] for x in classes])

dataloaders = {
    x: torch.utils.data.DataLoader(image_datasets[x], batch_size=batch_size, shuffle=True)
    for x in ["train", "validation"]
}
['bees', 'ants', 'bees', 'bees']

Variational quantum circuit

We first define some quantum layers that will compose the quantum circuit.

def H_layer(nqubits):
    """Layer of single-qubit Hadamard gates.
    """
    for idx in range(nqubits):
        qp.Hadamard(wires=idx)


def RY_layer(w):
    """Layer of parametrized qubit rotations around the y axis.
    """
    for idx, element in enumerate(w):
        qp.RY(element, wires=idx)


def entangling_layer(nqubits):
    """Layer of CNOTs followed by another shifted layer of CNOT.
    """
    # In other words it should apply something like :
    # CNOT  CNOT  CNOT  CNOT...  CNOT
    #   CNOT  CNOT  CNOT...  CNOT
    for i in range(0, nqubits - 1, 2):  # Loop over even indices: i=0,2,...N-2
        qp.CNOT(wires=[i, i + 1])
    for i in range(1, nqubits - 1, 2):  # Loop over odd indices:  i=1,3,...N-3
        qp.CNOT(wires=[i, i + 1])

Now we define the quantum circuit through the PennyLane qnode decorator .

The structure is that of a typical variational quantum circuit:

  • Embedding layer: All qubits are first initialized in a balanced superposition of up and down states, then they are rotated according to the input parameters (local embedding).

  • Variational layers: A sequence of trainable rotation layers and constant entangling layers is applied.

  • Measurement layer: For each qubit, the local expectation value of the \(Z\) operator is measured. This produces a classical output vector, suitable for additional post-processing.

@qp.qnode(dev)
def quantum_net(q_input_features, q_weights_flat):
    """
    The variational quantum circuit.
    """

    # Reshape weights
    q_weights = q_weights_flat.reshape(q_depth, n_qubits)

    # Start from state |+> , unbiased w.r.t. |0> and |1>
    H_layer(n_qubits)

    # Embed features in the quantum node
    RY_layer(q_input_features)

    # Sequence of trainable variational layers
    for k in range(q_depth):
        entangling_layer(n_qubits)
        RY_layer(q_weights[k])

    # Expectation values in the Z basis
    exp_vals = [qp.expval(qp.PauliZ(position)) for position in range(n_qubits)]
    return tuple(exp_vals)

Dressed quantum circuit

We can now define a custom torch.nn.Module representing a dressed quantum circuit.

This is a concatenation of:

  • A classical pre-processing layer (nn.Linear).

  • A classical activation function (torch.tanh).

  • A constant np.pi/2.0 scaling.

  • The previously defined quantum circuit (quantum_net).

  • A classical post-processing layer (nn.Linear).

The input of the module is a batch of vectors with 512 real parameters (features) and the output is a batch of vectors with two real outputs (associated with the two classes of images: ants and bees).

class DressedQuantumNet(nn.Module):
    """
    Torch module implementing the *dressed* quantum net.
    """

    def __init__(self):
        """
        Definition of the *dressed* layout.
        """

        super().__init__()
        self.pre_net = nn.Linear(512, n_qubits)
        self.q_params = nn.Parameter(q_delta * torch.randn(q_depth * n_qubits))
        self.post_net = nn.Linear(n_qubits, 2)

    def forward(self, input_features):
        """
        Defining how tensors are supposed to move through the *dressed* quantum
        net.
        """

        # obtain the input features for the quantum circuit
        # by reducing the feature dimension from 512 to 4
        pre_out = self.pre_net(input_features)
        q_in = torch.tanh(pre_out) * np.pi / 2.0

        # Apply the quantum circuit to each element of the batch and append to q_out
        q_out = torch.Tensor(0, n_qubits)
        q_out = q_out.to(device)
        for elem in q_in:
            q_out_elem = torch.hstack(quantum_net(elem, self.q_params)).float().unsqueeze(0)
            q_out = torch.cat((q_out, q_out_elem))

        # return the two-dimensional prediction from the postprocessing layer
        return self.post_net(q_out)

Hybrid classical-quantum model

We are finally ready to build our full hybrid classical-quantum network. We follow the transfer learning approach:

  1. First load the classical pre-trained network ResNet18 from the torchvision.models zoo.

  2. Freeze all the weights since they should not be trained.

  3. Replace the last fully connected layer with our trainable dressed quantum circuit (DressedQuantumNet).

Note

The ResNet18 model is automatically downloaded by PyTorch and it may take several minutes (only the first time).

weights = torchvision.models.ResNet18_Weights.IMAGENET1K_V1
model_hybrid = torchvision.models.resnet18(weights=weights)

for param in model_hybrid.parameters():
    param.requires_grad = False


# Notice that model_hybrid.fc is the last layer of ResNet18
model_hybrid.fc = DressedQuantumNet()

# Use CUDA or CPU according to the "device" object.
model_hybrid = model_hybrid.to(device)
Downloading: "https://download.pytorch.org/models/resnet18-f37072fd.pth" to /home/runner/.cache/torch/hub/checkpoints/resnet18-f37072fd.pth

0.3%
0.6%
0.8%
1.1%
1.4%
1.7%
2.0%
2.2%
2.5%
2.8%
3.1%
3.4%
3.6%
3.9%
4.2%
4.5%
4.8%
5.0%
5.3%
5.6%
5.9%
6.2%
6.4%
6.7%
7.0%
7.3%
7.6%
7.8%
8.1%
8.4%
8.7%
9.0%
9.2%
9.5%
9.8%
10.1%
10.4%
10.6%
10.9%
11.2%
11.5%
11.8%
12.0%
12.3%
12.6%
12.9%
13.2%
13.4%
13.7%
14.0%
14.3%
14.6%
14.8%
15.1%
15.4%
15.7%
16.0%
16.2%
16.5%
16.8%
17.1%
17.4%
17.6%
17.9%
18.2%
18.5%
18.8%
19.0%
19.3%
19.6%
19.9%
20.2%
20.4%
20.7%
21.0%
21.3%
21.6%
21.8%
22.1%
22.4%
22.7%
23.0%
23.2%
23.5%
23.8%
24.1%
24.4%
24.6%
24.9%
25.2%
25.5%
25.7%
26.0%
26.3%
26.6%
26.9%
27.1%
27.4%
27.7%
28.0%
28.3%
28.5%
28.8%
29.1%
29.4%
29.7%
29.9%
30.2%
30.5%
30.8%
31.1%
31.3%
31.6%
31.9%
32.2%
32.5%
32.7%
33.0%
33.3%
33.6%
33.9%
34.1%
34.4%
34.7%
35.0%
35.3%
35.5%
35.8%
36.1%
36.4%
36.7%
36.9%
37.2%
37.5%
37.8%
38.1%
38.3%
38.6%
38.9%
39.2%
39.5%
39.7%
40.0%
40.3%
40.6%
40.9%
41.1%
41.4%
41.7%
42.0%
42.3%
42.5%
42.8%
43.1%
43.4%
43.7%
43.9%
44.2%
44.5%
44.8%
45.1%
45.3%
45.6%
45.9%
46.2%
46.5%
46.7%
47.0%
47.3%
47.6%
47.9%
48.1%
48.4%
48.7%
49.0%
49.3%
49.5%
49.8%
50.1%
50.4%
50.7%
50.9%
51.2%
51.5%
51.8%
52.1%
52.3%
52.6%
52.9%
53.2%
53.5%
53.7%
54.0%
54.3%
54.6%
54.9%
55.1%
55.4%
55.7%
56.0%
56.3%
56.5%
56.8%
57.1%
57.4%
57.7%
57.9%
58.2%
58.5%
58.8%
59.1%
59.3%
59.6%
59.9%
60.2%
60.5%
60.7%
61.0%
61.3%
61.6%
61.9%
62.1%
62.4%
62.7%
63.0%
63.3%
63.5%
63.8%
64.1%
64.4%
64.7%
64.9%
65.2%
65.5%
65.8%
66.1%
66.3%
66.6%
66.9%
67.2%
67.5%
67.7%
68.0%
68.3%
68.6%
68.9%
69.1%
69.4%
69.7%
70.0%
70.3%
70.5%
70.8%
71.1%
71.4%
71.7%
71.9%
72.2%
72.5%
72.8%
73.1%
73.3%
73.6%
73.9%
74.2%
74.4%
74.7%
75.0%
75.3%
75.6%
75.8%
76.1%
76.4%
76.7%
77.0%
77.2%
77.5%
77.8%
78.1%
78.4%
78.6%
78.9%
79.2%
79.5%
79.8%
80.0%
80.3%
80.6%
80.9%
81.2%
81.4%
81.7%
82.0%
82.3%
82.6%
82.8%
83.1%
83.4%
83.7%
84.0%
84.2%
84.5%
84.8%
85.1%
85.4%
85.6%
85.9%
86.2%
86.5%
86.8%
87.0%
87.3%
87.6%
87.9%
88.2%
88.4%
88.7%
89.0%
89.3%
89.6%
89.8%
90.1%
90.4%
90.7%
91.0%
91.2%
91.5%
91.8%
92.1%
92.4%
92.6%
92.9%
93.2%
93.5%
93.8%
94.0%
94.3%
94.6%
94.9%
95.2%
95.4%
95.7%
96.0%
96.3%
96.6%
96.8%
97.1%
97.4%
97.7%
98.0%
98.2%
98.5%
98.8%
99.1%
99.4%
99.6%
99.9%
100.0%

Training and results

Before training the network we need to specify the loss function.

We use, as usual in classification problem, the cross-entropy which is directly available within torch.nn.

criterion = nn.CrossEntropyLoss()

We also initialize the Adam optimizer which is called at each training step in order to update the weights of the model.

optimizer_hybrid = optim.Adam(model_hybrid.fc.parameters(), lr=step)

We schedule to reduce the learning rate by a factor of gamma_lr_scheduler every 10 epochs.

exp_lr_scheduler = lr_scheduler.StepLR(
    optimizer_hybrid, step_size=10, gamma=gamma_lr_scheduler
)

What follows is a training function that will be called later. This function should return a trained model that can be used to make predictions (classifications).

def train_model(model, criterion, optimizer, scheduler, num_epochs):
    since = time.time()
    best_model_wts = copy.deepcopy(model.state_dict())
    best_acc = 0.0
    best_loss = 10000.0  # Large arbitrary number
    best_acc_train = 0.0
    best_loss_train = 10000.0  # Large arbitrary number
    print("Training started:")

    for epoch in range(num_epochs):

        # Each epoch has a training and validation phase
        for phase in ["train", "validation"]:
            if phase == "train":
                # Set model to training mode
                model.train()
            else:
                # Set model to evaluate mode
                model.eval()
            running_loss = 0.0
            running_corrects = 0

            # Iterate over data.
            n_batches = dataset_sizes[phase] // batch_size
            it = 0
            for inputs, labels in dataloaders[phase]:
                since_batch = time.time()
                batch_size_ = len(inputs)
                inputs = inputs.to(device)
                labels = labels.to(device)
                optimizer.zero_grad()

                # Track/compute gradient and make an optimization step only when training
                with torch.set_grad_enabled(phase == "train"):
                    outputs = model(inputs)
                    _, preds = torch.max(outputs, 1)
                    loss = criterion(outputs, labels)
                    if phase == "train":
                        loss.backward()
                        optimizer.step()

                # Print iteration results
                running_loss += loss.item() * batch_size_
                batch_corrects = torch.sum(preds == labels.data).item()
                running_corrects += batch_corrects
                print(
                    "Phase: {} Epoch: {}/{} Iter: {}/{} Batch time: {:.4f}".format(
                        phase,
                        epoch + 1,
                        num_epochs,
                        it + 1,
                        n_batches + 1,
                        time.time() - since_batch,
                    ),
                    end="\r",
                    flush=True,
                )
                it += 1

            # Print epoch results
            epoch_loss = running_loss / dataset_sizes[phase]
            epoch_acc = running_corrects / dataset_sizes[phase]
            print(
                "Phase: {} Epoch: {}/{} Loss: {:.4f} Acc: {:.4f}        ".format(
                    "train" if phase == "train" else "validation  ",
                    epoch + 1,
                    num_epochs,
                    epoch_loss,
                    epoch_acc,
                )
            )

            # Check if this is the best model wrt previous epochs
            if phase == "validation" and epoch_acc > best_acc:
                best_acc = epoch_acc
                best_model_wts = copy.deepcopy(model.state_dict())
            if phase == "validation" and epoch_loss < best_loss:
                best_loss = epoch_loss
            if phase == "train" and epoch_acc > best_acc_train:
                best_acc_train = epoch_acc
            if phase == "train" and epoch_loss < best_loss_train:
                best_loss_train = epoch_loss

            # Update learning rate
            if phase == "train":
                scheduler.step()

    # Print final results
    model.load_state_dict(best_model_wts)
    time_elapsed = time.time() - since
    print(
        "Training completed in {:.0f}m {:.0f}s".format(time_elapsed // 60, time_elapsed % 60)
    )
    print("Best test loss: {:.4f} | Best test accuracy: {:.4f}".format(best_loss, best_acc))
    return model

We are ready to perform the actual training process.

model_hybrid = train_model(
    model_hybrid, criterion, optimizer_hybrid, exp_lr_scheduler, num_epochs=num_epochs
)
Training started:
Phase: train Epoch: 1/3 Iter: 1/62 Batch time: 0.1826
Phase: train Epoch: 1/3 Iter: 2/62 Batch time: 0.1757
Phase: train Epoch: 1/3 Iter: 3/62 Batch time: 0.1775
Phase: train Epoch: 1/3 Iter: 4/62 Batch time: 0.1777
Phase: train Epoch: 1/3 Iter: 5/62 Batch time: 0.1778
Phase: train Epoch: 1/3 Iter: 6/62 Batch time: 0.1772
Phase: train Epoch: 1/3 Iter: 7/62 Batch time: 0.1834
Phase: train Epoch: 1/3 Iter: 8/62 Batch time: 0.1795
Phase: train Epoch: 1/3 Iter: 9/62 Batch time: 0.1794
Phase: train Epoch: 1/3 Iter: 10/62 Batch time: 0.1777
Phase: train Epoch: 1/3 Iter: 11/62 Batch time: 0.1793
Phase: train Epoch: 1/3 Iter: 12/62 Batch time: 0.1815
Phase: train Epoch: 1/3 Iter: 13/62 Batch time: 0.1909
Phase: train Epoch: 1/3 Iter: 14/62 Batch time: 0.1901
Phase: train Epoch: 1/3 Iter: 15/62 Batch time: 0.1837
Phase: train Epoch: 1/3 Iter: 16/62 Batch time: 0.1842
Phase: train Epoch: 1/3 Iter: 17/62 Batch time: 0.1887
Phase: train Epoch: 1/3 Iter: 18/62 Batch time: 0.1884
Phase: train Epoch: 1/3 Iter: 19/62 Batch time: 0.1844
Phase: train Epoch: 1/3 Iter: 20/62 Batch time: 0.1843
Phase: train Epoch: 1/3 Iter: 21/62 Batch time: 0.1863
Phase: train Epoch: 1/3 Iter: 22/62 Batch time: 0.1874
Phase: train Epoch: 1/3 Iter: 23/62 Batch time: 0.1843
Phase: train Epoch: 1/3 Iter: 24/62 Batch time: 0.1901
Phase: train Epoch: 1/3 Iter: 25/62 Batch time: 0.1844
Phase: train Epoch: 1/3 Iter: 26/62 Batch time: 0.1833
Phase: train Epoch: 1/3 Iter: 27/62 Batch time: 0.1862
Phase: train Epoch: 1/3 Iter: 28/62 Batch time: 0.1888
Phase: train Epoch: 1/3 Iter: 29/62 Batch time: 0.1816
Phase: train Epoch: 1/3 Iter: 30/62 Batch time: 0.1826
Phase: train Epoch: 1/3 Iter: 31/62 Batch time: 0.1780
Phase: train Epoch: 1/3 Iter: 32/62 Batch time: 0.1791
Phase: train Epoch: 1/3 Iter: 33/62 Batch time: 0.1806
Phase: train Epoch: 1/3 Iter: 34/62 Batch time: 0.1793
Phase: train Epoch: 1/3 Iter: 35/62 Batch time: 0.1822
Phase: train Epoch: 1/3 Iter: 36/62 Batch time: 0.1814
Phase: train Epoch: 1/3 Iter: 37/62 Batch time: 0.1860
Phase: train Epoch: 1/3 Iter: 38/62 Batch time: 0.1887
Phase: train Epoch: 1/3 Iter: 39/62 Batch time: 0.1909
Phase: train Epoch: 1/3 Iter: 40/62 Batch time: 0.1873
Phase: train Epoch: 1/3 Iter: 41/62 Batch time: 0.1825
Phase: train Epoch: 1/3 Iter: 42/62 Batch time: 0.1800
Phase: train Epoch: 1/3 Iter: 43/62 Batch time: 0.1803
Phase: train Epoch: 1/3 Iter: 44/62 Batch time: 0.1875
Phase: train Epoch: 1/3 Iter: 45/62 Batch time: 0.1883
Phase: train Epoch: 1/3 Iter: 46/62 Batch time: 0.1858
Phase: train Epoch: 1/3 Iter: 47/62 Batch time: 0.1820
Phase: train Epoch: 1/3 Iter: 48/62 Batch time: 0.1834
Phase: train Epoch: 1/3 Iter: 49/62 Batch time: 0.1899
Phase: train Epoch: 1/3 Iter: 50/62 Batch time: 0.1900
Phase: train Epoch: 1/3 Iter: 51/62 Batch time: 0.1865
Phase: train Epoch: 1/3 Iter: 52/62 Batch time: 0.1882
Phase: train Epoch: 1/3 Iter: 53/62 Batch time: 0.1884
Phase: train Epoch: 1/3 Iter: 54/62 Batch time: 0.1864
Phase: train Epoch: 1/3 Iter: 55/62 Batch time: 0.1872
Phase: train Epoch: 1/3 Iter: 56/62 Batch time: 0.1880
Phase: train Epoch: 1/3 Iter: 57/62 Batch time: 0.1953
Phase: train Epoch: 1/3 Iter: 58/62 Batch time: 0.1856
Phase: train Epoch: 1/3 Iter: 59/62 Batch time: 0.1925
Phase: train Epoch: 1/3 Iter: 60/62 Batch time: 0.1841
Phase: train Epoch: 1/3 Iter: 61/62 Batch time: 0.1840
Phase: train Epoch: 1/3 Loss: 0.6990 Acc: 0.5246
Phase: validation Epoch: 1/3 Iter: 1/39 Batch time: 0.1493
Phase: validation Epoch: 1/3 Iter: 2/39 Batch time: 0.1490
Phase: validation Epoch: 1/3 Iter: 3/39 Batch time: 0.1474
Phase: validation Epoch: 1/3 Iter: 4/39 Batch time: 0.1476
Phase: validation Epoch: 1/3 Iter: 5/39 Batch time: 0.1431
Phase: validation Epoch: 1/3 Iter: 6/39 Batch time: 0.1436
Phase: validation Epoch: 1/3 Iter: 7/39 Batch time: 0.1459
Phase: validation Epoch: 1/3 Iter: 8/39 Batch time: 0.1469
Phase: validation Epoch: 1/3 Iter: 9/39 Batch time: 0.1476
Phase: validation Epoch: 1/3 Iter: 10/39 Batch time: 0.1463
Phase: validation Epoch: 1/3 Iter: 11/39 Batch time: 0.1434
Phase: validation Epoch: 1/3 Iter: 12/39 Batch time: 0.1434
Phase: validation Epoch: 1/3 Iter: 13/39 Batch time: 0.1446
Phase: validation Epoch: 1/3 Iter: 14/39 Batch time: 0.1503
Phase: validation Epoch: 1/3 Iter: 15/39 Batch time: 0.1441
Phase: validation Epoch: 1/3 Iter: 16/39 Batch time: 0.1445
Phase: validation Epoch: 1/3 Iter: 17/39 Batch time: 0.1502
Phase: validation Epoch: 1/3 Iter: 18/39 Batch time: 0.1486
Phase: validation Epoch: 1/3 Iter: 19/39 Batch time: 0.1428
Phase: validation Epoch: 1/3 Iter: 20/39 Batch time: 0.1472
Phase: validation Epoch: 1/3 Iter: 21/39 Batch time: 0.1453
Phase: validation Epoch: 1/3 Iter: 22/39 Batch time: 0.1432
Phase: validation Epoch: 1/3 Iter: 23/39 Batch time: 0.1461
Phase: validation Epoch: 1/3 Iter: 24/39 Batch time: 0.1487
Phase: validation Epoch: 1/3 Iter: 25/39 Batch time: 0.1483
Phase: validation Epoch: 1/3 Iter: 26/39 Batch time: 0.1515
Phase: validation Epoch: 1/3 Iter: 27/39 Batch time: 0.1494
Phase: validation Epoch: 1/3 Iter: 28/39 Batch time: 0.1470
Phase: validation Epoch: 1/3 Iter: 29/39 Batch time: 0.1458
Phase: validation Epoch: 1/3 Iter: 30/39 Batch time: 0.1447
Phase: validation Epoch: 1/3 Iter: 31/39 Batch time: 0.1499
Phase: validation Epoch: 1/3 Iter: 32/39 Batch time: 0.1485
Phase: validation Epoch: 1/3 Iter: 33/39 Batch time: 0.1482
Phase: validation Epoch: 1/3 Iter: 34/39 Batch time: 0.1463
Phase: validation Epoch: 1/3 Iter: 35/39 Batch time: 0.1451
Phase: validation Epoch: 1/3 Iter: 36/39 Batch time: 0.1493
Phase: validation Epoch: 1/3 Iter: 37/39 Batch time: 0.1476
Phase: validation Epoch: 1/3 Iter: 38/39 Batch time: 0.1476
Phase: validation Epoch: 1/3 Iter: 39/39 Batch time: 0.0423
Phase: validation   Epoch: 1/3 Loss: 0.6429 Acc: 0.6536
Phase: train Epoch: 2/3 Iter: 1/62 Batch time: 0.1758
Phase: train Epoch: 2/3 Iter: 2/62 Batch time: 0.1818
Phase: train Epoch: 2/3 Iter: 3/62 Batch time: 0.1778
Phase: train Epoch: 2/3 Iter: 4/62 Batch time: 0.1792
Phase: train Epoch: 2/3 Iter: 5/62 Batch time: 0.1796
Phase: train Epoch: 2/3 Iter: 6/62 Batch time: 0.1826
Phase: train Epoch: 2/3 Iter: 7/62 Batch time: 0.1838
Phase: train Epoch: 2/3 Iter: 8/62 Batch time: 0.1821
Phase: train Epoch: 2/3 Iter: 9/62 Batch time: 0.1779
Phase: train Epoch: 2/3 Iter: 10/62 Batch time: 0.1804
Phase: train Epoch: 2/3 Iter: 11/62 Batch time: 0.1821
Phase: train Epoch: 2/3 Iter: 12/62 Batch time: 0.1794
Phase: train Epoch: 2/3 Iter: 13/62 Batch time: 0.1791
Phase: train Epoch: 2/3 Iter: 14/62 Batch time: 0.1799
Phase: train Epoch: 2/3 Iter: 15/62 Batch time: 0.1785
Phase: train Epoch: 2/3 Iter: 16/62 Batch time: 0.1857
Phase: train Epoch: 2/3 Iter: 17/62 Batch time: 0.1779
Phase: train Epoch: 2/3 Iter: 18/62 Batch time: 0.1782
Phase: train Epoch: 2/3 Iter: 19/62 Batch time: 0.1779
Phase: train Epoch: 2/3 Iter: 20/62 Batch time: 0.1777
Phase: train Epoch: 2/3 Iter: 21/62 Batch time: 0.1780
Phase: train Epoch: 2/3 Iter: 22/62 Batch time: 0.1828
Phase: train Epoch: 2/3 Iter: 23/62 Batch time: 0.1795
Phase: train Epoch: 2/3 Iter: 24/62 Batch time: 0.1774
Phase: train Epoch: 2/3 Iter: 25/62 Batch time: 0.1771
Phase: train Epoch: 2/3 Iter: 26/62 Batch time: 0.1778
Phase: train Epoch: 2/3 Iter: 27/62 Batch time: 0.1772
Phase: train Epoch: 2/3 Iter: 28/62 Batch time: 0.1777
Phase: train Epoch: 2/3 Iter: 29/62 Batch time: 0.1767
Phase: train Epoch: 2/3 Iter: 30/62 Batch time: 0.1774
Phase: train Epoch: 2/3 Iter: 31/62 Batch time: 0.1785
Phase: train Epoch: 2/3 Iter: 32/62 Batch time: 0.1776
Phase: train Epoch: 2/3 Iter: 33/62 Batch time: 0.1769
Phase: train Epoch: 2/3 Iter: 34/62 Batch time: 0.1771
Phase: train Epoch: 2/3 Iter: 35/62 Batch time: 0.1771
Phase: train Epoch: 2/3 Iter: 36/62 Batch time: 0.1773
Phase: train Epoch: 2/3 Iter: 37/62 Batch time: 0.1772
Phase: train Epoch: 2/3 Iter: 38/62 Batch time: 0.1770
Phase: train Epoch: 2/3 Iter: 39/62 Batch time: 0.1772
Phase: train Epoch: 2/3 Iter: 40/62 Batch time: 0.1775
Phase: train Epoch: 2/3 Iter: 41/62 Batch time: 0.1844
Phase: train Epoch: 2/3 Iter: 42/62 Batch time: 0.4100
Phase: train Epoch: 2/3 Iter: 43/62 Batch time: 0.1796
Phase: train Epoch: 2/3 Iter: 44/62 Batch time: 0.1778
Phase: train Epoch: 2/3 Iter: 45/62 Batch time: 0.1776
Phase: train Epoch: 2/3 Iter: 46/62 Batch time: 0.1784
Phase: train Epoch: 2/3 Iter: 47/62 Batch time: 0.1771
Phase: train Epoch: 2/3 Iter: 48/62 Batch time: 0.1782
Phase: train Epoch: 2/3 Iter: 49/62 Batch time: 0.1754
Phase: train Epoch: 2/3 Iter: 50/62 Batch time: 0.1775
Phase: train Epoch: 2/3 Iter: 51/62 Batch time: 0.1805
Phase: train Epoch: 2/3 Iter: 52/62 Batch time: 0.1774
Phase: train Epoch: 2/3 Iter: 53/62 Batch time: 0.1772
Phase: train Epoch: 2/3 Iter: 54/62 Batch time: 0.1776
Phase: train Epoch: 2/3 Iter: 55/62 Batch time: 0.1797
Phase: train Epoch: 2/3 Iter: 56/62 Batch time: 0.1810
Phase: train Epoch: 2/3 Iter: 57/62 Batch time: 0.1806
Phase: train Epoch: 2/3 Iter: 58/62 Batch time: 0.1825
Phase: train Epoch: 2/3 Iter: 59/62 Batch time: 0.1830
Phase: train Epoch: 2/3 Iter: 60/62 Batch time: 0.1842
Phase: train Epoch: 2/3 Iter: 61/62 Batch time: 0.1808
Phase: train Epoch: 2/3 Loss: 0.6134 Acc: 0.7008
Phase: validation Epoch: 2/3 Iter: 1/39 Batch time: 0.1475
Phase: validation Epoch: 2/3 Iter: 2/39 Batch time: 0.1432
Phase: validation Epoch: 2/3 Iter: 3/39 Batch time: 0.1430
Phase: validation Epoch: 2/3 Iter: 4/39 Batch time: 0.1421
Phase: validation Epoch: 2/3 Iter: 5/39 Batch time: 0.1421
Phase: validation Epoch: 2/3 Iter: 6/39 Batch time: 0.1416
Phase: validation Epoch: 2/3 Iter: 7/39 Batch time: 0.1494
Phase: validation Epoch: 2/3 Iter: 8/39 Batch time: 0.1417
Phase: validation Epoch: 2/3 Iter: 9/39 Batch time: 0.1429
Phase: validation Epoch: 2/3 Iter: 10/39 Batch time: 0.1414
Phase: validation Epoch: 2/3 Iter: 11/39 Batch time: 0.1432
Phase: validation Epoch: 2/3 Iter: 12/39 Batch time: 0.1417
Phase: validation Epoch: 2/3 Iter: 13/39 Batch time: 0.1417
Phase: validation Epoch: 2/3 Iter: 14/39 Batch time: 0.1419
Phase: validation Epoch: 2/3 Iter: 15/39 Batch time: 0.1419
Phase: validation Epoch: 2/3 Iter: 16/39 Batch time: 0.1415
Phase: validation Epoch: 2/3 Iter: 17/39 Batch time: 0.1423
Phase: validation Epoch: 2/3 Iter: 18/39 Batch time: 0.1416
Phase: validation Epoch: 2/3 Iter: 19/39 Batch time: 0.1424
Phase: validation Epoch: 2/3 Iter: 20/39 Batch time: 0.1414
Phase: validation Epoch: 2/3 Iter: 21/39 Batch time: 0.1422
Phase: validation Epoch: 2/3 Iter: 22/39 Batch time: 0.1413
Phase: validation Epoch: 2/3 Iter: 23/39 Batch time: 0.1422
Phase: validation Epoch: 2/3 Iter: 24/39 Batch time: 0.1416
Phase: validation Epoch: 2/3 Iter: 25/39 Batch time: 0.1420
Phase: validation Epoch: 2/3 Iter: 26/39 Batch time: 0.1413
Phase: validation Epoch: 2/3 Iter: 27/39 Batch time: 0.1428
Phase: validation Epoch: 2/3 Iter: 28/39 Batch time: 0.1402
Phase: validation Epoch: 2/3 Iter: 29/39 Batch time: 0.1430
Phase: validation Epoch: 2/3 Iter: 30/39 Batch time: 0.1414
Phase: validation Epoch: 2/3 Iter: 31/39 Batch time: 0.1424
Phase: validation Epoch: 2/3 Iter: 32/39 Batch time: 0.1415
Phase: validation Epoch: 2/3 Iter: 33/39 Batch time: 0.1423
Phase: validation Epoch: 2/3 Iter: 34/39 Batch time: 0.1427
Phase: validation Epoch: 2/3 Iter: 35/39 Batch time: 0.1438
Phase: validation Epoch: 2/3 Iter: 36/39 Batch time: 0.1440
Phase: validation Epoch: 2/3 Iter: 37/39 Batch time: 0.1430
Phase: validation Epoch: 2/3 Iter: 38/39 Batch time: 0.1428
Phase: validation Epoch: 2/3 Iter: 39/39 Batch time: 0.0395
Phase: validation   Epoch: 2/3 Loss: 0.5389 Acc: 0.8235
Phase: train Epoch: 3/3 Iter: 1/62 Batch time: 0.1762
Phase: train Epoch: 3/3 Iter: 2/62 Batch time: 0.1764
Phase: train Epoch: 3/3 Iter: 3/62 Batch time: 0.1729
Phase: train Epoch: 3/3 Iter: 4/62 Batch time: 0.1736
Phase: train Epoch: 3/3 Iter: 5/62 Batch time: 0.1729
Phase: train Epoch: 3/3 Iter: 6/62 Batch time: 0.1732
Phase: train Epoch: 3/3 Iter: 7/62 Batch time: 0.1734
Phase: train Epoch: 3/3 Iter: 8/62 Batch time: 0.1741
Phase: train Epoch: 3/3 Iter: 9/62 Batch time: 0.1737
Phase: train Epoch: 3/3 Iter: 10/62 Batch time: 0.1736
Phase: train Epoch: 3/3 Iter: 11/62 Batch time: 0.1745
Phase: train Epoch: 3/3 Iter: 12/62 Batch time: 0.1736
Phase: train Epoch: 3/3 Iter: 13/62 Batch time: 0.1734
Phase: train Epoch: 3/3 Iter: 14/62 Batch time: 0.1734
Phase: train Epoch: 3/3 Iter: 15/62 Batch time: 0.1741
Phase: train Epoch: 3/3 Iter: 16/62 Batch time: 0.1731
Phase: train Epoch: 3/3 Iter: 17/62 Batch time: 0.1747
Phase: train Epoch: 3/3 Iter: 18/62 Batch time: 0.1738
Phase: train Epoch: 3/3 Iter: 19/62 Batch time: 0.1734
Phase: train Epoch: 3/3 Iter: 20/62 Batch time: 0.1750
Phase: train Epoch: 3/3 Iter: 21/62 Batch time: 0.1758
Phase: train Epoch: 3/3 Iter: 22/62 Batch time: 0.1762
Phase: train Epoch: 3/3 Iter: 23/62 Batch time: 0.1744
Phase: train Epoch: 3/3 Iter: 24/62 Batch time: 0.1752
Phase: train Epoch: 3/3 Iter: 25/62 Batch time: 0.1744
Phase: train Epoch: 3/3 Iter: 26/62 Batch time: 0.1756
Phase: train Epoch: 3/3 Iter: 27/62 Batch time: 0.1734
Phase: train Epoch: 3/3 Iter: 28/62 Batch time: 0.1752
Phase: train Epoch: 3/3 Iter: 29/62 Batch time: 0.1734
Phase: train Epoch: 3/3 Iter: 30/62 Batch time: 0.1738
Phase: train Epoch: 3/3 Iter: 31/62 Batch time: 0.1737
Phase: train Epoch: 3/3 Iter: 32/62 Batch time: 0.1748
Phase: train Epoch: 3/3 Iter: 33/62 Batch time: 0.1748
Phase: train Epoch: 3/3 Iter: 34/62 Batch time: 0.1739
Phase: train Epoch: 3/3 Iter: 35/62 Batch time: 0.1755
Phase: train Epoch: 3/3 Iter: 36/62 Batch time: 0.1749
Phase: train Epoch: 3/3 Iter: 37/62 Batch time: 0.1759
Phase: train Epoch: 3/3 Iter: 38/62 Batch time: 0.1745
Phase: train Epoch: 3/3 Iter: 39/62 Batch time: 0.1747
Phase: train Epoch: 3/3 Iter: 40/62 Batch time: 0.1761
Phase: train Epoch: 3/3 Iter: 41/62 Batch time: 0.1749
Phase: train Epoch: 3/3 Iter: 42/62 Batch time: 0.1747
Phase: train Epoch: 3/3 Iter: 43/62 Batch time: 0.1743
Phase: train Epoch: 3/3 Iter: 44/62 Batch time: 0.1742
Phase: train Epoch: 3/3 Iter: 45/62 Batch time: 0.1749
Phase: train Epoch: 3/3 Iter: 46/62 Batch time: 0.1738
Phase: train Epoch: 3/3 Iter: 47/62 Batch time: 0.1743
Phase: train Epoch: 3/3 Iter: 48/62 Batch time: 0.1736
Phase: train Epoch: 3/3 Iter: 49/62 Batch time: 0.1734
Phase: train Epoch: 3/3 Iter: 50/62 Batch time: 0.1734
Phase: train Epoch: 3/3 Iter: 51/62 Batch time: 0.1728
Phase: train Epoch: 3/3 Iter: 52/62 Batch time: 0.1745
Phase: train Epoch: 3/3 Iter: 53/62 Batch time: 0.1755
Phase: train Epoch: 3/3 Iter: 54/62 Batch time: 0.1750
Phase: train Epoch: 3/3 Iter: 55/62 Batch time: 0.1744
Phase: train Epoch: 3/3 Iter: 56/62 Batch time: 0.1755
Phase: train Epoch: 3/3 Iter: 57/62 Batch time: 0.1749
Phase: train Epoch: 3/3 Iter: 58/62 Batch time: 0.1748
Phase: train Epoch: 3/3 Iter: 59/62 Batch time: 0.1748
Phase: train Epoch: 3/3 Iter: 60/62 Batch time: 0.1741
Phase: train Epoch: 3/3 Iter: 61/62 Batch time: 0.1730
Phase: train Epoch: 3/3 Loss: 0.5652 Acc: 0.7418
Phase: validation Epoch: 3/3 Iter: 1/39 Batch time: 0.1389
Phase: validation Epoch: 3/3 Iter: 2/39 Batch time: 0.1372
Phase: validation Epoch: 3/3 Iter: 3/39 Batch time: 0.1376
Phase: validation Epoch: 3/3 Iter: 4/39 Batch time: 0.1374
Phase: validation Epoch: 3/3 Iter: 5/39 Batch time: 0.1389
Phase: validation Epoch: 3/3 Iter: 6/39 Batch time: 0.1378
Phase: validation Epoch: 3/3 Iter: 7/39 Batch time: 0.1380
Phase: validation Epoch: 3/3 Iter: 8/39 Batch time: 0.1376
Phase: validation Epoch: 3/3 Iter: 9/39 Batch time: 0.1372
Phase: validation Epoch: 3/3 Iter: 10/39 Batch time: 0.1372
Phase: validation Epoch: 3/3 Iter: 11/39 Batch time: 0.1368
Phase: validation Epoch: 3/3 Iter: 12/39 Batch time: 0.1369
Phase: validation Epoch: 3/3 Iter: 13/39 Batch time: 0.1389
Phase: validation Epoch: 3/3 Iter: 14/39 Batch time: 0.1373
Phase: validation Epoch: 3/3 Iter: 15/39 Batch time: 0.1377
Phase: validation Epoch: 3/3 Iter: 16/39 Batch time: 0.1413
Phase: validation Epoch: 3/3 Iter: 17/39 Batch time: 0.1415
Phase: validation Epoch: 3/3 Iter: 18/39 Batch time: 0.1372
Phase: validation Epoch: 3/3 Iter: 19/39 Batch time: 0.1371
Phase: validation Epoch: 3/3 Iter: 20/39 Batch time: 0.1377
Phase: validation Epoch: 3/3 Iter: 21/39 Batch time: 0.1381
Phase: validation Epoch: 3/3 Iter: 22/39 Batch time: 0.1373
Phase: validation Epoch: 3/3 Iter: 23/39 Batch time: 0.1375
Phase: validation Epoch: 3/3 Iter: 24/39 Batch time: 0.1374
Phase: validation Epoch: 3/3 Iter: 25/39 Batch time: 0.1374
Phase: validation Epoch: 3/3 Iter: 26/39 Batch time: 0.1372
Phase: validation Epoch: 3/3 Iter: 27/39 Batch time: 0.1372
Phase: validation Epoch: 3/3 Iter: 28/39 Batch time: 0.1378
Phase: validation Epoch: 3/3 Iter: 29/39 Batch time: 0.1374
Phase: validation Epoch: 3/3 Iter: 30/39 Batch time: 0.1370
Phase: validation Epoch: 3/3 Iter: 31/39 Batch time: 0.1380
Phase: validation Epoch: 3/3 Iter: 32/39 Batch time: 0.1374
Phase: validation Epoch: 3/3 Iter: 33/39 Batch time: 0.1377
Phase: validation Epoch: 3/3 Iter: 34/39 Batch time: 0.1371
Phase: validation Epoch: 3/3 Iter: 35/39 Batch time: 0.1376
Phase: validation Epoch: 3/3 Iter: 36/39 Batch time: 0.1370
Phase: validation Epoch: 3/3 Iter: 37/39 Batch time: 0.1372
Phase: validation Epoch: 3/3 Iter: 38/39 Batch time: 0.1396
Phase: validation Epoch: 3/3 Iter: 39/39 Batch time: 0.0392
Phase: validation   Epoch: 3/3 Loss: 0.4484 Acc: 0.8497
Training completed in 0m 55s
Best test loss: 0.4484 | Best test accuracy: 0.8497

Visualizing the model predictions

We first define a visualization function for a batch of test data.

def visualize_model(model, num_images=6, fig_name="Predictions"):
    images_so_far = 0
    _fig = plt.figure(fig_name)
    model.eval()
    with torch.no_grad():
        for _i, (inputs, labels) in enumerate(dataloaders["validation"]):
            inputs = inputs.to(device)
            labels = labels.to(device)
            outputs = model(inputs)
            _, preds = torch.max(outputs, 1)
            for j in range(inputs.size()[0]):
                images_so_far += 1
                ax = plt.subplot(num_images // 2, 2, images_so_far)
                ax.axis("off")
                ax.set_title("[{}]".format(class_names[preds[j]]))
                imshow(inputs.cpu().data[j])
                if images_so_far == num_images:
                    return

Finally, we can run the previous function to see a batch of images with the corresponding predictions.

visualize_model(model_hybrid, num_images=batch_size)
plt.show()
[ants], [ants], [ants], [ants]

References

[1] Andrea Mari, Thomas R. Bromley, Josh Izaac, Maria Schuld, and Nathan Killoran. Transfer learning in hybrid classical-quantum neural networks. arXiv:1912.08278 (2019).

[2] Rajat Raina, Alexis Battle, Honglak Lee, Benjamin Packer, and Andrew Y Ng. Self-taught learning: transfer learning from unlabeled data. Proceedings of the 24th International Conference on Machine Learning*, 759–766 (2007).

[3] Kaiming He, Xiangyu Zhang, Shaoqing ren and Jian Sun. Deep residual learning for image recognition. Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition, 770-778 (2016).

[4] Ville Bergholm, Josh Izaac, Maria Schuld, Christian Gogolin, Carsten Blank, Keri McKiernan, and Nathan Killoran. PennyLane: Automatic differentiation of hybrid quantum-classical computations. arXiv:1811.04968 (2018).

About the author

Andrea Mari
Andrea Mari

Andrea Mari

Andrea obtained a PhD in quantum information theory from the University of Potsdam (Germany). He worked as a postdoc at Scuola Normale Superiore (Pisa, Italy) and as a remote researcher at Xanadu. Since 2020 is a Member of Technical Staff at Unitary ...

Total running time of the script: (1 minute 2.400 seconds)

Share demo

Ask a question on the forum

Related Demos

Turning quantum nodes into Torch Layers

Quantum GANs

Quanvolutional Neural Networks

Adversarial attacks and robustness for quantum machine learning

Variational Quantum Linear Solver

Multiclass margin classifier

Loading classical data with low-depth circuits

Turning quantum nodes into Keras Layers

Dropout in Quantum Neural Networks

Data-reuploading classifier

Never miss a milestone

Get the latest quantum updates delivered to your inbox.

Join the list
PennyLane

PennyLane is an open-source quantum software platform for quantum computing, quantum machine learning, and quantum chemistry. Create meaningful quantum algorithms, from inspiration to implementation.

Created with ❤️ by Xanadu.

Research

  • Research

  • Performance

  • Hardware and simulators

  • Demos library

  • Compilation hub

  • Quantum datasets

Education

  • Teach

  • Learn

  • Codebook

  • Coding challenges

  • Videos

  • Glossary

Software

  • Install

  • Features

  • PennyLane documentation

  • Catalyst documentation

  • Development guide

  • How-to guides

  • API

  • GitHub


Xanadu

© Copyright 2026 | Xanadu | All rights reserved

TensorFlow, the TensorFlow logo and any related marks are trademarks of Google Inc.

Privacy policyTerms of serviceCookies policyCode of conduct