I am trying to calculate the distance between sets of vectors. To do this I can create a SwapTest circuit (described here on page 34) and encode a feature vector with a U3 gate, then apply H and CSWAP gates to calculate the overlap. When your feature vectors are length 3 this seems fairly easy, as this can be encoded entirely by one U3. Each U3 parameter will represent a feature. I've done this with vectors of length 2, and have used the overlap as a measure to decide which 2 vectors are "closest".

However, what if we add a 4th or 5th or 10th feature? I imagine we could then also use a second qubit, encode the 5 features over two U3 gates. However, I have trouble seeing how to construct the rest of the circuit.

If we take two states, A and B, each with 6 features we could split this over 2 U3 gates each. Do we perform the "normal" SwapTest on each half of each state. Ie, find the overlap of the upper half of A and the upper half of B, then do the same for the lower half? This seems reasonable, but how would I be able to combine this into 1 value I can use to compare to another set of vectors?


You can employ a method described in paper Transformation of quantum states using uniformly controlled rotations. This allows you to prepare arbitrary quantum state. If you have $x$ features, you can encode them into amplitudes of $\log_2 x$ qubits state because $n$ qubits states are described by vectors of length $2^n$.

Just note that in Qiskit the algorithm in the article above is implemented in function initialize, for example:

quantumState = [
    1 / math.sqrt(2) * complex(1, 0),
    1 / 2 * complex(1, 1),]

q = QuantumRegister(1, name = 'q')
c = ClassicalRegister(1, name = 'c')

circuit = QuantumCircuit(q,c)

circuit.initialize(quantumState, [q[0]])

If you have two such states (vector), you can use a swap test for multiqubit states are described by KAJ226 here.

  • $\begingroup$ thanks, that diagram in the link was exactly what I was looking for I think $\endgroup$ – Andrew Feb 26 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.