Hello!
I created a subclass MyDenseLayer of the parent class KerasLayer and then tried to process the data using the newly defined methods.
One of the problems encountered was that the error reporting could be solved by deleting the index.
Cell In[49], line 11, in circuit(inputs, weights)
9 qml.AngleEmbedding(inputs[4:8], wires=range(0,4), rotation='Y')
10 qml.AngleEmbedding(inputs[8:12], wires=range(0,4), rotation='Z')
---> 11 qml.CRX(weights[0], wires=[0,1])
12 qml.CRX(weights[1], wires=[1,2])
13 qml.CRX(weights[2], wires=[2,3])
TypeError: Exception encountered when calling layer 'my_dense_layer_3' (type MyDenseLayer).
In that event, a new problem has arisen, and I don’t know what to do to solve it.
383 return str([qml.math.round(qml.math.real(d) % (2 * np.pi), 10) for d in op.data])
385 if op.name in ("CRX", "CRY", "CRZ", "CRot"):
--> 386 return str([qml.math.round(qml.math.real(d) % (4 * np.pi), 10) for d in op.data])
388 return str(op.data)
TypeError: Exception encountered when calling layer 'my_dense_layer_4' (type MyDenseLayer).
unsupported operand type(s) for %: 'generator' and 'float'
Call arguments received by layer 'my_dense_layer_4' (type MyDenseLayer):
• inputs=tf.Tensor(shape=(1, 32, 32, 3), dtype=float32)
Full Code:
from tensorflow.keras.datasets import cifar10
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers.experimental import preprocessing
(x_train_full, y_train_full), (x_test, y_test) = cifar10.load_data()
split = 0.2
x_train, x_val, y_train, y_val = train_test_split(
x_train_full, y_train_full, test_size=0.2, random_state=42)
x_train = preprocessing.Rescaling(scale=1.0/255)(x_train)
x_val = preprocessing.Rescaling(scale=1.0/255)(x_val)
y_train = y_train.reshape(y_train.shape[0],)
y_val = y_val.reshape(y_val.shape[0],)
import tensorflow as tf
import pennylane as qml
from pennylane import numpy as np
import matplotlib.pyplot as plt
import torch
n_qubits = 5
# qiskit.aer, default.qubit
dev = qml.device("default.qubit", wires=n_qubits)
@qml.qnode(dev)
def circuit(inputs, weights):
qml.Hadamard(wires=0)
qml.AngleEmbedding(inputs[0:4], wires=range(0,4), rotation='X')
qml.AngleEmbedding(inputs[4:8], wires=range(0,4), rotation='Y')
qml.AngleEmbedding(inputs[8:12], wires=range(0,4), rotation='Z')
qml.CRX(weights, wires=[0,1])
qml.CRX(weights, wires=[1,2])
qml.CRX(weights, wires=[2,3])
qml.CRX(weights, wires=[3,1])
qml.CPhase(weights, wires=[0,4])
return qml.expval(qml.PauliZ(wires=4))
class MyDenseLayer(qml.qnn.KerasLayer):
def _quanv(self, image, weights):
output_array = np.zeros((31, 31))
r = image[:,:,0]
g = image[:,:,1]
b = image[:,:,2]
for j in range(0, 31, 1):
for k in range(0, 31, 1):
result_qn = self.qnode(
[
r[j, k],
r[j, k + 1],
r[j + 1, k],
r[j + 1, k + 1],
g[j, k],
g[j, k + 1],
g[j + 1, k],
g[j + 1, k + 1],
b[j, k],
b[j, k + 1],
b[j + 1, k],
b[j + 1, k + 1]
], weights
)
output_array[j, k] = result_qn
return output_array
def _evaluate_qnode(self, x):
batch_round = x.shape[0]
res_list = []
q1 = (1.0 * w for k, w in self.qnode_weights.items())
for i in range(batch_round):
image = x[i]
res_list.append(self._quanv(image, q1))
res = tf.constant(res_list)
return res
def call(self, inputs):
results = self._evaluate_qnode(inputs)
return results
weight_shapes = {"weights": (5)}
def MyModel():
qlayer = MyDenseLayer(circuit, weight_shapes, output_dim=None)
clayer_1 = tf.keras.layers.Flatten()
clayer_2 = tf.keras.layers.Dense(100, activation="softmax")
clayer_3 = tf.keras.layers.Dense(10, activation="softmax")
model = tf.keras.models.Sequential([qlayer, clayer_1, clayer_2, clayer_3])
model.compile(
optimizer='adam',
loss="categorical_crossentropy",
metrics=["accuracy"],
)
return model
q_model = MyModel()
q_history = q_model.fit(
x_train,
y_train,
validation_data=(x_val, y_val),
batch_size=1,
epochs=30,
verbose=2,
)
Thanks in advance.