Turning quantum nodes into Keras Layers


In the ““Turning quantum nodes into Keras Layers””, the FINAL layer is

layer_2 = tf.keras.layers.Dense(2, activation="softmax")

Instead i would like to use

layer_2 = tf.keras.layers.Dense(1, activation=“sigmoid”)

so the previous quantum layer should have quantum circuit:

    def circuit(weights, x=None):
        AngleEmbedding(x, wires = range(n_qubits))
        StronglyEntanglingLayers(weights, wires = range(n_qubits))
        return qml.expval(qml.PauliZ(0))


   def qnode(inputs, weights):
    qml.templates.AngleEmbedding(inputs, wires=range(n_qubits))
    qml.templates.StronglyEntanglingLayers(weights, wires=range(n_qubits))
    return [qml.expval(qml.PauliZ(i)) for i in range(n_qubits)]

Thanks in advance! For sigmoid the Second qnode works just fine but i was expecting the first qnode to work.

Hi @NikSchet,

Thank you for your question.

There are two issues with the first QNode you have defined, which is why you are seeing errors. First, the KerasLayer template requires that inputs be named inputs; you can’t use x. Second, the final classical layer is expecting a vector of dimension two, but you have a single scalar as the output of the QNode.

When you fix these issues, you end up with the second QNode, which works!


Juan Miguel

1 Like