ValueError: No gradients provided for any variable: (['keras_1/weights:0', 'dense_2/kernel:0', 'dense_2/bias:0'],)

Hi, I am trying to use hybrid version with tf keras layers for a classification. I am using 4 qubits to encode 16 features. If i replace qnode layer with dense tf. It works fine. Else it gives an error. i am beginner in using pennylane. Can you please help me in it.

n_qubits = 4
num_layers = 1
data_dimension = 2

dev = qml.device(“default.qubit”, wires = n_qubits)

@qml.qnode(dev, interface=“tf”, diff_method=“backprop”)
def circuit(inputs, weights):
‘’’ Quantum QVC Circuit’‘’

  # Splits need to be done through the tensorflow interface
weights_each_layer = tf.split(weights, num_or_size_splits=num_layers, axis=0)

  # Input normalization
inputs_1 = inputs / p_np.sqrt(max(p_np.sum(inputs ** 2, axis=-1), 0.001))

for i, W in enumerate(weights):
    # Data re-uploading technique
    if i % 2 == 0:
          MottonenStatePreparation(inputs_1, wires = range(n_qubits))

    # Neural network layer
    StronglyEntanglingLayers(weights_each_layer[i], wires=range(n_qubits))

  # Measurement return
return [qml.expval(qml.PauliZ(i)) for i in range(n_qubits)] 

def create_keras_model():

n_qubits = 4
num_layers = 1
data_dimension = 2

weight_shapes = {"weights": (num_layers,n_qubits)}
print(weight_shapes)

# Model 
tf.keras.backend.set_floatx('float64')

input_m = tf.keras.layers.Input(shape=(2 ** n_qubits,), name = "input_0")
keras_1 = qml.qnn.KerasLayer(circuit, weight_shapes, output_dim=n_qubits, name = "keras_1")(input_m)

#output1 = tf.keras.layers.Dense(data_dimension, name = "dense_1")(input_m)

output = tf.keras.layers.Dense(data_dimension, activation='softmax', name = "dense_2")(keras_1)

# Model creation

inputs=p_np.random.uniform(size=(1,4), requires_grad=True)

model = tf.keras.Model(inputs=[input_m], outputs=[output], name="quantum_model")


return model

loss=tf.keras.losses.SparseCategoricalCrossentropy(),

metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]

keras_model = create_keras_model()

ValueError: No gradients provided for any variable: ([‘keras_1/weights:0’, ‘dense_2/kernel:0’, ‘dense_2/bias:0’],). Provided grads_and_vars is ((None, <tf.Variable ‘keras_1/weights:0’ shape=(1, 4) dtype=float64>), (None, <tf.Variable ‘dense_2/kernel:0’ shape=(4, 2) dtype=float64>), (None, <tf.Variable ‘dense_2/bias:0’ shape=(2,) dtype=float64>)).

Hi @Mandeep,

Thank you for your question! I’m taking a look at it and will be back soon with an answer.

Hi @Mandeep,

The code you shared works for me. Could you please post the output of qml.about()?

I’m also not sure that I understand your question. What line do you change (and how) so that you get or not the error?

Finally, you might find this demo on turning qnodes into Keras layers very useful.

Please let me know if you have any questions!