Manuscript Offprint
arXiv:2610.33739A quantum k-nearest neighbors implementation using magnitude-aware comparisons
Abstract
Much attention has recently been devoted to the k-nearest neighbors (KNN) algorithm as a case study for quantum computing algorithms. Several algorithms have devised methods to compute a similarity metric to solve Quantum KNN (QKNN). This paper presents a practical quantum encoding technique that enables Euclidean distance calculation between vectors with different L2 norms by appending a single component to each vector, then uses it in the QKNN problem. It is arguably simpler to understand and implement than comparable methods and uses fewer qubits. Further, an implementation of this algorithm is provided and is used to benchmark it against a recent Euclidean-distance QKNN method on standard labeled datasets. In addition to demonstrating proper formulation, the results show marked improvement over similar implementations during simulation with realistic noise due to the use of fewer qubits and thus more coherent circuits.
Keywords: Quantum Computing, Machine Learning, NISQ, Data Science
1 Introduction
Machine learning is a popular solution to many otherwise challenging problems spanning various disciplines. A nascent subset of these solutions use quantum computers as an alternate execution medium for well-known machine learning algorithms. Since Shor's solutions to the factoring, discrete-log, and period-finding problems, researchers have proposed several algorithms that could achieve quantum supremacy.
[2] over traditional computers. Quantum computing has shown promising improvements to classical algorithms, including proofs of quadratic [3] and exponential [1] computational speedups. This potential for speeding up classical algorithms provides an impetus to re-invent these algorithms, which were designed for classical computers, into implementations that can be executed on quantum computers. The field of machine learning has not been excluded - significant progress has been made in methods ranging from quantum annealing [4] to convolutional neural networks [5].
Recent advancements in Quantum Machine Learning (QML) include theoretical or practical implementations of quantum Support Vector Machines (SVMs) [6, 7], k-means [8, 9], and Quantum K-Nearest Neighbors (QKNN) [10]. The K-Nearest Neighbors (KNN) algorithm [11], in which test samples are iteratively assigned labels based on their similarity to pre-labeled training samples, has seen significant efforts toward developing a competitive quantum variant. A detailed review will follow in Section 2, but some outstanding issues remain to be addressed in the present literature. QKNN implementations use many metrics to evaluate similarity, including cosine similarity [12–14], Mahalanobis distance [15], and fidelity [16]. Euclidean distance has also been used [17]. Wiebe et al. [10] compute it coherently for normalized vectors, Schuld et al. [18] and Berti et al. [19] estimate it with an interference circuit on unit-norm inputs, Lloyd et al. [20] recover it for unnormalized vectors whose norms are supplied separately, and Zardini et al. [21] append norm-dependent components that roughly double the dimension of each encoded vector. These approaches either discard the magnitudes of the vectors, need the norms as separate inputs, or substantially enlarge the encoded vectors. This report shares the same professional sentiment as Zardini et al. [21] that few published algorithms are practical in the near term.
This report presents a novel approach to QKNN that addresses these concerns and can be implemented on quantum computers without the use of oracles or other such abstractions. It encodes real-valued vectors with different norms by appending a single component to each vector, so that meaningful magnitude comparisons between the original vectors can be retrieved by measuring the quantum state. It improves on previous implementations that use Euclidean distance comparisons by using a much less complicated encoding technique and fewer qubits.
In brief, Section 2 presents relevant background information; Section 3 presents a novel algorithm based on a new quantum encoding technique, along with its basic implementation; Section 4 describes the experimental setup and results; Section 5 provides closing remarks and potential future work.
2.1 Encoding Methods in Quantum Computing
Encoding meaningful values into Gate Based Quantum Computers (GBQCs) is still a topic of active research. The following is a review of three prevalent encoding methods. The first, chronologically and in its simplicity, is binary encoding. Familiarity with representing base 2 numbers in classical computers is assumed. Algorithms such as Grover's [3] use quantum states to represent integers and then apply gates or oracles to solve a problem. Other uses of quantum binary encoding appear in algorithms that implement binary arithmetic on GBQCs, such as this quantum image processing algorithm [22]. However, the operations that emerge from these methods use an impractical quantity of qubits for any quantum computing hardware expected in the remote future due to decoherence [23].
An alternative approach is to encode information in the phase of qubits. This approach enabled Shor to solve his factoring problem [1]. Encoding data in the phase of a qubit leverages useful arithmetic properties, such as the addition of exponents. However, phase encoding and inverse quantum Fourier transform subcircuits add more complexity than necessary for computing Euclidean distance, as it only requires addition and multiplication operations and involves no cyclical components.
The approach described in this paper uses amplitude encoding. Given a unit vector , amplitude encoding can be described by Equation 1, in which and is padded with zeros to length .
As described by Araujo et al. [24], this circuit can be implemented with a series of rotation gates around the y axis. Defined as in Nielsen's book [25], these are known colloquially as gates. The method first generates a tree of angles, as seen in Figure 1.

Fig. 1 An angle tree to encode a vector into the amplitudes of quantum states
Then, these angles are used as inputs to the controlled- gates, as shown in the circuit in Figure 2. To encode an N element vector, classical computations are required to find the N - 1 angles and N - 1 quantum gates are required. In reality, gate decomposition will likely be required to convert these abstract gates, to include the multiple control qubits, to those of the universal gate set available on the quantum hardware used to execute the circuit. There are a variety of decomposition methods available, and each has its own strengths and weaknesses. This article [26] provides a more thorough discussion of the subject.

Fig. 2 A quantum circuit which encodes an 8-element, real-valued vector
Thus, to encode vectors in quantum states, this method would require a circuit depth of and qubits. Additionally, Giovannetti et al. [27] have proposed Quantum Random Access Memory (QRAM) that would be able to accomplish the same in steps. However, it introduces a linear increase in the number of qubits necessary [28] and is still emerging as a practical method of encoding classical data into quantum computers.
2.2 Quantum k-Nearest Neighbors
Given a set of labeled features with labels and a test set of features , KNN aims to provide labels to each element of based on the elements of . This is done iteratively for each element by finding the subset of elements described by Definition (2).
is a relevant similarity metric that is discussed in further detail below. The test feature adopts the label that appears the most frequently in the set of labels corresponding to the elements of the set .
Many metrics have been proposed for the function in the context of QKNN. One method [29] uses a binary adder to find the Hamming distance between input bit strings. This requires an input string register and a difference register of the same size, which quickly becomes inefficient. An image classification QKNN [30] was proposed that used the NEQR [31] encoding to find the Hamming distance between image representations, then used Grover's algorithm [3] to select a minimum difference. Another binary-encoded Hamming distance implementation [32] uses an oracle to perform QAEA [33] to find the features with minimum distances.
Cosine similarity has been a metric commonly used in KNN. It has taken the form of its square modulus, fidelity, in QKNN. The fidelity is defined as in Equation 3.
All of these methods [10, 12–14, 16, 34, 35] apply some form of amplitude encoding, followed by a controlled swap test. This leaves the squared inner product shown in Equation 3.
Whether this calculation is performed on a GBQC or classical computer, this measurement is not appropriate for all applications. If the magnitude is pertinent to the similarity of two vectors, then cosine similarity can produce undesirable results. Consider two vectors, , , such that and .
Now consider that all vectors amplitude-encoded into a quantum computer must have L2 norms of 1. The normalized versions of and become identical, as shown in Equation 4.
The inner product of these vectors will always be unity, as demonstrated in Equation 5.
If , then is approximately with some noise. It may not be desirable to consider to be similar to in this case. Additionally, there are some issues with cosine similarity and normalized Euclidean distance results converging when comparing samples in high-dimensional feature spaces [36].
Another approach [15] encodes a covariance matrix into a gate operator using a Hamiltonian to calculate the Mahalanobis distance between features. It then uses QAEA to find the closest features. Mahalanobis distance can be reduced to Euclidean distance using the identity matrix as the covariance matrix. Zardini et al. [21] propose a metric based on Euclidean distance using two new encoding methods which they call extension and translation. Their approach is similar to the one presented in this report: rather than normalizing input vectors to an L2 norm of 1, they rescale each feature to a fixed range and append norm-dependent components so that every encoded vector has unit norm. However, it uses a complicated conditional encoding scheme in which a vector with N features becomes or components.
2.3 Comparing vectors with different L2 norms
A goal of a few of the algorithms discussed in Section 2.2 is to compute the squared Euclidean distance between two vectors , as defined in Equation 6.
Some of these approaches are able to find a value proportional to it when constrained such that . However, not all preprocessing techniques commonly used in machine learning accomplish this. Min-max scaling, as defined in Equation 7, and z-score scaling, as defined in Equation 8, do not achieve this constraint. is the sample mean and is the standard deviation.
Some preprocessing techniques do scale feature vectors by setting their norms equal to 1. However, this leaves the resulting vectors in a similar situation to the cosine similarity discussed in Section 2.2. Only the feature vector's orientation is considered, but not its magnitude. In fairness, some preprocessing standards exist that first find the min-max or z-score representation and then normalize the vectors to have norms of 1, but these are not used universally as of the time of this writing.
All input vectors must have an norm equal to 1 to encode them into a GBQC. Define as the unit-normalized version of vector such that . A quantum circuit can be created such that the probabilities of measuring certain states are proportional to Euclidean distance between these normalized vectors, as defined in Equation 9. The specifics of the circuit shall be discussed in Section 3.2.
It may appear that this method has successfully found the original Euclidean distance. However, there is a severe limitation to this method. It requires , , as shown graphically in Figure 3.

Fig. 3 Points and normalized as and to fit the encoding constraints of GBQCs.
If , then Equation 10 can be obtained by factoring out the common denominator. Thus, the original Euclidean distance is proportional to the normalized Euclidean distance via the relationship shown in Equation 11.

Fig. 4 To be encoded into a GBQC, the points and must be normalized to and , respectively.
Now consider the case in which . This is shown graphically in Figure 4. Once normalized to meet the constraints of GBQCs, the result still follows from Equation 9. However, the simplification used to obtain Equation 10 cannot be used here. Further, Equation 12 shows that the result cannot be linearly related to the Euclidean distance between the original vectors.
Thus, vectors with different norms cannot be compared directly using any similar technique.
3 Algorithm
The preceding approach is not practical unless all vectors have the same norm - that is, . This is often not the case for applications in science and engineering. Therefore, the vectors under consideration must be modified to exist in the same norm space. Section 3.1 describes a simple, yet novel, encoding method that modifies all input vectors to have the same L2 norm. This allows the use of Equation 11 to recover exact Euclidean distances between the original vectors upon measuring the circuit in Section 3.2. Section 3.3 shows how this method can be used to implement the well-known KNN algorithm.
3.1 Vector Mapping
This section shows that artificially increasing the dimension of the input vectors can allow retrieval of the Euclidean distances between the original vectors after encoding them into a GBQC. Given a vector , select a vector space of size such that , , and . Let a new vector be defined as in Equation 13.
Let the sum of the squares of the artificial elements be defined as in Equation 14. The sole purpose of is to manipulate the value .
Choose the maximum L2 norm of all the vectors in sets U and V, as in Equation 15. The maximum constraint ensures that it is possible to map every , to a vector within the same norm space.
To find , subtract the sum of the squared elements of from the square of the norm as in Equation 16.
A practical choice for the augmented vector would then be the value inserted into the element and the remaining elements set to 0, as shown in Equation 17.

Fig. 5 Artificially modifying a point to map it to the surface of a higher dimensional sphere of radius .
These augmented vectors can then be substituted for the vectors and in the conditional amplitude encoding step described later in Equation 24. Then, all vectors in both sets will have been mapped to the same norm , as depicted graphically by the spaces and in the transformation example in Figure 5.
This method of encoding shall be referred to as map encoding for the remainder of this report. A similar augmentation, which appends to give a set of vectors a common norm, is used classically to reduce maximum inner product search to nearest-neighbor search [37]. Let the map encoding procedure be denoted as the transform with and . Then, let and . With , these vectors must be unit-normalized into and , such that , so that they are eligible to be encoded into a quantum state.
The next section presents a circuit that can find the sum of squared differences presented in Equation 18
Equation 19 is obtained using the same factoring performed in Equation 10,
Equation 19 is further disassembled using the definition in Equation 17 to obtain the squared differences of the elements of and in Equation 20.
If the values of the second term in Equation 20 can be discarded, only the value remains in Equation 21. The next section shows how to obtain a measurement of this value via a GBQC.
3.2 Quantum Euclidean Distance
What follows is a description of a quantum circuit that calculates the Euclidean distance between a test point and all sample points. It builds on the interference circuit of Schuld et al. [18], applied here to map-encoded vectors. First, modify all training set vectors and test set vectors following the procedure described in Section 3.1, creating the augmented training set vectors and test set vectors . For clarity, and and and . For convenience, , , and . All augmented vectors have an norm of . Initialize a circuit with three registers with state in Equation 22. The notation will be used to track the state of each quantum register throughout the circuit.
Apply a Hadamard gate to all registers except the vector data register to produce the state in Equation 23, which puts the remaining registers into an equal superposition and serves as an address register.
With an amplitude encoding unitary as defined in Equation 1, a controlled variant of this unitary is additionally defined as and an anti-controlled variant . When qubit register is in the state , the controlled gate amplitude encodes into qubit register . The anti-controlled gate amplitude encodes into qubit register when qubit register is in the state .
These gates can encode the sets of vectors into the vector data register . The ancillary qubit conditionally encodes the vectors of set when and the test sample when . The address register is used to encode the data in the appropriate states. This results in state in Equation 24.
Finally, apply a Hadamard gate to the ancillary qubit , resulting in state shown in Equation 25. Figure 6 shows the circuit diagram for this entire procedure.

Fig. 6 The quantum circuit to compute Euclidean distance, with the ancillary qubit in the zeroth quantum register, the address register in the first, and the data in the second.
Define the projection . Then, the probabilities of measuring this observable are shown in Equation 26.
To retrieve the Euclidean distances, add the probabilities over the range while discarding the probabilities in range . Then, multiply by to obtain the squared Euclidean distances in Equation 27 to match the relationship described in Equation 21.
3.3 QKNN
This section describes the QKNN algorithm in its entirety. Given the training and test sets and with and label set as described in Section 2.2, perform any desired preprocessing. Then, follow the procedure in Listing 1 to assign labels to the test samples in set . norm_scale is the procedure described in Section 3.1, is the Hadamard gate transform, encode is the gate transform described in Equation 24, execute_circuit is the execution and measurement of the quantum circuit, and assign_label finds the training features with the lowest summed probabilities as described in Equation 2, and returns the associated label that occurs most frequently. The notation as a parameter of a function implies that the function acts on the quantum registers , and of the quantum state . is the cardinality of a set.
Listing 1 QKNN algorithm for a GBQC
1 U', V' = norm_scale(U, V) 2 m = 3 q = 4 5 6 for in U': 7 8 for in V': 9 10 11 measurements = execute_circuit(| ) 12 y_l = \text{assign_label}(\vec{y}, \text{measurements})
The implementation, provided here, uses Qiskit [38] to construct and simulate the quantum circuits. The assign_label function does not need to convert the measurements back into distances or unit vectors to determine which features are most similar. This is because these conversions would consist of multiplying all measurements by the same positive, real number.
3.4 Complexity
Let , , and . We can examine each step of the algorithm to determine the classical computational complexity and the depth and width of the quantum circuit needed to implement the algorithm.
The first step is to determine each element c that maps each vector to the same higher-dimensional surface as described in Section 3.1. This requires computations.
Currently, amplitude encoding one vector with N elements takes gates. With Q vectors to encode, this would take gates [24]. This process would theoretically take gates with QRAM. Hadamard gates can be applied in constant depth, .
Once the circuit is executed and the state counts are measured, applications may measure one quantum state or all quantum states. If all states are desired, this requires measuring all differences. However, if the results are indexed as needed, each lookup can be performed in steps.
The entire circuit then has a depth of , or if QRAM is available, with a classical computational complexity of for the setup. Each circuit requires 1 ancillary qubit, qubits to create address registers for the vectors in , and qubits to encode each vector in . This results in a circuit of width . circuits must be executed to run the QKNN algorithm.
Table 1 shows a comparison of circuit width, circuit depth, and the number of circuits required to complete the algorithm between a number of QKNN implementations. We use the QRAM-encoded complexities to be consistent with those reported by other papers. is either or as defined by Zardini et al. [21], depending on the encoding method.
| Author | Metric | Circuit Depth | Circuit Width | Circuits |
|---|---|---|---|---|
| Fastovets [39] | Fidelity | QR | ||
| Hai [34] | Fidelity | QR | ||
| Afham [12] | Fidelity | R | ||
| Ruan [29] | Hamming | R | ||
| Zardini [21] | Euclidean | R | ||
| This paper | Euclidean | R |
Table 1 A comparison of circuit depth and width between quantum KNN algorithms
4 Experiments
4.1 Hardware
All experiments were executed on Intel® Xeon® Gold 6148 CPUs at 2.4GHz with 384GB of RAM, provided by Old Dominion University's Wahab high-performance computing cluster. Quantum computers were not used because of their current limited capabilities and availability to the public.
4.2 Datasets
In an effort to provide an accurate comparison with relevant methods, we used the same datasets from the UCI Machine Learning Repository that Zardini et al. [21] used to evaluate the extension and translation methods. The properties of each dataset are shown in Table 2 for quick reference. Although our code is capable of running QKNN on datasets with any number of labels, the datasets used only had binary labels because the previous method's [21] code is not set up for multi-class prediction at this time and direct comparison with their results was desired.
To provide the most accurate comparison, this study uses as similar parameters and metrics as possible. A -fold cross-validation setup was used to split the datasets
| Dataset | Classes | Size | Features |
|---|---|---|---|
| Iris - setosa & versicolor | 2 | 100 | 4 |
| Iris - setosa & virginica | 2 | 100 | 4 |
| Iris - versicolor & virginica | 2 | 100 | 4 |
| Transfusion | 2 | 748 | 4 |
| Vertebral column | 2 | 310 | 6 |
| Ecoli - cp & im | 2 | 220 | 7 |
| Glass - 1 & 2 | 2 | 146 | 9 |
| Breast cancer | 2 | 116 | 9 |
Table 2 Datasets provided by UCI
into test and training sets before running the algorithm. The number of folds chosen was 5 - a default parameter in most machine learning training pipelines. The values of the KNN algorithm for this experiment were set to 3, 5, 7, and 9. This value is not to be confused with the in -fold cross-validation, as the number of folds is 5 for the entirety of this report. The same k-fold seed was used for all experiments, ensuring that all implementations were provided with the same sets of training and test features. Each data point in the results provided in the following sections represents the average of the results over all folds.
4.3 Execution
Two experiments were performed to assess the performance of the QKNN algorithm. Both experiments used a statevector simulator to evolve the quantum state to the desired Euclidean distance used in the KNN algorithm. The first experiment calculated the Euclidean distance using Qiskit's StatevectorSimulator to perform an ideal statevector simulation without noise. The second experiment used a realistic noise model based on the historical performance of IBM's Guadalupe Falcon r4P quantum processor via the FakeGuadalupeV2 and AerSimulator APIs provided by Qiskit. This mode introduces a restriction of the resolution of the measurements by running the circuit only a given number of times - a quantity commonly referred to as shots. Both methods were compared against the KNN algorithm using traditional binary arithmetic to calculate the Euclidean distances, which we hereafter refer to as classical KNN.
4.4 Metrics
The accuracy, Jaccard Index (JI), and Average JI (AJI) were recorded for every experiment. If is the set of actual nearest neighbor features found using classical computation and is the set of predicted nearest neighbor features, then the is defined as in Equation 28.
The AJI is computed by iteratively computing the for the set of most similar features, up through the value, as shown in Equation 29. and are the subsets of and , respectively, containing the most similar features to the test feature.
4.5 Results
4.5.1 Algorithm Performance
The results of the experiments are publicly available here.
| Experiment | k=3 | k=5 | k=7 | k=9 | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Acc | JI | AJI | Acc | JI | AJI | Acc | JI | AJI | Acc | JI | AJI | |
| Setosa-Versicolor | 0.000 | 0.993 | 0.993 | 0.000 | 0.988 | 0.989 | 0.000 | 0.987 | 0.990 | 0.000 | 0.986 | 0.989 |
| Setosa-Virginica | 0.000 | 0.997 | 0.994 | 0.001 | 0.988 | 0.992 | 0.000 | 0.989 | 0.992 | 0.001 | 0.984 | 0.990 |
| Versicolor-Virginica | 0.000 | 0.973 | 0.974 | 0.000 | 0.972 | 0.973 | 0.000 | 0.969 | 0.973 | 0.001 | 0.969 | 0.972 |
| Transfusion | 0.001 | 0.973 | 0.953 | 0.003 | 0.984 | 0.966 | 0.003 | 0.990 | 0.971 | 0.003 | 0.989 | 0.974 |
| Vertebral Column | 0.001 | 0.991 | 0.993 | 0.003 | 0.986 | 0.991 | 0.000 | 0.982 | 0.989 | 0.000 | 0.977 | 0.985 |
| Ecoli | 0.001 | 0.997 | 0.994 | 0.000 | 0.996 | 0.995 | 0.000 | 0.997 | 0.996 | 0.000 | 0.998 | 0.996 |
| Glass | 0.034 | 0.934 | 0.926 | 0.017 | 0.932 | 0.921 | 0.027 | 0.926 | 0.927 | 0.010 | 0.925 | 0.926 |
| Breast Cancer | 0.000 | 0.991 | 0.992 | 0.000 | 0.995 | 0.995 | 0.000 | 0.994 | 0.995 | 0.000 | 0.994 | 0.995 |
Table 3 The mean difference in accuracy ( Acc) between the classical KNN computation and the ideal statevector QKNN simulation with its standard deviation, and the mean Jaccard Index (JI) and Average JI (AJI) with standard deviation using the KNN results computed via binary arithmetic as truth.
The results in Table 3 compare the performance of QKNN using map-encoded data on Qiskit's [38] StatevectorSimulator to the ground truth of KNN performed using only traditional binary arithmetic. It shows the mean difference in accuracy, mean JI, and mean AJI across all 5 cross-validation folds for each dataset with their standard deviation. Besides a few exceptions from the glass dataset, the accuracy is effectively the same as the classical result and the JI and AJI are all nearly unity. This supports the conclusion that the map encoding method accurately computes Euclidean distance. This satisfies the first goal of this algorithm.
The edge cases can be attributed to the high sensitivity of some of the datasets, in which small differences in computation result in a different label for a test feature. The statevector result is implemented via the product of many matrices, while the classical result is obtained through relatively few arithmetic operations. The large number of operations in the statevector solution increases computational error propagation, resulting in slightly different results than the classical solution.
The algorithm was also run on a more realistic backend - the AerSimulator from Qiskit [38] using a statevector simulation with IBMQ's Guadalupe as the noise model. This backend adds noise to generate a more accurate representation of what running

(a)
(b)
(c)
Fig. 7 The mean accuracy (7a), JI (7b), and AJI (7c) of the map encoding QKNN algorithm executed on Qiskit's ideal StatevectorSimulator backend vs the same algorithm executed on Qiskit's AerSimulator backend with realistic noise.
this experiment on a real quantum computer would be like. All runs were performed with 1024 shots. As seen in Figure 7, the performance of the Aer simulation is significantly worse than that of the nearly ideal statevector backend. With a measurement resolution as coarse as , this poor performance is expected from this low-shots simulation. Ultimately, these shots must be distributed among the number of possible distinct states in the circuit. Using the definitions from Section 3.4, this is in our circuit.
4.5.2 Comparison with Leading Algorithm

(a)
(b)
(c)
Fig. 8 The mean accuracy (8a), JI (8b), and AJI (8c) of simulated QKNN using the map encoding technique compared to the extension encoding technique [21].
The map encoding technique is compared to the extension encoding technique [21] in Figure 8. Since the accuracy metric is largely dependent on the underlying KNN algorithm, the more relevant metrics are the JI and AJI. These metrics describe how closely the quantum results mirror the classical results. As such, it is clear that the map encoding technique replicates the classical KNN much better than the extension encoding technique in a realistic simulation.
There could be a few possible explanations for the difference in performance. While both methods used Qiskit's AerSimulator, minor differences in implementation could explain some variations. However, the result of these differences is expected to be minimal. A more plausible explanation for the large difference in performance is the circuit width. Our method uses fewer qubits, which allows the KNN step to make much finer label selections for test samples.
4.5.3 Performance with More Shots
It is expected that the integrity of the quantum result with respect to the classical result increases as the number of shots increases because the resolution of the measurement is inversely proportional to the number of shots. To study this, the map-encoded QKNN was executed on Qiskit's [38] AerSimulator with increasing shots. The results can be viewed in Figure 9. As expected, the AJI increases as shots increase, providing evidence for the claim of positive correlation between shots and integrity. It is worth noting that the standard deviation first increases and then decreases. This indicates that the algorithm consistently underperforms at lower shot counts due to low fidelity, reaches a point at which the results become meaningful to the KNN algorithm, and then becomes more reliable with increasing shots.

Fig. 9 The effect of increasing the number of circuit executions and measurements (shots) on the Average Jaccard Index
5 Conclusions and Future Work
This report described a practical QKNN implementation that used a new map encoding technique to load data into quantum computing hardware. This novel technique allows for efficient comparison of sets of vectors with different norm values. This algorithm required fewer qubits than the extension and translation encoding [21]. It is less complex to implement and arguably easier to understand than these other methods. It also computes the true Euclidean distance, which can be useful in contexts with geometrical implications. The realization of QRAM in the future would considerably decrease the circuit depth and execution speed. It would also increase fidelity due to less decoherence [23].
An implementation of this algorithm has been provided in a public repo, along with the performance results. It has been shown in Section 4.5.1 that the implementation accurately models the classical implementation. In Section 4.5.2, this algorithm demonstrated superior performance to the algorithm presented in [21] under similar operating conditions.
Regarding future applications of this method, several use cases are immediately attractive. For example, this algorithm would be much better suited to the k-means algorithm [40], as it can store the distances between all centroids and all features in the same superposition of states. Using KNN as a case study for map encoding was due to the larger volume and higher quality of the publications available on QKNN. This allowed for a more relevant evaluation of the new algorithm, the success of which can now be applied to other applications.
6 Funding
This research was performed without the receipt of grants or any other funding.
References
[1] Shor, P.W.: Polynomial-time algorithms for prime factorization and discrete logarithms on a quantum computer. SIAM Rev. 41, 303–332 (1999)
[2] Preskill, J.: Quantum computing and the entanglement frontier. arXiv:1203.5813 (2012)
[3] Grover, L.K.: Quantum mechanics helps in searching for a needle in a haystack. Physical Review Letters 79, 325–328 (1997)
[4] Venturelli, D., Kondratyev, A.: Reverse quantum annealing approach to portfolio optimization problems. Quantum Machine Intelligence 1, 17–30 (2018)
[5] Hur, T., Kim, L.Y., Park, D.K.: Quantum convolutional neural network for classical data classification. Quantum Machine Intelligence 4 (2021)
[6] Simon, L., Radons, M.: On neural quantum support vector machines. Quantum Mach. Intell. 6, 3 (2023)
[7] Mohanty, N., Behera, B.K., Ferrie, C.: Solving the vehicle routing problem via quantum support vector machines. Quantum Mach. Intell. 6, 34 (2023)
[8] Wu, Z., Song, T., Zhang, Y.: Quantum k-means algorithm based on manhattan distance. Quantum Information Processing 21 (2021)
[9] Ohno, H.: A quantum algorithm of k-means toward practical use. Quantum Information Processing 21 (2022)
[10] Wiebe, N., Kapoor, A., Svore, K.M.: Quantum nearest-neighbor algorithms for machine learning. Quantum Information & Computation 15, 318–358 (2014)
[11] Fix, E.: Discriminatory analysis: nonparametric discrimination, consistency properties. International Statistical Review 57, 238–247 (1985)
[12] Afham, Basheer, A., Goyal, S.K.: Quantum k-nearest neighbor machine learning algorithm. arXiv: Quantum Physics (2020)
[13] Luna-Márquez, D.C., Pinto-Elías, R., Pérez-Becerra, T., Salazar, A.M., González-Franco, N., Fuentes-Pacheco, J.: knn classification using hausdorff metric with quantum-based euclidean distance. Quantum Mach. Intell. 7, 54 (2025)
[14] Maldonado-Romo, A., Montiel-Pérez, J.Y., Onofre, V., Maldonado-Romo, J., Sossa-Azuela, J.H.: Quantum k-nearest neighbors: Utilizing qram and swap-test techniques for enhanced performance. Mathematics (2024)
[15] Gao, L.-Z., Lu, C.-Y., Guo, G., Zhang, X., Lin, S.: Quantum k-nearest neighbors classification algorithm based on mahalanobis distance. In: Frontiers of Physics (2022). https://api.semanticscholar.org/CorpusID:253069511
[16] Ma, Y., Song, H., Zhang, J.: Quantum algorithm for k-nearest neighbors classification based on the categorical tensor network states. International Journal of Theoretical Physics 60, 1164–1174 (2021)
[17] Yu, K., Guo, G.-D., Li, J., Lin, S.: Quantum algorithms for similarity measurement based on euclidean distance. International Journal of Theoretical Physics 59 (2020) https://doi.org/10.1007/s10773-020-04567-1
[18] Schuld, M., Fingerhuth, M., Petruccione, F.: Implementing a distance-based classifier with a quantum interference circuit. Europhysics Letters 119, 60002 (2017) https://doi.org/10.1209/0295-5075/119/60002
[19] Berti, A., Bernasconi, A., Del Corso, G.M., Guidotti, R.: The role of encodings and distance metrics for the quantum nearest neighbor. Quantum Mach. Intell. 6, 62 (2024) https://doi.org/10.1007/s42484-024-00197-6
[20] Lloyd, S., Mohseni, M., Rebentrost, P.: Quantum algorithms for supervised and unsupervised machine learning. arXiv:1307.0411 (2013)
[21] Zardini, E., Blanzieri, E., Pastorello, D.: A quantum k-nearest neighbors algorithm based on the euclidean distance estimation. Quantum Mach. Intell. 6, 23 (2023)
[22] Yuan, S., Mao, X., Zhou, J., Wang, X.: Quantum image filtering in the spatial domain. International Journal of Theoretical Physics 56, 2495–2511 (2017)
[23] Chuang, I.L., Laflamme, R., Shor, P.W., Zurek, W.H.: Quantum computers, factoring, and decoherence. Science 270(5242), 1633–1635 (1995) https://doi.org/10.1126/science.270.5242.1633 https://www.science.org/doi/pdf/10.1126/science.270.5242.1633
[24] Araujo, I.F., Park, D.K., Petruccione, F., Silva, A.J.: A divide-and-conquer algorithm for quantum state preparation. Scientific Reports 11 (2020)
[25] Nielsen, M.A., Chuang, I.L.: Quantum computation and quantum information (10th anniversary edition). (2011). https://api.semanticscholar.org/CorpusID:263408726
[26] Zindorf, B., Bose, S.: Efficient implementation of multicontrolled quantum gates. Physical Review Applied (2024)
[27] Giovannetti, V., Lloyd, S., Maccone, L.: Quantum random access memory. Physical review letters 100 16, 160501 (2007)
[28] Phalak, K., Chatterjee, A., Ghosh, S.: Quantum random access memory for dummies. Sensors (Basel, Switzerland) 23 (2023)
[29] Ruan, Y., Xue, X., Liu, H., Tan, J., Li, X.: Quantum algorithm for k-nearest neighbors classification based on the metric of hamming distance. International Journal of Theoretical Physics 56, 3496–3507 (2017)
[30] Zhou, N., Liu, X., Chen, Y.-L., Du, N.: Quantum k-nearest-neighbor image classification algorithm based on k-1 transform. International Journal of Theoretical Physics 60, 1209–1224 (2021)
[31] Zhang, Y., Lu, K., Gao, Y., Wang, M.: Neqr: a novel enhanced quantum representation of digital images. Quantum Information Processing 12, 2833–2860 (2013)
[32] Li, J., Lin, S., Yu, K.-h., Guo, G.: Quantum k-nearest neighbor classification algorithm based on hamming distance. Quantum Information Processing 21 (2021)
[33] Brassard, G., Høyer, P., Mosca, M., Montreal, A., Aarhus, B.U., Waterloo, C.U.: Quantum amplitude amplification and estimation. arXiv: Quantum Physics (2000)
[34] Hai, V.T., Chuong, P.H., Bao, P.T.: New approach of knn algorithm in quantum computing based on new design of quantum circuits. Informatica (Slovenia) 46 (2022)
[35] Ronggon, A.A., Hossain, T., Alahmadi, T.J., Moni, M.A.: Qknn: Noise-resilient quantum knn algorithm for high-accuracy classification. Advanced Quantum Technologies 9 (2026)
[36] Tessari, F., Hogan, N.: Surpassing cosine similarity for multidimensional comparisons: Dimension insensitive euclidean metric (diem). ArXiv abs/2407.08623 (2024)
[37] Bachrach, Y., Finkelstein, Y., Gilad-Bachrach, R., Katzir, L., Koenigstein, N., Nice, N., Paquet, U.: Speeding up the Xbox recommender system using a Euclidean transformation for inner-product spaces. In: Proceedings of the 8th ACM Conference on Recommender Systems, pp. 257–264 (2014). https://doi.org/10.1145/2645710.2645741
[38] Qiskit contributors: Qiskit: An Open-source Framework for Quantum Computing (2023). https://doi.org/10.5281/zenodo.2573505
[39] Fastovets, D.V., Bogdanov, Y.I., Bantysh, B.I., Lukichev, V.F.: Machine learning methods in quantum computing theory. In: International Conference on Micro- and Nano-Electronics (2019). https://api.semanticscholar.org/CorpusID:88499935
[40] Yadav, J., Sharma, M.: A review of k-mean algorithm. (2013). https://api.semanticscholar.org/CorpusID:61532973