Simple xOr Quantum to Keras

Hi @jerteach,

As for encoding the XOR function, there are multiple ways of how a circuit could be implemented. A fairly simple approach could be to prepare 2 qubits in the computational basis, apply the CNOT gate with wire 0 being the control and wire 1 being the target. Then, we’d consider the measurement outcome of wire 1 in the computational basis.

import pennylane as qml

dev = qml.device('default.qubit', wires=2, analytic=True)

@qml.qnode(dev)
def circuit(x=None, y=None):
    qml.BasisState(np.array([x,y]), wires=[0,1])
    qml.CNOT(wires=[0,1])
    return qml.probs(wires=[1])

# Get the probability of the first wire being in state 1
print(circuit(x=0,y=0)[1])
print(circuit(x=0,y=1)[1])
print(circuit(x=1,y=0)[1])
print(circuit(x=1,y=1)[1])

0.0
1.0
1.0
0.0

Note: the first element of the output array is the probability of the state on wire 1 being in the zero state, while the second element is the probability of wire 1 being in state 1.

In order to create a variational circuit, the basis state preparation could be done using rotation gates that are equivalent to flipping a qubit (i.e., PauliX). Essentially parameters to these rotation gates would have to be learnt. Note that there would still be subtleties to work out, e.g., when defining the exact cost function that allows finding the correct parameters.


As for the Keras integration, linking the KerasLayer documentation including examples (most probably you’ve come across it before).

Hope this helps further!