Convert Qnode to keras layer and make it trainable error

Hello!
I’ve tried to convert a qnode to a keras layer and to integrate this kerasLayer

to tf.keras.models.Sequential model
I got this error
TypeError: RY: Real scalar parameter expected, got <class 'numpy.ndarray'>. .

@qml.qnode(dev)
def circuit(inputs, conv_params):
    # Encoding of 4 classical input values
    for j in range(4):
        qml.RY(np.pi * inputs[j], wires=j)

    # Random quantum circuit
    RandomLayers(conv_params, wires=list(range(4)))

    # Measurement producing 4 classical output values
    return [qml.expval(qml.PauliZ(j)) for j in range(4)]

qlayer = qml.qnn.KerasLayer(circuit, weight_shapes, output_dim=4)

def MyModel():
    """Initializes and returns a custom Keras model
    which is ready to be trained."""
    model = keras.models.Sequential([
        qlayer,
        keras.layers.Conv2D(64, (3, 3), activation='relu'),
        keras.layers.MaxPooling2D((2, 2)), 
        keras.layers.Conv2D(64, (3, 3), activation='relu'),
        keras.layers.MaxPooling2D((2, 2)),                                                 
        keras.layers.Flatten(),
        keras.layers.Dense(10, activation="softmax")
    ])

    model.compile(
        optimizer='adam',
        loss="sparse_categorical_crossentropy",
        metrics=["accuracy"],
    )
    return model


q_model = MyModel()

q_history = q_model.fit(
    train_images,
    train_labels,
    validation_data=(test_images, test_labels),
    batch_size=4,
    epochs=n_epochs,
    verbose=2,
)

Can anyone help me please!

Hey @FerjaniMY!

This is likely due to how weight_shapes is defined. Something like this should work:

layers = 3
qubits = 4
weight_shapes = {"conv_params": (layers, qubits)}

If not, feel free to share the full code and I can give some feedback.

One thing I noticed from a quick look at MyModel() is that it might not make sense to place qlayer at the start of the model. It expects 4-dimensional data at input and output, so I’d imagine placing the qlayer between keras.layers.Flatten() and keras.layers.Dense() - although you would also need to add an additional keras.layers.Dense(4, ...) layer before qlayer.

Hello @Tom_Bromley ,
Thank you so much for your suggestions !
I solved the problem by using your suggestions and by modifying the batch_size=56 instead of batch_size=4,

1 Like