<jupyter_start><jupyter_text>Quantum Nearest Neighbour: distance based classifier References: * Classifier: Implementing a distance-based classifier with a quantum interference circuit, <NAME> et al 2017 EPL 119 60002  Preparing the data<jupyter_code>import numpy as np
import pandas as pd
iris = pd.read_csv("input_files/iris.data",header=None,names=["f0","f1","f2","f3","class"])
setosa = iris[iris["class"] == "Iris-setosa"].loc[:,["f0","f1","class"]]
# setosa.loc[:,"class"] = -1
setosa["color"] = "Red"
setosa["marker"] = "o"

versicolor = iris[iris["class"] == "Iris-versicolor"].loc[:,["f0","f1","class"]]
# versicolor.loc[:,"class"] = 1
versicolor["color"] = "Blue"
versicolor["marker"] = "x"

virginica = iris[iris["class"] == "Iris-virginica"].loc[:,["f0","f1","class"]]
# virginica.loc[:,"class"] = 1
virginica["color"] = "Green"
virginica["marker"] = "."
data = pd.concat([setosa,versicolor])
# data = pd.concat([versicolor,virginica])
# data = pd.concat([setosa,versicolor,virginica])
import matplotlib.pyplot as plt
plt.scatter(data.to_numpy()[:50,0], data.to_numpy()[:50,1], color="red", marker="o", label="setosa")
plt.scatter(data.to_numpy()[50:100,0], data.to_numpy()[50:100,1], color="blue", marker="x", label="versicolor")

plt.xlabel('sepal length [cm]')
plt.ylabel('sepal width [cm]')
plt.legend(loc='upper left')

plt.show()
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
data.iloc[:,[0,1]] = scaler.fit_transform(data.iloc[:,[0,1]])
plt.scatter(data.to_numpy()[:50,0], data.to_numpy()[:50,1], color="red", marker="o", label="setosa")
plt.scatter(data.to_numpy()[50:100,0], data.to_numpy()[50:100,1], color="blue", marker="x", label="versicolor")

plt.xlabel('sepal length [cm]')
plt.ylabel('sepal width [cm]')
plt.legend(loc='upper left')

plt.show()
def normalize(v):
    norm = np.linalg.norm(v)
    if norm == 0: 
       return v
    return v / norm
for i in data.index:
    v = [data.loc[i,"f0"],data.loc[i,"f1"]]
    v = normalize(v)
    data.loc[i,"f0"], data.loc[i,"f1"] = v[0], v[1]
plt.scatter(data.to_numpy()[:50,0], data.to_numpy()[:50,1], color="red", marker="o", label="setosa")
plt.scatter(data.to_numpy()[50:100,0], data.to_numpy()[50:100,1], color="blue", marker="x", label="versicolor")

plt.xlabel('sepal length [cm]')
plt.ylabel('sepal width [cm]')
plt.legend(loc='upper left')

plt.show()
setosa.head()
# For setosa and versicolor
vectors = data.loc[[33,85,28,56],["f0","f1","class"]]
vectors["label"], vectors["angle"] = ["x0 (t0)","x1 (t1)","x' (x0)","x'' (x1)"], [round(np.pi,3),1.325,4.304,3.036]
vectors

# For versicolor and virginica
# vectors = data.loc[[50,145,53,149],["f0","f1","class"]]
# vectors["label"] = ["t0","t1","x0","x1"]
# vectors
f0 = vectors.columns.get_loc("f0")
f1 = vectors.columns.get_loc("f1")
t0 = np.arctan(vectors.iloc[0,f1] / vectors.iloc[0,f0]) * 2 % (2 * np.pi)
t1 = np.arctan(vectors.iloc[1,f1] / vectors.iloc[1,f0]) * 2 % (2 * np.pi)
x0 = np.arctan(vectors.iloc[2,f1] / vectors.iloc[2,f0]) * 2 % (2 * np.pi)
x1 = np.arctan(vectors.iloc[3,f1] / vectors.iloc[3,f0]) * 2 % (2 * np.pi)<jupyter_output><empty_output><jupyter_text>Building the quantum circuit<jupyter_code>import qiskit
from qiskit import IBMQ
from qiskit import (
    QuantumCircuit,
    QuantumRegister,
    ClassicalRegister,
    execute,
    Aer)
from qiskit.visualization import plot_histogram
# import qiskit.aqua.circuits.gates.controlled_ry_gates
str(1+1+1+1) + ' qubits'
a = QuantumRegister(1,'a')
m = QuantumRegister(1,'m')
i = QuantumRegister(1,'i')
c = QuantumRegister(1,'c')
b = ClassicalRegister(2, 'bit')
circuit = QuantumCircuit(a,m,i,c,b)

circuit.h(a)
circuit.h(m)

circuit.barrier()

circuit.cry(x0,a[0],i[0])
circuit.x(a)

circuit.barrier()

# circuit.ccx(a,m,i)
circuit.mcry(t0,a[:]+m[:],i[0],None)
circuit.x(m)

circuit.barrier()

circuit.mcry(t1,a[:]+m[:],i[0],None)

circuit.barrier()

circuit.cx(m,c)

circuit.barrier()

circuit.h(a)
circuit.measure(a,b[0])
circuit.measure(c,b[1])

circuit.draw(output='mpl')
simulator = Aer.get_backend('qasm_simulator')
job = execute(circuit, simulator, shots=8192)
result = job.result()
counts = result.get_counts(circuit)
print("\nTotal counts are:",counts)
plot_histogram(counts)
goodCounts = {k: counts[k] for k in counts.keys() & {'00', '10'}}
plot_histogram(goodCounts)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.22168396770472895, 'fraction_numerical': 0.04452133794694348, 'mean_word_length': 6.6203866432337435, 'pattern_counts': {'":': 0, '<': 10, '<?xml version=': 0, '>': 10, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '517867', 'license': 'Apache-2.0', 'n_tokens_mistral': 1926, 'n_tokens_neox': 1775, 'n_words': 293, 'path': 'artificial_intelligence/qnn_base.ipynb', 'repo_name': 'visika/qiskit-community-tutorials', 'size': '4338'}