Welcome to dc-qiskit-qml’s documentation!

Release

0.0.3

Date

Oct 18, 2019

qiskit is an open-source compilation framework capable of targeting various types of hardware and a high-performance quantum computer simulator with emulation capabilities and various compiler plug-ins.

This library implements so far one quantum machine learning classifier which has been introduced by F.Petruccione, M. Schuld and M. Fingerhuth (http://stacks.iop.org/0295-5075/119/i=6/a=60002). Athough this is the only classifier implemented so far, this library is to be used as a repository for more classifiers using qiskit as a background framework.

Features

  • Distance & Majority based Hadamard-gate classifier

    • Generic real valued vector space input data (slow)

    • Binary valued vector space input data (faster)

    • Feature map pre-processing for non-linear classification

Contents

Installation

This library requires Python version 3.5 and above, as well as qiskit. Installation of this library, as well as all dependencies, can be done using pip:

$ python -m pip install dc_qiskit_qml

To test that the algorithms are working correctly you can run

$ make test

Getting started

You can check out the classifier as follows

import numpy as np
from sklearn.datasets import load_iris
from sklearn.preprocessing import StandardScaler, Normalizer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline

import qiskit

from dc_qiskit_qml.feature_maps import NormedAmplitudeEncoding
from dc_qiskit_qml.distance_based.hadamard import QmlHadamardNeighborClassifier
from dc_qiskit_qml.distance_based.hadamard.state import QmlGenericStateCircuitBuilder
from dc_qiskit_qml.distance_based.hadamard.state.sparsevector import MöttönenStatePreparation

X, y = load_iris(True)
# Only the first two features and only get two labels
# This is a toy example!
X = np.asarray([x[0:2] for x, yy in zip(X, y) if yy != 2])
y = np.asarray([yy for x, yy in zip(X, y) if yy != 2])

preprocessing_pipeline = Pipeline([
    ('scaler',  StandardScaler()),
    ('l2norm', Normalizer(norm='l2', copy=True))
])
X = preprocessing_pipeline.fit_transform(X, y)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.10)

# Using the generic wave function (state vector) routine using the 'Möttönen'
# state preparation algorithm
initial_state_builder = QmlGenericStateCircuitBuilder(MöttönenStatePreparation())

# The normed amplitude encoding ensures that the data is normalized
# This is a somewhat unnecessary step as above we do that already
feature_map = NormedAmplitudeEncoding()

execution_backend: BaseBackend = qiskit.Aer.get_backend('qasm_simulator')
qml = QmlHadamardNeighborClassifier(backend=execution_backend,
                                    shots=8192,
                                    classifier_circuit_factory=initial_state_builder,
                                    feature_map=feature_map)

qml.fit(X_train, y_train)
prediction = qml.predict(X_test)

"Test Accuracy: {}".format(
    sum([1 if p == t else 0 for p, t in zip(prediction, y_test)])/len(prediction)
)

prediction_train = qml.predict(X_train)
"Train Accuracy: {}".format(
    sum([1 if p == t else 0 for p, t in zip(prediction_train, y_train)])/len(prediction_train)
)

The details are a bit more involved as to how this works and the classifier can be configured with a circuit factory or a feature map.

Support

If you are having issues, please let us know by posting the issue on our Github issue tracker.

License

The data cybernetics qiskit algorithms plugin is free and open source, released under the Apache License, Version 2.0.

Tutorials

TODO

Code Details

TODO

QmlHadamardNeighborClassifier

Implementing the Hadamard distance & majority based classifier (http://stacks.iop.org/0295-5075/119/i=6/a=60002).

QmlHadamardNeighborClassifier

The Hadamard distance & majority based classifier implementing sci-kit learn’s mechanism of fit/predict

AsyncPredictJob

Wrapper for a qiskit BaseJob and classification experiments

More details:

QmlHadamardNeighborClassifier

class dc_qiskit_qml.distance_based.hadamard._QmlHadamardNeighborClassifier.QmlHadamardNeighborClassifier(encoding_map, classifier_circuit_factory, backend, shots=1024, coupling_map=None, basis_gates=None, theta=None, options=None)[source]

The Hadamard distance & majority based classifier implementing sci-kit learn’s mechanism of fit/predict

predict_qasm_only(X)[source]

Instead of predicting straight away returns the Qobj, the command object for executing the experiment

Parameters

X – array like, unclassified input set

Returns

the compiled Qobj ready for execution!

predict(X, do_async=False)[source]

Predict the class labels of the unclassified input set!

Parameters
  • X – array like, the unclassified input set

  • do_async – if True return a wrapped job, it is handy for reading out the prediction results from a real processor

Returns

depending on the input either the prediction on class labels or a wrapper object for an async task

predict_async(X)[source]

Same as predict(self, X, do_aysnc=True)

Parameters

X – unclassified input set

Returns

Wrapper for a Job

predict_sync(X)[source]

Same as predict(self, X, do_aysnc=False)

Parameters

X – unclassified input set

Returns

List of class labels

static p_acc_theory(X_train, y_train, X_test)[source]

Computes the branch acceptance probability

Parameters
  • X_train – training set (list of numpy arrays shape (n,1)

  • y_train – Class labels of training set

  • X_test – Unclassified input vector (shape (n,1))

Returns

branch acceptance probability P_acc

static p_label_theory(X_train, y_train, X_test, label)[source]

Computes the label’s probability

Parameters
  • X_train – training set

  • y_train – Class labels of training set

  • X_test – Unclassified input vector (shape: (n,1))

  • label – The label to test

Returns

probability of class label

AsyncPredictJob

class dc_qiskit_qml.distance_based.hadamard._QmlHadamardNeighborClassifier.AsyncPredictJob(input, job, qml)[source]

Wrapper for a qiskit BaseJob and classification experiments

predict_result()[source]

Returns the prediction result if it exists

Returns

a list of class labels or None

QmlStateCircuitBuilder

This is the abstract base class to implement a custom state circuit builder which takes the classification training data samples and labels and one to be classified sample and outputs the circuit that creates the necessary quantum state than then can be used to apply the QmlHadamardNeighborClassifier.

QmlStateCircuitBuilder

Interface class for creating a quantum circuit from a sparse quantum state vector.

QmlStateCircuitBuilder

class dc_qiskit_qml.distance_based.hadamard.state._QmlStateCircuitBuilder.QmlStateCircuitBuilder[source]

Interface class for creating a quantum circuit from a sparse quantum state vector.

abstract build_circuit(circuit_name, X_train, y_train, X_input)[source]

Build a circuit that encodes the training (samples/labels) and input data sets into a quantum circuit

Parameters
  • circuit_name – The name of the quantum circuit

  • X_train – The training data set

  • y_train – the training class label data set

  • X_input – the unclassified input data vector

Returns

The circuit containing the gates to encode the input data

abstract is_classifier_branch(branch_value)[source]

As each state preparation algorithm uses a unique layout. The classifier has the correct classification probabilities only on the correct branch of the ancilla qubit. However each state preparation may have different methods making it necessary to query specific logic to assess what value must be given after the branch qubit measurement.

Parameters

branch_value – The measurement of the branch

Returns

True is the branch is containing the classification, False if not

QmlGenericStateCircuitBuilder

The generic state circuit builder classically computes the necessary quantum state vector (sparse) and will use a state preparing quantum routine that takes the state vector and creates a circuit. This state preparing quantum routine must implement QmlSparseVectorFactory.

QmlGenericStateCircuitBuilder

From generic training and testing data creates the quantum state vector and applies a quantum algorithm to create a circuit.

QmlGenericStateCircuitBuilder

class dc_qiskit_qml.distance_based.hadamard.state._QmlGenericStateCircuitBuilder.QmlGenericStateCircuitBuilder(state_preparation)[source]

From generic training and testing data creates the quantum state vector and applies a quantum algorithm to create a circuit.

static get_binary_representation(sample_index, sample_label, entry_index, is_input, index_qb_len, label_qb_len, data_qb_len)[source]

Computes the binary representation of the quantum state as str given indices and qubit lengths

Parameters
  • sample_index – the training data sample index

  • sample_label – the training data label

  • entry_index – the data sample vector index

  • is_input – True if the we encode the input instead of the training vector

  • index_qb_len – total qubits needed for the index register

  • label_qb_len – total qubits needed for the label register

  • data_qb_len – total qubits needed for the data register

Returns

binary representation of which the quantum state being addressed

build_circuit(circuit_name, X_train, y_train, X_input)[source]

Build a circuit that encodes the training (samples/labels) and input data sets into a quantum circuit.

It does so by iterating through the training data set with labels and constructs upon sample index and vector position the to be modified amplitude. The state vector is stored into a sparse matrix of shape (n,1) which is stored and can be accessed through get_last_state_vector() for debugging purposes.

Then the routine uses a QmlSparseVectorStatePreparation routine to encode the calculated state vector into a quantum circuit.

Parameters
  • circuit_name – The name of the quantum circuit

  • X_train – The training data set

  • y_train – the training class label data set

  • X_input – the unclassified input data vector

Returns

The circuit containing the gates to encode the input data

is_classifier_branch(branch_value)[source]

As each state preparation algorithm uses a unique layout. Here the QmlSparseVectorFactory is asked how the branch for post selection can be identified.

Parameters

branch_value – The measurement of the branch

Returns

True is the branch is containing the classification, False if not

get_last_state_vector()[source]

From the last call of build_circuit() the computed (sparse) state vector.

Returns

a sparse vector (shape (n,0)) if present

QmlBinaryDataStateCircuitBuilder

QmlBinaryDataStateCircuitBuilder

From binary training and testing data creates the quantum state vector and applies a quantum algorithm to create a circuit.

QmlBinaryDataStateCircuitBuilder

class dc_qiskit_qml.distance_based.hadamard.state._QmlBinaryDataStateCircuitBuilder.QmlBinaryDataStateCircuitBuilder(ccx_factory, do_optimizations=True)[source]

From binary training and testing data creates the quantum state vector and applies a quantum algorithm to create a circuit.

build_circuit(circuit_name, X_train, y_train, X_input)[source]

Build a circuit that encodes the training (samples/labels) and input data sets into a quantum circuit. Sample data must be given as a binary (sparse) vector, i.e. each vector’s entry must be either 0.0 or 1.0. It may also be given already normed to unit length instead of binary.

Parameters
  • circuit_name – The name of the quantum circuit

  • X_train – The training data set

  • y_train – the training class label data set

  • X_input – the unclassified input data vector

Returns

The circuit containing the gates to encode the input data

is_classifier_branch(branch_value)[source]

The branch of quantum state bearing the classification is defined to be 0. This functions checks this.

Parameters

branch_value – The measurement of the branch

Returns

True is the measured branch is 0, False if not

QmlSparseVectorStatePreparation

This is the abstract base class that needs to be implemented for any routine that takes a sparse state vector and encodes it into a quantum circuit that produces this quantum state.

QmlSparseVectorStatePreparation

QmlSparseVectorStatePreparation

class dc_qiskit_qml.distance_based.hadamard.state.sparsevector._QmlSparseVectorStatePreparation.QmlSparseVectorStatePreparation[source]
abstract prepare_state(qc, state_vector)[source]

Given a sparse quantum state apply a quantum algorithm (gates) to the given circuit to produce the desired quantum state.

Parameters
  • qc – the quantum circuit to be used

  • state_vector – the (complex) state vector of unit length to be prepared

Returns

the quantum circuit

abstract is_classifier_branch(branch_value)[source]

The state preparation logic is done in this class, therefore it knows what value the branch measurement must have in order to know if we can get classification numbers.

Parameters

branch_value – the branch measurement value

Returns

True if the branch measurement was 0

MöttönenStatePreparation

MöttönenStatePreparation

MöttönenStatePreparation

class dc_qiskit_qml.distance_based.hadamard.state.sparsevector._MöttönenStatePreparation.MöttönenStatePreparation[source]
prepare_state(qc, state_vector)[source]

Apply the Möttönen state preparation routine on a quantum circuit using the given state vector. The quantum circuit’s quantum registers must be able to hold the state vector. Also it is expected that the registers are initialized to the ground state ´´|0>´´ each.

Parameters
  • qc – the quantum circuit to be used

  • state_vector – the (complex) state vector of unit length to be prepared

Returns

the quantum circuit

is_classifier_branch(branch_value)[source]

The classifier will be directly usable if the branch label is 0.

Parameters

branch_value – the branch measurement value

Returns

True if the branch measurement was 0

CCXFactory

This class is the abstract base class for the multiple-controlled X-gates (short ccx) that are primarily used for binary input data of the classifier.

CCXFactory

Abstract base class for using a multi-ccx gate within the context of the classifier

CCXFactory

class dc_qiskit_qml.distance_based.hadamard.state.cnot._CCXFactory.CCXFactory[source]

Abstract base class for using a multi-ccx gate within the context of the classifier

abstract ccx(qc, conditial_case, control_qubits, tgt)[source]

This method applies to a quantum circuit on the control qubits the desired controlled operation on the target if the quantum state coincides with the (binary representation of the) conditional case.

This abstract method must be implemented in order to be used by the _QmlUniformAmplitudeStateCircuitBuilder and so that the correct state for the classifier can be applied.

Parameters
  • qc – the circuit to apply this operation to

  • conditial_case – an integer whose binary representation signifies the branch to controll on

  • control_qubits – the qubits that hold the desired conditional case

  • tgt – the target to be applied the controlled X gate on

Returns

the circuit after application of the gate

CCXMöttönen

This module implements a CCXFactory to create a multi-controlled X-gate (or NOT gate) to a circuit using the uniform rotations as described by Möttönen et al. (http://dl.acm.org/citation.cfm?id=2011670.2011675).

CCXMöttönen

cc-X gate implemented via the uniform rotation scheme (Möttönen et al.

CCXMöttönen

class dc_qiskit_qml.distance_based.hadamard.state.cnot._CCXMöttönen.CCXMöttönen[source]

cc-X gate implemented via the uniform rotation scheme (Möttönen et al. 2005)

ccx(qc, conditial_case, control_qubits, tgt)[source]

Using the Möttönen uniform rotation, one can create multi-controlled NOT gate (along with other arbitrary rotations). The routine has exponential (w.r.t. number of qubits) gate usage.

Parameters
  • qc – the circuit to apply this operation to

  • conditial_case – an integer whose binary representation signifies the branch to controll on

  • control_qubits – the qubits that hold the desired conditional case

  • tgt – the target to be applied the controlled X gate on

Returns

the circuit after application of the gate

CCXToffoli

This module implements a CCXFactory to create a multi-controlled X-gate (or NOT gate) to a circuit using the Toffoli gate cascade on ancillary qubits described by Nielsen & Chuang (https://doi.org/10.1017/CBO9780511976667). Its advantage is that it doesn’t need expnential gates w.r.t. to the controlled qubit count, however, its downside is that it needs auxiliary qubits. It depends strongly on the use case whether to use this or the algorithm by Möttönen et al. as implemented by CCXMöttönen.

CCXToffoli

cc-X gate implemented via the Toffoli cascade with auxiliary qubits.

CCXToffoli

class dc_qiskit_qml.distance_based.hadamard.state.cnot._CCXToffoli.CCXToffoli[source]

cc-X gate implemented via the Toffoli cascade with auxiliary qubits.

ccx(qc, conditial_case, control_qubits, tgt)[source]

Using the Toffoli gate cascade on auxiliary qubits, one can create multi-controlled NOT gate. The routine needs to add an auxiliary register called `` ccx_ancilla`` which also will be re-used if multiple calls of this routine are done within the same circuit. As the cascade is always ‘undone’, the ancilla register is left to the ground state.

Parameters
  • qc – the circuit to apply this operation to

  • conditial_case – an integer whose binary representation signifies the branch to controll on

  • control_qubits – the qubits that hold the desired conditional case

  • tgt – the target to be applied the controlled X gate on

Returns

the circuit after application of the gate

Indices and tables