I write simple qnn qnode code for mnist.
But it throws an error of dimension
I am not getting what is error about.
can you please look into it.
import pennylane as qml
import tensorflow as tf
from tensorflow.keras import layers
import numpy as np
# Define the quantum circuit for encoding
def qnode(params, x):
qml.templates.AngleEmbedding(x, wires=range(9))
qml.templates.BasicEntanglerLayers(params, wires=range(9))
return qml.expval(qml.PauliZ(0))
class QNN(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense = layers.Dense(10)
self.qnode = qml.QNode(qnode, device=qml.device('default.qubit', wires=9), interface='tf')
def call(self, inputs):
# Split the image into patches
patches = tf.image.extract_patches(inputs, sizes=[1,3,3,1], strides=[1,1,1,1], rates=[1,1,1,1],
padding='VALID')
patches = tf.reshape(patches, [-1, 9])
weights=np.random.uniform(size=(3,9))
# Apply the quantum circuit to each patch
q_results = self.qnode(weights, patches)
return self.dense(q_results)
# Load the MNIST dataset
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train=x_train.reshape(x_train.shape[0], 28,28,1)
model = QNN()
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=10, batch_size=32)
extracted patches from each mnist image and run qnode over it.