QNN for MNIST dimension problem

Hi,
I am trying to make a hybrid QNN model inspired by this tutorial 1. The modification I want to made is by changing the half moon dataset replaced by MNIST image data. However, I am having some error in the quantum layer.

code:
“”"
import matplotlib.pyplot as plt
from sklearn import datasets

import pennylane as qml
import tensorflow as tf
import numpy as np

import keras
from keras import layers
from sklearn.model_selection import train_test_split

from tensorflow import keras
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense,Flatten
import keras.losses

(X_train,y_train),(X_test,y_test) = keras.datasets.mnist.load_data()

n_qubits = 10
n_layers = 2
#data_dimension = 10
dev = qml.device(“default.qubit”, wires=n_qubits)

@qml.qnode(dev)
def qnode(weights, inputs=None):
qml.templates.AmplitudeEmbedding(features=inputs, wires=range(n_qubits),pad_with=0, normalize=True)
qml.templates.StronglyEntanglingLayers(weights, wires=range(n_qubits))
return [qml.expval(qml.PauliZ(i)) for i in range(n_qubits)]

weight_shapes = {“weights”: (n_layers,n_qubits)}

flayer = tf.keras.layers.Flatten(input_shape=[28, 28])
clayer_1 = tf.keras.layers.Dense(128,activation =‘relu’)
qlayer_1 = qml.qnn.KerasLayer(qnode, weight_shapes, output_dim=n_qubits)
clayer_3 = tf.keras.layers.Dense(10, activation=“softmax”)

model = tf.keras.models.Sequential([flayer, clayer_1,qlayer_1, clayer_3])

model.compile(
optimizer=‘adam’,
loss= ‘SparseCategoricalCrossentropy’,
metrics=[‘accuracy’],
)
model.summary()

bs = 1
n_epoch = 2
model.fit(
X_train,
y_train,
batch_size=bs,
epochs=n_epoch,
validation_data=(X_test, y_test),
)

with the error message:
IndexError: Exception encountered when calling layer ‘keras_layer_49’ (type KerasLayer).

tuple index out of range

Call arguments received by layer ‘keras_layer_49’ (type KerasLayer):
• inputs=tf.Tensor(shape=(1, 128), dtype=float64)

How to determine dimension on the quantum layer? Should I add any encoding/decoding techniques for this data?

Hi @monikakabir11 , welcome to the Forum!

Indeed making sure sizes match is a big part of the process. There are different ways of processing MNIST before you add it to a workflow so there’s no obvious right answer.

My recommendation would be to look at how others have done this, for example in our demo on quanvolutional neural networks, and our recent project on benchmarking quantum algorithms. If you’re interested in the latter I strongly recommend reading this blog post and maybe even the paper if you’re keen. We even have a dataset of a downscaled version of MNIST which you can download and use here.

If none of this helps you can take a look at projects made by the PennyLane community, for example this community demo. The community demo is from several years ago so it’s very likely that the code will no longer work, but it may give you some good ideas.

I hope this helps!

Thank you @CatalinaAlbornoz for your insightful suggestions and sharing the resources!

No problem @monikakabir11 ! I’m happy to help.