Quantum K-Nearest Neighbours
Quantum KNN Base
- class QNeighborsBase(n_neighbors=3, encoding_map=None, quantum_instance=None)[source]
Bases:
qlearnkit.algorithms.quantum_estimator.QuantumEstimator
,abc.ABC
Base class for Nearest Neighbors algorithms
- Parameters
n_neighbors – number of neighbors. It’s the \(k\) parameter of the knn algorithm
encoding_map – map to classical data to quantum states. This class does not impose any constraint on it.
quantum_instance – the quantum instance to set. Can be a
QuantumInstance
or aBackend
Quantum KNeighbours Classifier
- class QKNeighborsClassifier(n_neighbors=3, encoding_map=None, quantum_instance=None)[source]
Bases:
sklearn.base.ClassifierMixin
,qlearnkit.algorithms.qknn.qknn_base.QNeighborsBase
The Quantum K-Nearest Neighbors algorithm for classification
Note
The naming conventions follow the KNeighborsClassifier from sklearn.neighbors
Example
Classify data using the Iris dataset.
import numpy as np from qlearnkit.algorithms import QKNeighborsClassifier from qlearnkit.encodings import AmplitudeEncoding from qiskit import BasicAer from qiskit.utils import QuantumInstance, algorithm_globals from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split seed = 42 algorithm_globals.random_seed = seed quantum_instance = QuantumInstance(BasicAer.get_backend('qasm_simulator'), shots=1024, optimization_level=1, seed_simulator=seed, seed_transpiler=seed) encoding_map = AmplitudeEncoding(n_features=2) # Use iris data set for training and test data X, y = load_iris(return_X_y=True) X = np.asarray([x[0:2] for x, y_ in zip(X, y) if y_ != 2]) y = np.asarray([y_ for x, y_ in zip(X, y) if y_ != 2]) qknn = QKNeighborsClassifier( n_neighbors=3, quantum_instance=quantum_instance, encoding_map=encoding_map ) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=seed) qknn.fit(X_train, y_train) print(f"Testing accuracy: " f"{qknn.score(X_test, y_test):0.2f}")
Testing accuracy: 1.00
Creates a QKNeighborsClassifier Object
- Parameters
n_neighbors – number of neighbors participating in the majority vote
encoding_map – map to classical data to quantum states. This class does not impose any constraint on it.
quantum_instance – the quantum instance to set. Can be a
QuantumInstance
or aBackend
Quantum KNeighbours Regressor
- class QKNeighborsRegressor(n_neighbors=3, encoding_map=None, quantum_instance=None)[source]
Bases:
sklearn.base.RegressorMixin
,qlearnkit.algorithms.qknn.qknn_base.QNeighborsBase
The Quantum K-Nearest Neighbors algorithm for regression
Note
The naming conventions follow the KNeighborsRegressor from sklearn.neighbors
Creates a QKNeighborsClassifier Object
- Parameters
n_neighbors – number of neighbors participating in the majority vote
encoding_map – map to classical data to quantum states. This class does not impose any constraint on it.
quantum_instance – the quantum instance to set. Can be a
QuantumInstance
or aBackend