scikit_quri.qnn package

Contents

scikit_quri.qnn package#

Submodules#

scikit_quri.qnn.classifier module#

class scikit_quri.qnn.classifier.QNNClassifier(ansatz, num_class, estimator, gradient_estimator, optimizer, operator=<factory>, x_norm_range=1.0, do_x_scale=True, y_exp_ratio=2.2, trained_param=None, _pred_cache=<factory>)[source]#

Bases: object

Class to solve classification problems by quantum neural networks. The prediction is made by making a vector which predicts one-hot encoding of labels. The prediction is made by 1. taking expectation values of Pauli Z operator of each qubit <Z_i>, 2. taking softmax function of the vector (<Z_0>, <Z_1>, ..., <Z_{n-1}>).

Parameters:

Example

>>> from scikit_quri.qnn.classifier import QNNClassifier
>>> from scikit_quri.circuit import create_qcl_ansatz
>>> from quri_parts.core.estimator.gradient import (
>>>     create_numerical_gradient_estimator,
>>> )
>>> from quri_parts.qulacs.estimator import (
>>>     create_qulacs_vector_concurrent_estimator,
>>>     create_qulacs_vector_concurrent_parametric_estimator,
>>> )
>>> from quri_parts.algo.optimizer import Adam
>>> num_class = 3
>>> nqubit = 5
>>> c_depth = 3
>>> time_step = 0.5
>>> circuit = create_qcl_ansatz(nqubit, c_depth, time_step, 0)
>>> adam = Adam()
>>> estimator = create_qulacs_vector_concurrent_estimator()
>>> gradient_estimator = create_numerical_gradient_estimator(
>>>    create_qulacs_vector_concurrent_parametric_estimator(), delta=1e-10
>>> )
>>> qnn = QNNClassifier(circuit, num_class, estimator, gradient_estimator, adam)
>>> qnn.fit(x_train, y_train, maxiter)
>>> y_pred = qnn.predict(x_test).argmax(axis=1)
ansatz: LearningCircuit#
num_class: int#
estimator: BaseEstimator#
gradient_estimator: Callable[[Union[Operator, PauliLabel], _ParametricStateT, Sequence[float]], Estimates[complex]]#
optimizer: Optimizer#
operator: List[Union[Operator, PauliLabel]]#
x_norm_range: float = 1.0#
do_x_scale: bool = True#
y_exp_ratio: float = 2.2#
trained_param: Optional[npt.NDArray[np.float64]] = None#
n_qubit: int#
fit(x_train, y_train, maxiter=100)[source]#
Parameters:
  • x_train (ndarray[tuple[int, ...], dtype[float64]]) – List of training data inputs whose shape is (n_samples, n_features).

  • y_train (ndarray[tuple[int, ...], dtype[int64]]) – List of labels to fit. Labels must be represented as integers. Shape is (n_samples,).

  • maxiter (int) – The number of maximum iterations for the optimizer.

Returns:

None

predict(x_test)[source]#

Predict outcome for each input data in x_test. This method returns the predicted outcome as a vector of probabilities for each class. :param x_test: Input data whose shape is (n_samples, n_features).

Returns:

Predicted outcome whose shape is (n_samples, num_class).

Return type:

y_pred

Parameters:

x_test (ndarray[tuple[int, ...], dtype[float64]]) –

cost_func(x_scaled, y_train, params)[source]#
Parameters:
Return type:

float

cost_func_grad(x_scaled, y_train, params)[source]#
Parameters:
Return type:

ndarray[tuple[int, …], dtype[float64]]

scikit_quri.qnn.generation module#

Quantum Circuit Born Machine (QCBM) generative model.

Implements the MMD-based training algorithm from Liu & Wang, “Differentiable Learning of Quantum Circuit Born Machines”, Phys. Rev. A 98, 062324 (2018), arXiv:1804.04168.

The model samples bit strings z from p_theta(z) = |⟨z|psi(theta)⟩|^2 (Born rule); training minimizes the squared maximum mean discrepancy MMD^2 between model samples and target samples in a reproducing kernel Hilbert space. Both cost and gradient estimators are sample-based, so the same code runs on a state-vector simulator (QulacsSampler), a noisy simulator, or real hardware (OqtopusSampler).

scikit_quri.qnn.generation.default_gaussian_mixture_kernel(sigmas=(0.25, 1.0, 4.0))[source]#

Gaussian-mixture kernel on integer bit-string distances.

K(x_i, y_j) = (1/|sigmas|) * sum_sigma exp(-(x_i - y_j)^2 / (2 sigma^2)).

Liu & Wang recommend mixtures of bandwidths so the kernel captures both local and global differences between distributions. The default values are reasonable for low-qubit problems; for larger bit-string ranges consider scaling sigmas with the support size.

Parameters:

sigmas (Sequence[float]) –

Return type:

Callable[[ndarray[tuple[int, …], dtype[_ScalarType_co]], ndarray[tuple[int, …], dtype[_ScalarType_co]]], ndarray[tuple[int, …], dtype[_ScalarType_co]]]

class scikit_quri.qnn.generation.QNNGenerator(circuit, solver, sampler, n_shots=1024, kernel=None, fitting_qubit=None)[source]#

Bases: object

Quantum Circuit Born Machine trained with MMD loss.

Parameters:
  • circuit (LearningCircuit) – Parametric circuit (ansatz). The input portion of the circuit is bound to a constant np.array([0]) placeholder — this class learns an unconditional distribution, so any add_input_* gates should be avoided.

  • solver (Optimizer) – Optimizer driving theta updates.

  • sampler (BaseSampler) – Sampling backend implementing BaseSampler.

  • n_shots (int) – Number of measurement shots per circuit evaluation. Used for cost, gradient (per shift), and predict.

  • kernel (Optional[Callable[[ndarray[tuple[int, ...], dtype[_ScalarType_co]], ndarray[tuple[int, ...], dtype[_ScalarType_co]]], ndarray[tuple[int, ...], dtype[_ScalarType_co]]]]) – Kernel K(x, y) -> (n_x, n_y) for the MMD loss. x and y are arrays of bit-string integers. Defaults to a Gaussian mixture from default_gaussian_mixture_kernel().

  • fitting_qubit (Optional[int]) – Number of qubits used to represent the output distribution. When less than circuit.n_qubits the higher qubits are marginalized out (z mod 2^fitting_qubit). Defaults to circuit.n_qubits.

Notes

Parameter-shift gradients are computed at the learning-parameter level (length = circuit.learning_params_count). This is exact when each learning parameter controls a single Pauli rotation gate; circuits using share_with to share one learning parameter across multiple gates will receive an approximate gradient — the cost function itself is unaffected.

fit(train_data, maxiter=100)[source]#

Train against a sample-list target distribution.

Parameters:
  • train_data (ndarray[tuple[int, ...], dtype[int64]]) – Array of bit-string integers; the empirical distribution of these is the target.

  • maxiter (int) – Maximum optimizer iterations.

Return type:

None

fit_direct_distribution(p, maxiter=100, n_target_samples=10000, seed=0)[source]#

Train against a target probability vector.

Internally samples n_target_samples bit strings from p and delegates to fit(). The MMD estimator is sample-based.

Parameters:
  • p (ndarray[tuple[int, ...], dtype[float64]]) – Target probability vector of length 2^fitting_qubit.

  • maxiter (int) – Maximum optimizer iterations.

  • n_target_samples (int) – Number of target-distribution samples.

  • seed (int) – Seed for the target sampler.

Return type:

None

predict(n_shots=None)[source]#

Estimate the model’s output probability vector via sampling.

Parameters:

n_shots (Optional[int]) – Override sampling shots. Defaults to self.n_shots.

Returns:

Empirical probability vector of length 2^fitting_qubit. Has shot noise of order 1/sqrt(n_shots).

Return type:

ndarray[tuple[int, …], dtype[float64]]

cost_func(theta, train_samples)[source]#

Estimate MMD^2(model, target) with self.n_shots model samples.

Parameters:
Return type:

float

scikit_quri.qnn.kernel_tsne module#

class scikit_quri.qnn.kernel_tsne.pqc_f_helper(pqs_f)[source]#

Bases: object

Helper class that evaluates and caches quantum states for input data.

Parameters:

pqs_f (Callable[[ndarray[tuple[int, ...], dtype[float64]]], GeneralCircuitQuantumState]) –

get(input)[source]#

Return the cached quantum state for the given input, computing it if not yet cached.

Parameters:

input (ndarray[tuple[int, ...], dtype[float64]]) – Input data array.

Returns:

Quantum state corresponding to the input.

Return type:

GeneralCircuitQuantumState

class scikit_quri.qnn.kernel_tsne.overlap_estimator(states)[source]#

Bases: object

Materializes quri-parts quantum states into qulacs state vectors.

Holds a list of states and converts them to qulacs QuantumState objects (cached in qula_states). Used by fidelity_gram() / fidelity_cross() to obtain the raw state vectors for a single vectorized overlap computation.

Parameters:

states (List[GeneralCircuitQuantumState]) –

calc_all_qula_states()[source]#

Convert and cache the qulacs state vector for every input state.

scikit_quri.qnn.kernel_tsne.fidelity_gram(states)[source]#

Compute the symmetric fidelity matrix |⟨φi|φj⟩|² for all pairs in one BLAS call.

The diagonal is exactly 1 for normalized states.

Parameters:

states (List[GeneralCircuitQuantumState]) – Quantum states.

Returns:

Fidelity matrix of shape (n, n).

Return type:

ndarray[tuple[int, …], dtype[float64]]

scikit_quri.qnn.kernel_tsne.fidelity_cross(states, states_tr)[source]#

Compute the rectangular fidelity matrix |⟨φi|ψj⟩|² between two sets of states.

Parameters:
Returns:

Fidelity matrix of shape (len(states), len(states_tr)).

Return type:

ndarray[tuple[int, …], dtype[float64]]

class scikit_quri.qnn.kernel_tsne.TSNE(perplexity=30)[source]#

Bases: object

Basic t-SNE implementation for computing p and q probability matrices.

calc_probabilities_p(X_train)[source]#

Compute the t-SNE joint probability matrix P from Euclidean distances.

Parameters:

X_train (ndarray[tuple[int, ...], dtype[float64]]) – Input data of shape (n_samples, n_features).

Returns:

Symmetric joint probability matrix P of shape (n_samples, n_samples).

Return type:

ndarray[tuple[int, …], dtype[float64]]

calc_probabilities_p_state(X_train_state)[source]#

Compute the t-SNE joint probability matrix P from quantum state overlaps. Uses 1 - |⟨φi|φj⟩|² as the distance metric between quantum states.

Parameters:

X_train_state (List[GeneralCircuitQuantumState]) – List of quantum states corresponding to the training inputs.

Returns:

Symmetric joint probability matrix P of shape (n_samples, n_samples).

Return type:

ndarray[tuple[int, …], dtype[float64]]

calc_probabilities_p_from_fidelity(fidelity)[source]#

Compute the joint probability matrix P from a precomputed fidelity matrix.

Uses 1 - |⟨φi|φj⟩|² as the (squared) distance between quantum states. Kept separate from the fidelity computation so callers that already hold the fidelity matrix (e.g. the embedding kernel) need not recompute it.

Parameters:

fidelity (ndarray[tuple[int, ...], dtype[float64]]) – Symmetric fidelity matrix |⟨φi|φj⟩|² of shape (n, n).

Returns:

Symmetric joint probability matrix P of shape (n, n).

Return type:

ndarray[tuple[int, …], dtype[float64]]

calc_probabilities_q(c_data)[source]#

Compute the t-SNE joint probability matrix Q from the low-dimensional embedding. Uses the Student’s t-distribution as the similarity kernel.

Parameters:

c_data (ndarray[tuple[int, ...], dtype[float64]]) – Low-dimensional embedding (called y in the original paper), of shape (n_samples, n_components).

Returns:

Symmetric joint probability matrix Q of shape (n_samples, n_samples).

Return type:

ndarray[tuple[int, …], dtype[float64]]

joint_probabilities(sq_distance, perplexity)[source]#

Compute the symmetric joint probability matrix from pairwise distances.

Parameters:
  • sq_distance (ndarray[tuple[int, ...], dtype[float64]]) – Pairwise distance matrix of shape (n_samples, n_samples).

  • perplexity (int) – Target perplexity for the conditional distributions.

Returns:

Symmetric joint probability matrix of shape (n_samples, n_samples).

binary_search_perplexity(sq_distance, perplexity)[source]#

Find the Gaussian kernel bandwidth for each point via binary search so that the perplexity of the conditional distribution matches the target.

Parameters:
kldiv(p_probs, q_probs)[source]#

Compute the KL divergence KL(P || Q).

Parameters:
  • p_probs – Reference probability matrix P.

  • q_probs – Approximate probability matrix Q.

Returns:

Scalar KL divergence value.

cdist(X, X_tr)[source]#

Compute pairwise SQUARED Euclidean distances between rows of X and X_tr.

t-SNE uses squared distances in both the high-dimensional Gaussian kernel (exp(-||x_i - x_j||^2 * beta)) and the low-dimensional Student-t kernel ((1 + ||y_i - y_j||^2)^-1), so callers expect sq_distance here.

Parameters:
Returns:

Squared-distance matrix of shape (n_samples, m_samples).

class scikit_quri.qnn.kernel_tsne.quantum_kernel_tsne(perplexity=30, max_iter=400)[source]#

Bases: object

t-SNE using a quantum kernel as the similarity measure in the high-dimensional space.

init(pqc_f, theta)[source]#

Set up the parametric quantum circuit used to encode input data.

Parameters:
Return type:

None

calc_loss(p_prob, q_prob)[source]#

Compute the KL divergence loss KL(P || Q) used as the optimization objective.

Parameters:
Returns:

Scalar KL divergence loss value.

calc_grad(alpha, p_prob, fidelity)[source]#

Analytic gradient of the loss with respect to the embedding coefficients alpha.

Since y = fidelity @ alpha, the chain rule gives dC/dalpha = fidelity^T @ dC/dy (fidelity is symmetric for the train kernel). This replaces the former central-difference gradient, which cost O(n) loss evaluations per gradient and made gradient-based optimizers impractical.

Parameters:
  • alpha (ndarray[tuple[int, ...], dtype[float64]]) – Flattened embedding coefficients of shape (n_samples * 2,).

  • p_prob (ndarray[tuple[int, ...], dtype[float64]]) – High-dimensional joint probability matrix P.

  • fidelity (ndarray[tuple[int, ...], dtype[float64]]) – Pairwise fidelity matrix of shape (n_samples, n_samples).

Returns:

Flattened gradient of the same shape as alpha.

calc_loss_grad(alpha, p_prob, fidelity)[source]#

Joint loss and gradient w.r.t. alpha, for gradient-based optimizers.

Computing both together shares the d^2 / num / Z work, so a gradient step costs a single cdist(y, y) instead of two (one for the value and one for the jacobian). Used by the L-BFGS-B path via scipy.optimize.minimize(..., jac=True).

Parameters:
  • alpha (ndarray[tuple[int, ...], dtype[float64]]) – Flattened embedding coefficients of shape (n_samples * 2,).

  • p_prob (ndarray[tuple[int, ...], dtype[float64]]) – High-dimensional joint probability matrix P (normalized, sum 1).

  • fidelity (ndarray[tuple[int, ...], dtype[float64]]) – Pairwise fidelity matrix of shape (n_samples, n_samples).

Returns:

Tuple (loss, grad_alpha) where grad_alpha is flattened like alpha.

cost_f(alpha, p_prob, fidelity)[source]#

Cost function passed to the optimizer.

Parameters:
  • alpha (ndarray[tuple[int, ...], dtype[float64]]) – Flattened embedding coefficients of shape (n_samples * 2,). The optimizer passes a 1-D array; it is reshaped to (n_samples, 2) internally.

  • p_prob (ndarray[tuple[int, ...], dtype[float64]]) – High-dimensional joint probability matrix P.

  • fidelity (ndarray[tuple[int, ...], dtype[float64]]) – Pairwise fidelity matrix of shape (n_samples, n_samples).

Returns:

Scalar KL divergence loss value.

generate_X_train_state(X_train)[source]#

Generate quantum states for all training inputs using the cached circuit evaluator.

Parameters:

X_train (ndarray[tuple[int, ...], dtype[float64]]) – Training input array of shape (n_samples, n_features).

Returns:

Array of GeneralCircuitQuantumState objects of shape (n_samples,).

train(X_train, y_label, method='Powell')[source]#

Fit the quantum kernel t-SNE embedding.

Parameters:
  • X_train (ndarray[tuple[int, ...], dtype[float64]]) – Training input array of shape (n_samples, n_features).

  • y_label (ndarray[tuple[int, ...], dtype[int8]]) – Class labels of shape (n_samples,). Used only for plotting.

  • method – Optimization method. One of "L-BFGS-B", "adam", "COBYLA", or "Powell". "L-BFGS-B" and "adam" use the analytic gradient and converge in far fewer evaluations than the gradient-free "Powell" / "COBYLA". Defaults to "Powell".

transform(X_test)[source]#

Compute the low-dimensional embedding for test data using the trained alpha.

Parameters:

X_test (ndarray[tuple[int, ...], dtype[float64]]) – Test input array of shape (n_samples, n_features).

Returns:

Low-dimensional embedding of shape (n_samples, 2).

Return type:

ndarray[tuple[int, …], dtype[float64]]

calc_y(fidelity, alpha)[source]#

Compute the low-dimensional embedding y = fidelity @ alpha.

Parameters:
  • fidelity (ndarray[tuple[int, ...], dtype[float64]]) – Pairwise fidelity matrix |⟨φi|φj⟩|² of shape (n_data, n_data).

  • alpha (ndarray[tuple[int, ...], dtype[float64]]) – Embedding coefficients of shape (n_data, 2).

Returns:

Low-dimensional embedding of shape (n_data, 2).

Return type:

ndarray[tuple[int, …], dtype[float64]]

input_quantum_state(input, pqc_f, theta)[source]#

Compute the quantum state |φ(input, θ)⟩ for the given input and circuit parameters.

Parameters:
Returns:

Bound quantum state corresponding to the input and parameters.

Return type:

GeneralCircuitQuantumState

calc_fidelity(data, data_tr, pqs_f_helper)[source]#

Compute the full symmetric fidelity matrix when data == data_tr.

Parameters:
  • data – Input array.

  • data_tr – Must be identical to data.

  • pqs_f_helper (pqc_f_helper) – Cached quantum state evaluator.

Returns:

Symmetric fidelity matrix of shape (n_data, n_data).

Raises:

ValueError – If data and data_tr are not identical.

calc_fidelity_all(data, data_tr, pqs_f_helper)[source]#

Compute the fidelity matrix when data != data_tr (e.g. train vs test).

Parameters:
  • data – Query data array of shape (n_data, n_features).

  • data_tr – Reference data array of shape (n_data_tr, n_features).

  • pqs_f_helper (pqc_f_helper) – Cached quantum state evaluator.

Returns:

Fidelity matrix of shape (n_data, n_data_tr).

plot(y, y_label, title)[source]#

Plot the 2-D embedding with class labels.

Parameters:

scikit_quri.qnn.regressor module#

scikit_quri.qnn.regressor.mean_squared_error(y_true, y_pred)[source]#

Calculate the mean squared error between true and predicted values.

Parameters:
Returns:

Mean squared error.

Return type:

mse

class scikit_quri.qnn.regressor.QNNRegressor(ansatz, estimator, gradient_estimator, optimizer, operator=<factory>, x_norm_range=1.0, y_norm_range=0.7, do_x_scale=True, do_y_scale=True, n_outputs=1, y_exp_ratio=2.2, trained_param=None, _pred_cache=<factory>)[source]#

Bases: object

Class to solve regression problems with quantum neural networks. The out is taken as expectation values of Pauli Z operators acting on the first qubit. i.e., output is <Z_0>.

Parameters:

Example

>>> from quri_parts.qulacs.estimator import (
>>>     create_qulacs_vector_concurrent_estimator,
>>>     create_qulacs_vector_concurrent_parametric_estimator,
>>> )
>>> from quri_parts.core.estimator.gradient import (
>>>     create_numerical_gradient_estimator,
>>> )
>>> n_qubit = 3
>>> depth = 3
>>> time_step = 0.5
>>> estimator = create_qulacs_vector_concurrent_estimator()
>>> gradient_estimator = create_numerical_gradient_estimator(
>>>     create_qulacs_vector_concurrent_parametric_estimator()
>>> )
>>> circuit = create_qcl_ansatz(n_qubit, depth, time_step, 0)
>>> circuit = create_qcl_ansatz(n_qubit, depth, time_step, 0)
>>> qnn = QNNRegressor(n_qubit, circuit, estimator, gradient_estimator, solver)
>>> qnn.fit(x_train, y_train, maxiter)
>>> y_pred = qnn.predict(x_test)
ansatz: LearningCircuit#
estimator: BaseEstimator#
gradient_estimator: Callable[[Union[Operator, PauliLabel], _ParametricStateT, Sequence[float]], Estimates[complex]]#
optimizer: Optimizer#
operator: List[Union[Operator, PauliLabel]]#
x_norm_range: float = 1.0#
y_norm_range: float = 0.7#
n_qubit: int#
do_x_scale: bool = True#
do_y_scale: bool = True#
n_outputs: int = 1#
y_exp_ratio: float = 2.2#
trained_param: Optional[npt.NDArray[np.float64]] = None#
fit(x_train, y_train, maxiter=20)[source]#

Fit the model to the training data.

Parameters:
  • x_train (ndarray[tuple[int, ...], dtype[float64]]) – Input data whose shape is (n_samples, n_features).

  • y_train (ndarray[tuple[int, ...], dtype[float64]]) – Output data whose shape is (n_samples, n_outputs).

  • batch_size – The number of samples in each batch.

Return type:

None

cost_fn(x_scaled, y_scaled, params)[source]#

Calculate the cost function for solver.

Parameters:
  • x_batched – Input data whose shape is (batch_size, n_features).

  • y_batched – Output data whose shape is (batch_size, n_outputs).

  • params (npt.NDArray[np.float64]) – Parameters for the quantum circuit.

  • x_scaled (ndarray[tuple[int, ...], dtype[float64]]) –

  • y_scaled (ndarray[tuple[int, ...], dtype[float64]]) –

Returns:

Cost function value.

Return type:

cost

predict(x_test)[source]#

Predict outcome for each input data in x_test.

Parameters:

x_test (ndarray[tuple[int, ...], dtype[float64]]) – Input data whose shape is (batch_size, n_features).

Returns:

Predicted outcome.

Return type:

y_pred

grad_fn(x_scaled, y_scaled, params)[source]#

Calculate the gradient of the cost function for solver.

Parameters:
  • x_batched – Input data whose shape is (batch_size, n_features).

  • y_batched – Output data whose shape is (batch_size, n_outputs).

  • params (npt.NDArray[np.float64]) – Parameters for the quantum circuit.

  • x_scaled (ndarray[tuple[int, ...], dtype[float64]]) –

  • y_scaled (ndarray[tuple[int, ...], dtype[float64]]) –

Returns:

Gradient of the cost function.

Return type:

grads

Module contents#

class scikit_quri.qnn.QNNClassifier(ansatz, num_class, estimator, gradient_estimator, optimizer, operator=<factory>, x_norm_range=1.0, do_x_scale=True, y_exp_ratio=2.2, trained_param=None, _pred_cache=<factory>)[source]

Bases: object

Class to solve classification problems by quantum neural networks. The prediction is made by making a vector which predicts one-hot encoding of labels. The prediction is made by 1. taking expectation values of Pauli Z operator of each qubit <Z_i>, 2. taking softmax function of the vector (<Z_0>, <Z_1>, ..., <Z_{n-1}>).

Parameters:

Example

>>> from scikit_quri.qnn.classifier import QNNClassifier
>>> from scikit_quri.circuit import create_qcl_ansatz
>>> from quri_parts.core.estimator.gradient import (
>>>     create_numerical_gradient_estimator,
>>> )
>>> from quri_parts.qulacs.estimator import (
>>>     create_qulacs_vector_concurrent_estimator,
>>>     create_qulacs_vector_concurrent_parametric_estimator,
>>> )
>>> from quri_parts.algo.optimizer import Adam
>>> num_class = 3
>>> nqubit = 5
>>> c_depth = 3
>>> time_step = 0.5
>>> circuit = create_qcl_ansatz(nqubit, c_depth, time_step, 0)
>>> adam = Adam()
>>> estimator = create_qulacs_vector_concurrent_estimator()
>>> gradient_estimator = create_numerical_gradient_estimator(
>>>    create_qulacs_vector_concurrent_parametric_estimator(), delta=1e-10
>>> )
>>> qnn = QNNClassifier(circuit, num_class, estimator, gradient_estimator, adam)
>>> qnn.fit(x_train, y_train, maxiter)
>>> y_pred = qnn.predict(x_test).argmax(axis=1)
ansatz: LearningCircuit
num_class: int
estimator: BaseEstimator
gradient_estimator: Callable[[Union[Operator, PauliLabel], _ParametricStateT, Sequence[float]], Estimates[complex]]
optimizer: Optimizer
operator: List[Union[Operator, PauliLabel]]
x_norm_range: float = 1.0
do_x_scale: bool = True
y_exp_ratio: float = 2.2
trained_param: Optional[npt.NDArray[np.float64]] = None
n_qubit: int
fit(x_train, y_train, maxiter=100)[source]
Parameters:
  • x_train (ndarray[tuple[int, ...], dtype[float64]]) – List of training data inputs whose shape is (n_samples, n_features).

  • y_train (ndarray[tuple[int, ...], dtype[int64]]) – List of labels to fit. Labels must be represented as integers. Shape is (n_samples,).

  • maxiter (int) – The number of maximum iterations for the optimizer.

Returns:

None

predict(x_test)[source]

Predict outcome for each input data in x_test. This method returns the predicted outcome as a vector of probabilities for each class. :param x_test: Input data whose shape is (n_samples, n_features).

Returns:

Predicted outcome whose shape is (n_samples, num_class).

Return type:

y_pred

Parameters:

x_test (ndarray[tuple[int, ...], dtype[float64]]) –

cost_func(x_scaled, y_train, params)[source]
Parameters:
Return type:

float

cost_func_grad(x_scaled, y_train, params)[source]
Parameters:
Return type:

ndarray[tuple[int, …], dtype[float64]]

class scikit_quri.qnn.QNNRegressor(ansatz, estimator, gradient_estimator, optimizer, operator=<factory>, x_norm_range=1.0, y_norm_range=0.7, do_x_scale=True, do_y_scale=True, n_outputs=1, y_exp_ratio=2.2, trained_param=None, _pred_cache=<factory>)[source]

Bases: object

Class to solve regression problems with quantum neural networks. The out is taken as expectation values of Pauli Z operators acting on the first qubit. i.e., output is <Z_0>.

Parameters:

Example

>>> from quri_parts.qulacs.estimator import (
>>>     create_qulacs_vector_concurrent_estimator,
>>>     create_qulacs_vector_concurrent_parametric_estimator,
>>> )
>>> from quri_parts.core.estimator.gradient import (
>>>     create_numerical_gradient_estimator,
>>> )
>>> n_qubit = 3
>>> depth = 3
>>> time_step = 0.5
>>> estimator = create_qulacs_vector_concurrent_estimator()
>>> gradient_estimator = create_numerical_gradient_estimator(
>>>     create_qulacs_vector_concurrent_parametric_estimator()
>>> )
>>> circuit = create_qcl_ansatz(n_qubit, depth, time_step, 0)
>>> circuit = create_qcl_ansatz(n_qubit, depth, time_step, 0)
>>> qnn = QNNRegressor(n_qubit, circuit, estimator, gradient_estimator, solver)
>>> qnn.fit(x_train, y_train, maxiter)
>>> y_pred = qnn.predict(x_test)
ansatz: LearningCircuit
estimator: BaseEstimator
gradient_estimator: Callable[[Union[Operator, PauliLabel], _ParametricStateT, Sequence[float]], Estimates[complex]]
optimizer: Optimizer
operator: List[Union[Operator, PauliLabel]]
x_norm_range: float = 1.0
y_norm_range: float = 0.7
n_qubit: int
do_x_scale: bool = True
do_y_scale: bool = True
n_outputs: int = 1
y_exp_ratio: float = 2.2
trained_param: Optional[npt.NDArray[np.float64]] = None
fit(x_train, y_train, maxiter=20)[source]

Fit the model to the training data.

Parameters:
  • x_train (ndarray[tuple[int, ...], dtype[float64]]) – Input data whose shape is (n_samples, n_features).

  • y_train (ndarray[tuple[int, ...], dtype[float64]]) – Output data whose shape is (n_samples, n_outputs).

  • batch_size – The number of samples in each batch.

Return type:

None

cost_fn(x_scaled, y_scaled, params)[source]

Calculate the cost function for solver.

Parameters:
  • x_batched – Input data whose shape is (batch_size, n_features).

  • y_batched – Output data whose shape is (batch_size, n_outputs).

  • params (npt.NDArray[np.float64]) – Parameters for the quantum circuit.

  • x_scaled (ndarray[tuple[int, ...], dtype[float64]]) –

  • y_scaled (ndarray[tuple[int, ...], dtype[float64]]) –

Returns:

Cost function value.

Return type:

cost

predict(x_test)[source]

Predict outcome for each input data in x_test.

Parameters:

x_test (ndarray[tuple[int, ...], dtype[float64]]) – Input data whose shape is (batch_size, n_features).

Returns:

Predicted outcome.

Return type:

y_pred

grad_fn(x_scaled, y_scaled, params)[source]

Calculate the gradient of the cost function for solver.

Parameters:
  • x_batched – Input data whose shape is (batch_size, n_features).

  • y_batched – Output data whose shape is (batch_size, n_outputs).

  • params (npt.NDArray[np.float64]) – Parameters for the quantum circuit.

  • x_scaled (ndarray[tuple[int, ...], dtype[float64]]) –

  • y_scaled (ndarray[tuple[int, ...], dtype[float64]]) –

Returns:

Gradient of the cost function.

Return type:

grads

class scikit_quri.qnn.QNNGenerator(circuit, solver, sampler, n_shots=1024, kernel=None, fitting_qubit=None)[source]

Bases: object

Quantum Circuit Born Machine trained with MMD loss.

Parameters:
  • circuit (LearningCircuit) – Parametric circuit (ansatz). The input portion of the circuit is bound to a constant np.array([0]) placeholder — this class learns an unconditional distribution, so any add_input_* gates should be avoided.

  • solver (Optimizer) – Optimizer driving theta updates.

  • sampler (BaseSampler) – Sampling backend implementing BaseSampler.

  • n_shots (int) – Number of measurement shots per circuit evaluation. Used for cost, gradient (per shift), and predict.

  • kernel (Optional[Callable[[ndarray[tuple[int, ...], dtype[_ScalarType_co]], ndarray[tuple[int, ...], dtype[_ScalarType_co]]], ndarray[tuple[int, ...], dtype[_ScalarType_co]]]]) – Kernel K(x, y) -> (n_x, n_y) for the MMD loss. x and y are arrays of bit-string integers. Defaults to a Gaussian mixture from default_gaussian_mixture_kernel().

  • fitting_qubit (Optional[int]) – Number of qubits used to represent the output distribution. When less than circuit.n_qubits the higher qubits are marginalized out (z mod 2^fitting_qubit). Defaults to circuit.n_qubits.

Notes

Parameter-shift gradients are computed at the learning-parameter level (length = circuit.learning_params_count). This is exact when each learning parameter controls a single Pauli rotation gate; circuits using share_with to share one learning parameter across multiple gates will receive an approximate gradient — the cost function itself is unaffected.

fit(train_data, maxiter=100)[source]

Train against a sample-list target distribution.

Parameters:
  • train_data (ndarray[tuple[int, ...], dtype[int64]]) – Array of bit-string integers; the empirical distribution of these is the target.

  • maxiter (int) – Maximum optimizer iterations.

Return type:

None

fit_direct_distribution(p, maxiter=100, n_target_samples=10000, seed=0)[source]

Train against a target probability vector.

Internally samples n_target_samples bit strings from p and delegates to fit(). The MMD estimator is sample-based.

Parameters:
  • p (ndarray[tuple[int, ...], dtype[float64]]) – Target probability vector of length 2^fitting_qubit.

  • maxiter (int) – Maximum optimizer iterations.

  • n_target_samples (int) – Number of target-distribution samples.

  • seed (int) – Seed for the target sampler.

Return type:

None

predict(n_shots=None)[source]

Estimate the model’s output probability vector via sampling.

Parameters:

n_shots (Optional[int]) – Override sampling shots. Defaults to self.n_shots.

Returns:

Empirical probability vector of length 2^fitting_qubit. Has shot noise of order 1/sqrt(n_shots).

Return type:

ndarray[tuple[int, …], dtype[float64]]

cost_func(theta, train_samples)[source]

Estimate MMD^2(model, target) with self.n_shots model samples.

Parameters:
Return type:

float