matchcake.ml.kernels package¶
Submodules¶
matchcake.ml.kernels.fermionic_pqc_kernel module¶
- class matchcake.ml.kernels.fermionic_pqc_kernel.FermionicPQCKernel(*, gram_batch_size: int = 10000, random_state: int = 0, n_qubits: int = 12, rotations: str = 'Y,Z', entangling_mth: str = 'fswap')¶
Bases:
NIFKernelThe FermionicPQCKernel class defines a Parameterized Quantum Circuit (PQC) kernel for use in quantum machine learning applications. It enables data embedding into a quantum feature space, supports various entangling methods, and allows customization of circuit parameters.
This class incorporates layered circuit design with options to specify the rotation gates, entangling method, depth, and the number of qubits. It is designed to transform classical data into quantum embeddings for downstream tasks like classification or regression using quantum or hybrid models.
Inspired from: https://iopscience.iop.org/article/10.1088/2632-2153/acb0b4/meta#artAbst
By default, the size of the kernel is computed as
\[\text{size} = \max\left(2, \lceil\log_2(\text{n features} + 2)\rceil\right)\]and the depth is computed as
\[\text{depth} = \max\left(1, \left(\frac{\text{n features}}{\text{size}} - 1\right)\right)\]- Variables:
DEFAULT_N_QUBITS – Default number of qubits to use in the circuit.
DEFAULT_GRAM_BATCH_SIZE – Default batch size for Gram matrix computations.
available_entangling_mth – Set of available entangling methods supported by the circuit.
depth – Number of entangling layers in the circuit. If set to None, it is dynamically computed based on the input data and number of qubits.
rotations – String describing the sequence of rotation gates used for embedding angles.
entangling_mth – Method used to introduce entanglement between qubits. Possible values include “fswap”, “identity”, and “hadamard”.
bias – Bias tensor added to the input data for encoding. It is initialized during the fit method call.
encoder – Encoder used to flatten the input data before embedding.
data_scaling – Scaling factor applied to the input data for encoding. It is initialized during the fit method call.
- DEFAULT_GRAM_BATCH_SIZE = 10000¶
- DEFAULT_N_QUBITS = 12¶
- __init__(*, gram_batch_size: int = 10000, random_state: int = 0, n_qubits: int = 12, rotations: str = 'Y,Z', entangling_mth: str = 'fswap')¶
Initializes the class with specified parameters for quantum circuit design and data processing. Ensures that user-provided configurations such as the entangling method are valid.
- Parameters:
gram_batch_size – Size of the gram batch, used for processing data in batches.
random_state – Seed for random number generator to ensure reproducibility.
n_qubits – Number of qubits to be used in the quantum circuit.
rotations – Types of rotations to be applied in the quantum circuit, specified as a comma-separated string (e.g., “Y,Z”).
entangling_mth – Method for entangling qubits in the quantum circuit. Must match one of the supported options.
- ansatz(x)¶
Generates a quantum circuit ansatz based on specific encoding, entangling methods, and configurations.
The ansatz consists of layers of a circuit that perform decomposition of encoded inputs over wires. It includes a choice of entangling methods and alternates over defined patterns of wire connectivity for double and double_odd configurations. Parameters are scaled and biased based on internal attributes.
- Parameters:
x (Any tensor-compatible object) – Input to be processed. The input is tensor-compatible and undergoes encoding.
- Raises:
ValueError – If the specified entangling method (entangling_mth) is not supported.
- Yield:
Decompositions of specified operations for inclusion in a quantum circuit.
- available_entangling_mth = {'fswap', 'hadamard', 'identity'}¶
- fit(x_train: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor, y_train: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor | None = None)¶
Fits the model to the training data by initializing the parameters for the quantum operations and determining the depth of the operation layers based on the input shape and the number of qubits. The function adapts the model to the provided input shape and prepares it for further processing.
- Parameters:
x_train – Training input data. Can be of type NDArray or torch.Tensor.
y_train – Optional parameter for training target/output data. Can be of type NDArray or torch.Tensor.
- Returns:
Updated instance of the class after fitting the training data.
- set_fit_request(*, x_train: bool | None | str = '$UNCHANGED$', y_train: bool | None | str = '$UNCHANGED$') FermionicPQCKernel¶
Request metadata passed to the
fitmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x_train (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
x_trainparameter infit.y_train (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
y_trainparameter infit.
- Returns:
self – The updated object.
- Return type:
object
- set_predict_request(*, x: bool | None | str = '$UNCHANGED$') FermionicPQCKernel¶
Request metadata passed to the
predictmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topredictif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
xparameter inpredict.- Returns:
self – The updated object.
- Return type:
object
- set_transform_request(*, x: bool | None | str = '$UNCHANGED$') FermionicPQCKernel¶
Request metadata passed to the
transformmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
xparameter intransform.- Returns:
self – The updated object.
- Return type:
object
matchcake.ml.kernels.gram_matrix module¶
- class matchcake.ml.kernels.gram_matrix.GramMatrix(shape: Tuple[int, ...], initial_value: float = 0.0, requires_grad: bool = False)¶
Bases:
objectRepresents a Gram matrix structure for storing symmetric matrix data. The class provides utilities for managing memory efficiently, either on disk via numpy.memmap or in memory using PyTorch tensors, depending on whether gradient computation is required. It supports in-place operations, symmetric updates, and provides tools for batch processing.
- Variables:
shape – Shape of the Gram matrix.
requires_grad – Whether the matrix requires gradient computation.
- __init__(shape: Tuple[int, ...], initial_value: float = 0.0, requires_grad: bool = False)¶
- apply_(func: Callable[[ndarray[tuple[int, ...], dtype[_ScalarType_co]]], Any], batch_size: int = 32, symmetrize: bool = True) GramMatrix¶
Apply a given function to a batch of indices in the Gram matrix and optionally symmetrize the matrix.
The apply_ method processes the Gram matrix in batches of indices and applies the provided function to update the matrix values at those indices. After processing the batches, the matrix can be symmetrized if specified.
- Parameters:
func – A callable that accepts an ndarray of indices and performs an operation on the corresponding elements in the matrix.
batch_size – The size of the batches in which the Gram matrix is processed. Default is 32.
symmetrize – Whether to symmetrize the matrix after applying func. Default is True.
- Returns:
Returns the updated instance of the Gram matrix.
- indices_batch_generator(batch_size: int = 32) Iterator[ndarray[tuple[int, ...], dtype[int64]]]¶
Generates batches of indices in the form of tuples within the constraints of a given shape and selection logic. The generator iterates over all pairwise index combinations (i, j) of an array defined by the object’s shape attribute. The generator yields these indices batch by batch, depending on the specified batch size.
- Parameters:
batch_size – The maximum number of (i, j) index pairs to be included in each batch. Defaults to 32.
- Returns:
Iterator that yields batches of index pairs as numpy arrays of shape (batch_size, 2). Each batch contains tuples of indices in the form (i, j), respecting the constraints based on the dimensions of the object’s shape.
- property requires_grad: bool¶
- property shape: Tuple[int, ...]¶
- symmetrize_() GramMatrix¶
Creates a symmetric version of the matrix by mirroring its values across the main diagonal. Entries below the diagonal are updated to match their corresponding entries above the diagonal for matrices with more rows than columns. Conversely, entries above the diagonal are updated to match their counterparts below the diagonal for matrices with more columns than rows. The diagonal values of the matrix are filled with ones.
- Returns:
A symmetric version of the current matrix.
- Return type:
- to_tensor() Tensor¶
Converts the contained data to a PyTorch tensor.
If requires_grad is True, the method returns the original tensor associated with the object. Otherwise, it converts the _memmap data to a PyTorch tensor with float32 dtype.
- Returns:
The PyTorch tensor representation of the contained data.
- Return type:
torch.Tensor
matchcake.ml.kernels.kernel module¶
- class matchcake.ml.kernels.kernel.Kernel(*, gram_batch_size: int = 10000, random_state: int = 0)¶
Bases:
Module,TransformerMixin,BaseEstimatorKernel class that extends
torch.nn.Module,TransformerMixin, andBaseEstimator.This class provides a base structure for implementing a kernel model with features like forward computation, data transformation, and model fitting. It is designed to handle both NumPy arrays and PyTorch tensors, offering functionality for model freezing and easy access to the device where the model parameters are stored. It is intended to be subclassed for specific kernel functionality.
- Variables:
gram_batch_size – Batch size for gram matrix computation.
random_state – Random state seed for reproducibility.
- DEFAULT_GRAM_BATCH_SIZE = 10000¶
- __init__(*, gram_batch_size: int = 10000, random_state: int = 0)¶
Initializes the class with configurations related to batch sizes and random state.
- Parameters:
gram_batch_size – The batch size to be used for processing gram matrices.
random_state – The seed value for ensuring reproducible random number generation.
- property device¶
Provides the current device of the model parameters. If the model has no parameters, it defaults to the CPU device. This property is useful for determining where the model is currently located, either on CPU or a specific GPU.
- Returns:
The device on which the model’s parameters reside, or ‘cpu’ if there are no parameters.
- Return type:
torch.device
- fit(x_train: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor, y_train: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor | None = None)¶
Fits the model using the provided training data. This method stores the training data and sets the model’s state to fitted.
- Parameters:
x_train (Union[NDArray, torch.Tensor]) – Training input data. It can be a NumPy array or a Torch tensor.
y_train (Optional[Union[NDArray, torch.Tensor]]) – Training target data. It can be a NumPy array, a Torch tensor, or None. Defaults to None.
- Returns:
The fitted model instance.
- Return type:
self
- forward(x0: Tensor, x1: Tensor | None = None) Tensor¶
Computes the forward pass of the model with the given inputs.
The forward method defines the computation performed at every call of the model. This typically involves applying a sequence of operations on input tensors to produce the output tensor(s). The specific implementation details are to be defined in subclasses.
- Parameters:
x0 – The primary input tensor for the forward pass. This tensor is expected to have a shape suitable for the compute module being used in the forward method.
x1 – An optional secondary input tensor for the forward pass. If provided, it is used in conjunction with the primary input tensor depending on the specific implementation of the forward pass logic.
- Returns:
The output tensor resulting from the computation of the forward pass.
- freeze()¶
Freezes the model by setting it to evaluation mode and disabling gradient computations.
This method is typically used for inference to ensure the model does not update its parameters during forward passes. It switches the model to evaluation mode and sets all parameters to not require gradients.
- Returns:
The model instance with evaluation mode enabled and gradient computations disabled.
- Return type:
self
- predict(x: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor) ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor¶
Predict transformed data using the model.
This function applies a transformation to the input data and returns the resulting output. It supports both NumPy arrays and PyTorch tensors as input. The return type will match the input type.
- Parameters:
x – The input data to be transformed. Can be either a NumPy array or a PyTorch tensor.
- Returns:
The transformed input data. The returned type will match the type of the input data (NumPy array or PyTorch tensor).
- set_fit_request(*, x_train: bool | None | str = '$UNCHANGED$', y_train: bool | None | str = '$UNCHANGED$') Kernel¶
Request metadata passed to the
fitmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x_train (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
x_trainparameter infit.y_train (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
y_trainparameter infit.
- Returns:
self – The updated object.
- Return type:
object
- set_predict_request(*, x: bool | None | str = '$UNCHANGED$') Kernel¶
Request metadata passed to the
predictmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topredictif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
xparameter inpredict.- Returns:
self – The updated object.
- Return type:
object
- set_transform_request(*, x: bool | None | str = '$UNCHANGED$') Kernel¶
Request metadata passed to the
transformmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
xparameter intransform.- Returns:
self – The updated object.
- Return type:
object
- transform(x: ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor) ndarray[tuple[int, ...], dtype[_ScalarType_co]] | Tensor¶
Transforms the input using a specified transformation process. The transformation is performed on the provided input data, converting it into a tensor if necessary and applying the forward operation with the trained data. If the original input was not a tensor, it converts the transformed data back to a numpy array.
- Parameters:
x (Union[NDArray, torch.Tensor]) – Input data to be transformed. Can be either a NumPy array or a PyTorch tensor.
- Returns:
The transformed data. The format matches the input type (a NumPy array or a PyTorch tensor).
- Return type:
Union[NDArray, torch.Tensor]
matchcake.ml.kernels.linear_nif_kernel module¶
- class matchcake.ml.kernels.linear_nif_kernel.LinearNIFKernel(*, gram_batch_size: int = 10000, random_state: int = 0, n_qubits: int = 12, bias: bool = True, encoder_activation: str = 'Identity')¶
Bases:
NIFKernelRepresents a specialized kernel model extending the NIFKernel class.
This class provides a quantum kernel suitable for simulations utilizing a non-interacting fermionic hardware backend with customizable qubit configurations and encoder activations. The class heavily integrates PyTorch modules for defining the encoding layer and uses matrix operations to define the ansatz required for quantum computations. Allows fine-tuning of kernel parameters like bias, encoder activation function, and qubit distribution, making it highly adaptable to various quantum learning tasks.
- Variables:
DEFAULT_N_QUBITS – Default number of qubits used in the kernel.
DEFAULT_GRAM_BATCH_SIZE – Default size of the Gram matrix computation batch.
- DEFAULT_GRAM_BATCH_SIZE = 10000¶
- DEFAULT_N_QUBITS = 12¶
- __init__(*, gram_batch_size: int = 10000, random_state: int = 0, n_qubits: int = 12, bias: bool = True, encoder_activation: str = 'Identity')¶
Initializes the class with configurable parameters for the model’s encoder and quantum settings. It manages setup for batch processing, randomness seed, number of qubits, output bias and activation type of the encoder.
- Parameters:
gram_batch_size (int) – Number of samples to include in each batch for processing. Optimally adjusts memory and computation requirements.
random_state (int) – Seed value for random number generation to ensure reproducibility and consistency.
n_qubits (int) – Number of qubits used in the quantum computation process.
bias (bool) – Determines if the linear layers in the encoder should include a bias term.
encoder_activation (str) – The activation function applied in the encoder layers. Should match options available in torch.nn (e.g., “Identity”).
- ansatz(x: Tensor)¶
Applies the ansatz to the input data for quantum computation. The method first processes the input tensor, creating a Hamiltonian matrix, and then calculates the single-particle transition matrix. Once computed, the method yields a single-particle transition matrix operation that can be applied to quantum wires.
- Parameters:
x (torch.Tensor) – The input tensor containing data to be encoded in the ansatz.
- Returns:
A generator yielding a single-particle transition matrix operation.
- Return type:
Generator[SingleParticleTransitionMatrixOperation, None, None]
- property bias: bool¶
- property encoder_activation: str¶
- property encoder_out_indices¶
- property encoder_out_tril_indices¶
- property n_qubits: int¶
- set_fit_request(*, x_train: bool | None | str = '$UNCHANGED$', y_train: bool | None | str = '$UNCHANGED$') LinearNIFKernel¶
Request metadata passed to the
fitmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x_train (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
x_trainparameter infit.y_train (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
y_trainparameter infit.
- Returns:
self – The updated object.
- Return type:
object
- set_predict_request(*, x: bool | None | str = '$UNCHANGED$') LinearNIFKernel¶
Request metadata passed to the
predictmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topredictif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
xparameter inpredict.- Returns:
self – The updated object.
- Return type:
object
- set_transform_request(*, x: bool | None | str = '$UNCHANGED$') LinearNIFKernel¶
Request metadata passed to the
transformmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
xparameter intransform.- Returns:
self – The updated object.
- Return type:
object
matchcake.ml.kernels.nif_kernel module¶
- class matchcake.ml.kernels.nif_kernel.NIFKernel(*, gram_batch_size: int = 10000, random_state: int = 0, n_qubits: int = 12)¶
Bases:
KernelDefines a quantum kernel using a non-interacting fermionic device for similarity computations between input data.
This class encapsulates quantum kernel operations, leveraging a specific device implementation (NonInteractingFermionicDevice). It handles the computation of kernel values between input datasets, based on the provided similarity measure. The class supports flexible configuration of qubit numbers and processing batch sizes.
- Variables:
R_DTYPE – Data type used for computation within the kernel.
- DEFAULT_GRAM_BATCH_SIZE = 10000¶
- DEFAULT_N_QUBITS = 12¶
- __init__(*, gram_batch_size: int = 10000, random_state: int = 0, n_qubits: int = 12)¶
Initializes the class with specific parameters for quantum device configuration and random state.
- Parameters:
gram_batch_size – The batch size for the Gram computation.
random_state – Seed for the random number generator to ensure reproducibility.
n_qubits – The number of qubits for the non-interacting fermionic device.
- ansatz(x: Tensor)¶
Represents an abstract method for implementing a specific ansatz.
This method must be overridden in a subclass and is not implemented in the base class itself. It serves as a blueprint for any specific ansatz that is required by the framework or application.
The responsibility of providing the implementation for the ansatz logic remains with the derived class.
- Parameters:
x (torch.Tensor) – Input tensor.
- Raises:
NotImplementedError – If the method is called without overriding it in a subclass.
- circuit(x0, x1)¶
Generates a quantum circuit by applying an ansatz followed by its adjoint.
The method first yields the result of applying the ansatz function to the first input, x0. Then, it yields the adjoint of the ansatz function applied to the second input, x1. This allows the generation of customized quantum circuits where specific operations are defined by the ansatz function.
- Parameters:
x0 – The first parameter used for generating the circuit via the ansatz.
x1 – The second parameter used for generating the adjoint circuit via the ansatz.
- Returns:
Yields the quantum operations for constructing the circuit.
- compute_similarities(x0: Tensor, x1: Tensor)¶
Computes the similarity matrix between tensors x0 and x1. The function evaluates quantum computational circuits for pairs of instances from x0 and x1 to compute a Gram matrix that represents the pairwise similarities. These values are then processed and provided as a tensor representation of the similarity matrix.
- Parameters:
x0 (torch.Tensor) – The first tensor containing a batch of samples for similarity computation.
x1 (torch.Tensor) – The second tensor containing another batch of samples for similarity computation.
- Returns:
A tensor representing the computed similarity matrix.
- Return type:
torch.Tensor
- forward(x0: Tensor, x1: Tensor | None = None) Tensor¶
Calculates the similarities between input tensors and returns the kernel output.
This method takes two tensors, converts them to the specified dtype, and computes their similarities using the compute_similarities method of the class. If the second input tensor is not provided, it defaults to the first tensor. The result is a kernel tensor representing the similarities between the inputs.
- Parameters:
x0 – The first input tensor.
x1 – The second input tensor. Defaults to
x0if not provided.
- Returns:
A tensor representing the computed kernel similarities.
- property n_qubits: int¶
- property q_device¶
- set_fit_request(*, x_train: bool | None | str = '$UNCHANGED$', y_train: bool | None | str = '$UNCHANGED$') NIFKernel¶
Request metadata passed to the
fitmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed tofitif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it tofit.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x_train (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
x_trainparameter infit.y_train (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
y_trainparameter infit.
- Returns:
self – The updated object.
- Return type:
object
- set_predict_request(*, x: bool | None | str = '$UNCHANGED$') NIFKernel¶
Request metadata passed to the
predictmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed topredictif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it topredict.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
xparameter inpredict.- Returns:
self – The updated object.
- Return type:
object
- set_transform_request(*, x: bool | None | str = '$UNCHANGED$') NIFKernel¶
Request metadata passed to the
transformmethod.Note that this method is only relevant if
enable_metadata_routing=True(seesklearn.set_config()). Please see User Guide on how the routing mechanism works.The options for each parameter are:
True: metadata is requested, and passed totransformif provided. The request is ignored if metadata is not provided.False: metadata is not requested and the meta-estimator will not pass it totransform.None: metadata is not requested, and the meta-estimator will raise an error if the user provides it.str: metadata should be passed to the meta-estimator with this given alias instead of the original name.
The default (
sklearn.utils.metadata_routing.UNCHANGED) retains the existing request. This allows you to change the request for some parameters and not others.New in version 1.3.
Note
This method is only relevant if this estimator is used as a sub-estimator of a meta-estimator, e.g. used inside a
Pipeline. Otherwise it has no effect.- Parameters:
x (str, True, False, or None, default=sklearn.utils.metadata_routing.UNCHANGED) – Metadata routing for
xparameter intransform.- Returns:
self – The updated object.
- Return type:
object
- property wires¶
matchcake.ml.kernels.nystroem module¶
- class matchcake.ml.kernels.nystroem.Nystroem(kernel: Kernel, *, n_components=100, random_state=None)¶
Bases:
NystroemEncapsulation of the Nystroem method for kernel approximation.
This class provides an implementation of the Nystroem method, which is used to approximate a kernel map for a given dataset. It is designed to reduce computation cost while maintaining a good approximation of the original kernel matrix. It involves sampling a subset of the data and computing the kernel function on these sampled points to derive the approximation.
- Variables:
n_components – Number of components (basis functions) used to approximate the kernel map. If greater than the number of samples, it will be automatically set to the number of samples in the data.
kernel – Kernel function to be used for computing the kernel similarity.
random_state – Controls the randomness of the sampling of the subset of training data. Can be an integer, RandomState instance, or None.
- __init__(kernel: Kernel, *, n_components=100, random_state=None)¶
Initializes an instance of the class with specified kernel, number of components, and random state. This class is used for applications requiring these parameters to process data or perform computations efficiently. The kernel defines the transformation applied, n_components specifies the dimensionality, and random_state ensures reproducibility.
- Parameters:
kernel – An instance of a Kernel defining the transformation method to be applied.
n_components – Number of components for dimensionality reduction or computation. Defaults to 100.
random_state – Seed or random state for ensuring reproducible results. Defaults to None.
- fit(X, y=None)¶
Fit estimator to data.
Samples a subset of training points, computes kernel on these and computes normalization matrix.
- Parameters:
X (array-like, shape (n_samples, n_features)) – Training data, where n_samples is the number of samples and n_features is the number of features.
y (array-like, shape (n_samples,) or (n_samples, n_outputs), default=None) – Target values (None for unsupervised transformations).
- Returns:
self – Returns the instance itself.
- Return type:
object
- freeze()¶
Freezes the kernel to retain its current state and settings.
This method ensures that the kernel does not alter its configuration or parameters anymore, providing stability for subsequent operations.
- Returns:
The current instance of the class.
- Return type:
Same as the class of the current instance.
- transform(X)¶
Apply feature map to X.
Computes an approximate feature map using the kernel between some training points and X.
- Parameters:
X (array-like of shape (n_samples, n_features)) – Data to transform.
- Returns:
X_transformed – Transformed data.
- Return type:
ndarray of shape (n_samples, n_components)