aqmlator.qml module


This module contains the functionalities related to the quantum machine learning.


Copyright 2023 ACK Cyfronet AGH. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


This work was supported by the EuroHPC PL project funded at the Smart Growth Operational Programme 2014-2020, Measure 4.2 under the grant agreement no. POIR.04.02.00-00-D014/20-00.


class aqmlator.qml.QMLModel(wires: int | Sequence[int], *, device: Device | None = None, optimizer: GradientDescentOptimizer | None = None, embedding_method: Type[Operation] | None = None, embedding_kwargs: Dict[str, Any] | None = None, layers: Sequence[Type[Operation]] | None = None, validation_set_size: float = 0.2, rng_seed: int = 42, coupling_map: Sequence[Sequence[int]] | None = None, n_qubit: int | None = None)[source]

Bases: ABC

A boilerplate class, providing an interface for future QML models.

The constructor for the QMLModel class.

Parameters:
  • wires – The wires to use in the VQC or the number of qubits (and wires) used in the VQC.

  • device – A device on which the model should operate.

  • optimizer – The optimizer that will be used in the training. NesterovMomentumOptimizer with default parameters will be used as default.

  • embedding_method – Embedding method of the data. By default - when None is specified - the QMLModel will use AngleEmbedding. See _prepare_default_embedding for parameters details.

  • embedding_kwargs – Keyword arguments for the embedding method. If None are specified the QMLModel will use the default embedding method.

  • layers – Layers to be used in the VQC. The layers will be applied in the given order. A double StronglyEntanglingLayer will be used if None is given.

  • validation_set_size – A part of the training set that will be used for QMLModel validation. It should be from (0, 1).

  • rng_seed – A seed used for random weights initialization.

  • coupling_map – A description of connections between the qubits in the device.

abstractmethod fit(X: Sequence[Sequence[float]] | ndarray[Any, dtype[float64]], y: Sequence[ModelOutput] | None) QMLModel[source]

The model training method.

Parameters:
  • X – The lists of features of the objects that are used during the training.

  • y – A list of classes corresponding to the given lists of features.

Raises:

NotImplementedError – If the method is not implemented.

Returns:

Returns self after training.

seed(new_seed: int) None[source]

Sets up the new seed.

Parameters:

new_seed – New seed to be applied to the model.

class aqmlator.qml.QNNBinaryClassifier(wires: int | Sequence[int], batch_size: int, n_epochs: int = 1, *, device: Device | None = None, optimizer: GradientDescentOptimizer | None = None, embedding_method: Type[Operation] | None = None, embedding_kwargs: Dict[str, Any] | None = None, layers: Sequence[Type[Operation]] | None = None, accuracy_threshold: float = 0.8, initial_weights: Sequence[float] | None = None, rng_seed: int = 42, validation_set_size: float = 0.2, prediction_function: Callable[[Sequence[Sequence[float]]], Sequence[ModelOutput]] | None = None, debug_flag: bool = False, coupling_map: Sequence[Sequence[int]] | None = None, n_qubit: int | None = None)[source]

Bases: ClassifierMixin, QNNModel

This class implements a binary classifier that uses Quantum Neural Networks.

The classifier expects two classes {0, 1}.

The constructor for the QNNModel class.

Parameters:
  • wires – The wires to use in the VQC or the number of qubits (and wires) used in the VQC.

  • batch_size – Size of a batches used during the training.

  • n_epochs – The number of training epochs.

  • device – A device on which the model should operate.

  • optimizer – The optimizer that will be used in the training. NesterovMomentumOptimizer with default parameters will be used as default.

  • embedding_method – Embedding method of the data. By default - when None is specified - the model will use AmplitudeEmbedding. See _prepare_default_embedding for parameters details.

  • embedding_kwargs – Keyword arguments for the embedding method. If none are specified the model will use the default embedding method.

  • layers – Layers to be used in the VQC. The layers will be applied in the given order. A double StronglyEntanglingLayer will be used if None is given.

  • accuracy_threshold – The satisfactory accuracy of the model.

  • initial_weights – The initial weights for the training.

  • rng_seed – A seed used for random weights initialization.

  • validation_set_size – A part of the training set that will be used for model validation. It should be from (0, 1).

  • prediction_function – A prediction function that will be used to process the output of the VQC. If None then the default one (for given model) will be used.

  • debug_flag – A flag informing the model if the training info should be printed to the console or not.

  • coupling_map – A description of connections between the qubits in the device.

class aqmlator.qml.QNNClassifier(wires: int | Sequence[int], n_classes: int, *, binary_classifiers: Sequence[QNNBinaryClassifier] | None = None, batch_size: int = 10, accuracy_threshold: float = 0.8, device: Device | None = None, optimizer: GradientDescentOptimizer | None = None, embedding_method: Type[Operation] | None = None, embedding_kwargs: Dict[str, Any] | None = None, layers: Sequence[Type[Operation]] | None = None, validation_set_size: float = 0.2, rng_seed: int = 42)[source]

Bases: QMLModel, ClassifierMixin

This class implements a quantum classifier based on the multiple binary quantum classifiers.

The constructor for the QuantumClassifier class.

Parameters:
  • wires – The wires to use in the VQC or the number of qubits (and wires) used in the VQC. It will be used in the qml.devices.Device specification.

  • n_classes – The number of classes in the classification task.

  • binary_classifiers – Binary classifiers that will be used in the classification. If None is given, then the QuantumClassifier will produce default binary classifiers.

  • batch_size – Batch size using during binary classifiers fitting.

  • accuracy_threshold – The target minimal accuracy of the classifier. Note that it reflects total accuracy of the classifier, which is lower than accuracy of each binary classifier.

  • device – A device on which the model should operate.

  • optimizer – The optimizer that will be used in the training. NesterovMomentumOptimizer with default parameters will be used as default. It will be used in each of the binary classifiers initialized by QuantumClassifier.

  • embedding_method – Embedding method of the data. By default - when None is specified - the QMLModel will use AngleEmbedding. See _prepare_default_embedding for parameters details. It will be used in each of the binary classifiers initialized by QuantumClassifier.

  • embedding_kwargs – Keyword arguments for the embedding method. If None are specified the QMLModel will use the default embedding method. It will be used in each of the binary classifiers initialized by QuantumClassifier.

  • layers – Layers to be used in the VQC. The layers will be applied in the given order. A double StronglyEntanglingLayer will be used if None is given.

  • validation_set_size – A part of the training set that will be used for QMLModel validation. It should be from (0, 1). It will be used in each of the binary classifiers.

  • rng_seed – A seed used for random weights initialization.

fit(X: Sequence[Sequence[float]] | ndarray[Any, dtype[float64]], y: Sequence[ModelOutput] | None) QNNClassifier[source]

The model training method. Essentially, it fits every binary classifier to the respective class.

Parameters:
  • X – The lists of features of the objects that are used during the training.

  • y – A list of outputs corresponding to the given lists of features.

Raises:
  • AttributeError – If the device is not specified.

  • AttributeError – If the y is not specified.

  • AssertionError – If the number of provided binary classifiers and classes don’t match.

Returns:

Returns self after training.

predict(features: Sequence[Sequence[float]]) Sequence[ModelOutput][source]

Returns predictions of the model for the given features. In the case of QuantumClassifier, for given features, the predicted class corresponds to the index of the binary classifier which returns the highest expectation value of the PauliZ measurement on the first qubit.

Parameters:

features – Features of the objects for which the model will predict the values.

Returns:

Values predicted for given features.

seed(new_seed: int) None[source]

Sets up the new seed.

Parameters:

new_seed – New seed to be applied to both the classifier and it’s binary classifier parts.

set_dev(new_dev: Device | None) None[source]
class aqmlator.qml.QNNLinearRegression(wires: int | Sequence[int], batch_size: int, n_epochs: int = 1, *, device: Device | None = None, optimizer: GradientDescentOptimizer | None = None, embedding_method: Type[Operation] | None = None, embedding_kwargs: Dict[str, Any] | None = None, layers: Sequence[Type[Operation]] | None = None, accuracy_threshold: float = 0.8, initial_weights: Sequence[float] | None = None, rng_seed: int = 42, validation_set_size: float = 0.2, prediction_function: Callable[[Sequence[Sequence[float]]], Sequence[ModelOutput]] | None = None, debug_flag: bool = False, coupling_map: Sequence[Sequence[int]] | None = None, n_qubit: int | None = None)[source]

Bases: RegressorMixin, QNNModel

This class implements a linear regressor that uses Quantum Neural Networks.

The constructor for the QNNModel class.

Parameters:
  • wires – The wires to use in the VQC or the number of qubits (and wires) used in the VQC.

  • batch_size – Size of a batches used during the training.

  • n_epochs – The number of training epochs.

  • device – A device on which the model should operate.

  • optimizer – The optimizer that will be used in the training. NesterovMomentumOptimizer with default parameters will be used as default.

  • embedding_method – Embedding method of the data. By default - when None is specified - the model will use AmplitudeEmbedding. See _prepare_default_embedding for parameters details.

  • embedding_kwargs – Keyword arguments for the embedding method. If none are specified the model will use the default embedding method.

  • layers – Layers to be used in the VQC. The layers will be applied in the given order. A double StronglyEntanglingLayer will be used if None is given.

  • accuracy_threshold – The satisfactory accuracy of the model.

  • initial_weights – The initial weights for the training.

  • rng_seed – A seed used for random weights initialization.

  • validation_set_size – A part of the training set that will be used for model validation. It should be from (0, 1).

  • prediction_function – A prediction function that will be used to process the output of the VQC. If None then the default one (for given model) will be used.

  • debug_flag – A flag informing the model if the training info should be printed to the console or not.

  • coupling_map – A description of connections between the qubits in the device.

class aqmlator.qml.QNNModel(wires: int | Sequence[int], batch_size: int, n_epochs: int = 1, *, device: Device | None = None, optimizer: GradientDescentOptimizer | None = None, embedding_method: Type[Operation] | None = None, embedding_kwargs: Dict[str, Any] | None = None, layers: Sequence[Type[Operation]] | None = None, accuracy_threshold: float = 0.8, initial_weights: Sequence[float] | None = None, rng_seed: int = 42, validation_set_size: float = 0.2, prediction_function: Callable[[Sequence[Sequence[float]]], Sequence[ModelOutput]] | None = None, debug_flag: bool = False, coupling_map: Sequence[Sequence[int]] | None = None, n_qubit: int | None = None)[source]

Bases: QMLModel, ABC

A boilerplate class, providing an interface for future QNN-Based models.

The constructor for the QNNModel class.

Parameters:
  • wires – The wires to use in the VQC or the number of qubits (and wires) used in the VQC.

  • batch_size – Size of a batches used during the training.

  • n_epochs – The number of training epochs.

  • device – A device on which the model should operate.

  • optimizer – The optimizer that will be used in the training. NesterovMomentumOptimizer with default parameters will be used as default.

  • embedding_method – Embedding method of the data. By default - when None is specified - the model will use AmplitudeEmbedding. See _prepare_default_embedding for parameters details.

  • embedding_kwargs – Keyword arguments for the embedding method. If none are specified the model will use the default embedding method.

  • layers – Layers to be used in the VQC. The layers will be applied in the given order. A double StronglyEntanglingLayer will be used if None is given.

  • accuracy_threshold – The satisfactory accuracy of the model.

  • initial_weights – The initial weights for the training.

  • rng_seed – A seed used for random weights initialization.

  • validation_set_size – A part of the training set that will be used for model validation. It should be from (0, 1).

  • prediction_function – A prediction function that will be used to process the output of the VQC. If None then the default one (for given model) will be used.

  • debug_flag – A flag informing the model if the training info should be printed to the console or not.

  • coupling_map – A description of connections between the qubits in the device.

fit(X: Sequence[Sequence[float]] | ndarray[Any, dtype[float64]], y: Sequence[ModelOutput] | None) QNNModel[source]

The model training method.

TODO TR: How to break this method down into smaller ones?

Parameters:
  • X – The lists of features of the objects that are used during the training.

  • y – A list of outputs corresponding to the given lists of features.

Raises:
  • AttributeError – If the device is not specified.

  • AttributeError – If the y is not specified.

Returns:

Returns self after training.

get_circuit_expectation_values(features_lists: Sequence[Sequence[float]]) ndarray[source]

Computes and returns the expectation value of the PauliZ measurement of the first qubit of the VQC.

Parameters:

features_lists – Features that will be encoded at the input of the circuit.

Returns:

The expectation value of the PauliZ measurement on the first qubit of the VQC.

get_torch_layer() Module[source]

This method creates a PyTorch (quantum) layer based on the VQC.

Returns:

Returns a PyTorch Layer made from the VQC.

predict(features: Sequence[Sequence[float]]) Sequence[float] | Sequence[int][source]

Returns predictions of the model for the given features.

Parameters:

features – Features of the objects for which the model will predict the values.

Returns:

Values predicted for given features.

abstractmethod score(X: Sequence[Sequence[float]], y: Sequence[int | float], sample_weight: Sequence[float] = None) float[source]

Computes and returns score of the model.

Note:

There are no typehints, same as in sklearn score functions that we will use.

Parameters:
  • X – Test samples.

  • y – True labels for X.

  • sample_weight – Sample weights.

Raises:

NotImplementedError – If the method is not implemented.

Returns:

Mean accuracy of self.predict(X) w.r.t. y.

class aqmlator.qml.QuantumKernelBinaryClassifier(wires: int | Sequence[int], *, n_epochs: int = 10, kta_subset_size: int = 5, device: Device | None = None, optimizer: GradientDescentOptimizer | None = None, embedding_method: Type[Operation] | None = None, embedding_kwargs: Dict[str, Any] | None = None, layers: Sequence[Type[Operation]] | None = None, initial_weights: Sequence[float] | None = None, rng_seed: int = 42, accuracy_threshold: float = 0.8, validation_set_size: float = 0.2, debug_flag: bool = False, coupling_map: Sequence[Sequence[int]] | None = None)[source]

Bases: QMLModel, ClassifierMixin

This class implements the binary classifier based on quantum kernels.

A constructor for the QuantumKernelBinaryClassifier class.

Parameters:
  • wires – The wires to use in the VQC or the number of qubits (and wires) used in the VQC.

  • n_epochs – The maximal number of training iterations.

  • kta_subset_size – The number of objects used to evaluate the kernel target alignment method in the cost function.

  • device – A device on which the model should operate.

  • optimizer – The optimizer that will be used in the training. NesterovMomentumOptimizer with default parameters will be used as default.

  • embedding_method – Embedding method of the data. By default - when None is specified - the classifier will use AngleEmbedding. See _prepare_default_embedding for parameters details.

  • embedding_kwargs – Keyword arguments for the embedding method. If none are specified the classifier will use the default embedding method.

  • layers – A list of layer functions to be applied in the kernel ansatz VQC.

  • initial_weights – The weights using which the training will start.

  • rng_seed – A random seed used to initialize the weights (if no weights are given).

  • accuracy_threshold – The accuracy after which the training is considered complete.

  • validation_set_size – A part of the training set that will be used for classifier validation. It should be from (0, 1).

  • debug_flag – A flag informing the classifier if the training info should be printed to the console or not.

  • coupling_map – A description of connections between the qubits in the device.

fit(X: Sequence[Sequence[float]] | ndarray[Any, dtype[float64]], y: Sequence[ModelOutput] | None) QuantumKernelBinaryClassifier[source]

The classifier training method.

TODO TR: How to break this method down into smaller ones?

Parameters:
  • X – The lists of features of the objects that are used during the training.

  • y – A list of classes corresponding to the given lists of features. The classes should be from set {-1, 1}.

Raises:
  • AttributeError – If the device is not specified.

  • AttributeError – If the y is not specified.

Returns:

Returns self after training.

predict(features_lists: Sequence[Sequence[float]]) Sequence[ModelOutput][source]

Predicts and returns the classes of the objects for which features were given. It applies current self.weights as the parameters of VQC.

Parameters:

features_lists – Objects’ features to be encoded at the input of the VQC.

Returns:

The results_reconstruction - classes 0 or 1 - of the classification. The data structure of the returned object is np.ndarray with dtype=bool.

transform(features_lists: Sequence[Sequence[float]]) List[List[ExpectationMP]][source]

Maps the object described by the features into it’s representation in the feature space.

Parameters:

features_lists – The features of the object to be mapped.

Returns:

The representation of the given object in the feature space.

class aqmlator.qml.RBMClustering(lbae_input_shape: Tuple[int, ...], lbae_out_channels: int, lbae_n_layers: int, rbm_n_visible_neurons: int, *, rbm_n_hidden_neurons: int, n_gpus: int = 0, n_epochs: int = 100, learning_rate: float = 0.01, qubo_scale: float = 1.0, sampler: Sampler | None = None, fireing_threshold: float = 0.8, rng: Generator | None = None)[source]

Bases: object

A class for performing clustering using Restricted Boltzmann Machine. The RBM can be trained using both classical and quantum algorithms. The quantum algorithm requires the D-Wave quantum annealer to be specified.

fit(data_loader: DataLoader[Tuple[Tensor, Tensor]]) None[source]
predict(x: Tensor) Tensor[source]

Returns the predicted class for the given input.

Parameters:

x – Input to be classified.

Returns:

Predicted class.