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:
objectClass 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:
ansatz (LearningCircuit) – Circuit to use in the learning.
num_class (int) – The number of classes; the number of qubits to measure. must be n_qubits >= num_class .
estimator (BaseEstimator) – Estimator to use. It must be a concurrent estimator.
gradient_estimator (Callable[[Union[Operator, PauliLabel], _ParametricStateT, Sequence[float]], Estimates[complex]]) – Gradient estimator to use.
optimizer (Optimizer) – Solver to use. use
AdamorLBFGSmethod.operator (List[Union[Operator, PauliLabel]]) –
x_norm_range (float) –
do_x_scale (bool) –
y_exp_ratio (float) –
trained_param (Optional[npt.NDArray[np.float64]]) –
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#
- estimator: BaseEstimator#
- gradient_estimator: Callable[[Union[Operator, PauliLabel], _ParametricStateT, Sequence[float]], Estimates[complex]]#
- operator: List[Union[Operator, PauliLabel]]#
- 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).
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.
- class scikit_quri.qnn.generation.QNNGenerator(circuit, solver, sampler, n_shots=1024, kernel=None, fitting_qubit=None)[source]#
Bases:
objectQuantum 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 anyadd_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.xandyare arrays of bit-string integers. Defaults to a Gaussian mixture fromdefault_gaussian_mixture_kernel().fitting_qubit (Optional[int]) – Number of qubits used to represent the output distribution. When less than
circuit.n_qubitsthe higher qubits are marginalized out (z mod 2^fitting_qubit). Defaults tocircuit.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 usingshare_withto share one learning parameter across multiple gates will receive an approximate gradient — the cost function itself is unaffected.- fit_direct_distribution(p, maxiter=100, n_target_samples=10000, seed=0)[source]#
Train against a target probability vector.
Internally samples
n_target_samplesbit strings frompand delegates tofit(). The MMD estimator is sample-based.
scikit_quri.qnn.kernel_tsne module#
- class scikit_quri.qnn.kernel_tsne.pqc_f_helper(pqs_f)[source]#
Bases:
objectHelper class that evaluates and caches quantum states for input data.
- class scikit_quri.qnn.kernel_tsne.overlap_estimator(states)[source]#
Bases:
objectMaterializes quri-parts quantum states into qulacs state vectors.
Holds a list of states and converts them to qulacs
QuantumStateobjects (cached inqula_states). Used byfidelity_gram()/fidelity_cross()to obtain the raw state vectors for a single vectorized overlap computation.- Parameters:
states (List[GeneralCircuitQuantumState]) –
- 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.
- scikit_quri.qnn.kernel_tsne.fidelity_cross(states, states_tr)[source]#
Compute the rectangular fidelity matrix |⟨φi|ψj⟩|² between two sets of states.
- Parameters:
states (List[GeneralCircuitQuantumState]) – Query states (rows).
states_tr (List[GeneralCircuitQuantumState]) – Reference states (columns).
- Returns:
Fidelity matrix of shape (len(states), len(states_tr)).
- Return type:
- class scikit_quri.qnn.kernel_tsne.TSNE(perplexity=30)[source]#
Bases:
objectBasic 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.
- 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.
- 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.
- 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.
- joint_probabilities(sq_distance, perplexity)[source]#
Compute the symmetric joint probability matrix from pairwise distances.
- 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.
- 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 expectsq_distancehere.
- class scikit_quri.qnn.kernel_tsne.quantum_kernel_tsne(perplexity=30, max_iter=400)[source]#
Bases:
objectt-SNE using a quantum kernel as the similarity measure in the high-dimensional space.
- calc_loss(p_prob, q_prob)[source]#
Compute the KL divergence loss KL(P || Q) used as the optimization objective.
- 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 givesdC/dalpha = fidelity^T @ dC/dy(fidelityis 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/Zwork, so a gradient step costs a singlecdist(y, y)instead of two (one for the value and one for the jacobian). Used by theL-BFGS-Bpath viascipy.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)wheregrad_alphais flattened likealpha.
- 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.
- 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.
- calc_y(fidelity, alpha)[source]#
Compute the low-dimensional embedding y = fidelity @ alpha.
- Parameters:
- Returns:
Low-dimensional embedding of shape (n_data, 2).
- Return type:
- 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:
- 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).
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.
- 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:
objectClass to solve regression problems with quantum neural networks. The out is taken as expectation values of
Pauli Zoperators acting on the first qubit. i.e., output is<Z_0>.- Parameters:
ansatz (LearningCircuit) – Circuit to use in the learning.
estimator (BaseEstimator) – Estimator to use. use
create_qulacs_vector_concurrent_estimator()method.gradient_estimator (Callable[[Union[Operator, PauliLabel], _ParametricStateT, Sequence[float]], Estimates[complex]]) – Gradient estimator to use. use
create_parameter_shift_gradient_estimator()orcreate_parameter_shift_gradient_estimator()method.optimizer (Optimizer) – Optimizer to use. use
AdamorLBFGSmethod.operator (List[Union[Operator, PauliLabel]]) –
x_norm_range (float) –
y_norm_range (float) –
do_x_scale (bool) –
do_y_scale (bool) –
n_outputs (int) –
y_exp_ratio (float) –
trained_param (Optional[npt.NDArray[np.float64]]) –
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]]#
- operator: List[Union[Operator, PauliLabel]]#
- 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.
- Returns:
Cost function value.
- Return type:
cost
- 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.
- 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:
objectClass 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:
ansatz (LearningCircuit) – Circuit to use in the learning.
num_class (int) – The number of classes; the number of qubits to measure. must be n_qubits >= num_class .
estimator (BaseEstimator) – Estimator to use. It must be a concurrent estimator.
gradient_estimator (Callable[[Union[Operator, PauliLabel], _ParametricStateT, Sequence[float]], Estimates[complex]]) – Gradient estimator to use.
optimizer (Optimizer) – Solver to use. use
AdamorLBFGSmethod.operator (List[Union[Operator, PauliLabel]]) –
x_norm_range (float) –
do_x_scale (bool) –
y_exp_ratio (float) –
trained_param (Optional[npt.NDArray[np.float64]]) –
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).
- cost_func(x_scaled, y_train, params)[source]
- 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:
objectClass to solve regression problems with quantum neural networks. The out is taken as expectation values of
Pauli Zoperators acting on the first qubit. i.e., output is<Z_0>.- Parameters:
ansatz (LearningCircuit) – Circuit to use in the learning.
estimator (BaseEstimator) – Estimator to use. use
create_qulacs_vector_concurrent_estimator()method.gradient_estimator (Callable[[Union[Operator, PauliLabel], _ParametricStateT, Sequence[float]], Estimates[complex]]) – Gradient estimator to use. use
create_parameter_shift_gradient_estimator()orcreate_parameter_shift_gradient_estimator()method.optimizer (Optimizer) – Optimizer to use. use
AdamorLBFGSmethod.operator (List[Union[Operator, PauliLabel]]) –
x_norm_range (float) –
y_norm_range (float) –
do_x_scale (bool) –
do_y_scale (bool) –
n_outputs (int) –
y_exp_ratio (float) –
trained_param (Optional[npt.NDArray[np.float64]]) –
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.
- 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.
- Returns:
Cost function value.
- Return type:
cost
- predict(x_test)[source]
Predict outcome for each input data in x_test.
- 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.
- 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:
objectQuantum 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 anyadd_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.xandyare arrays of bit-string integers. Defaults to a Gaussian mixture fromdefault_gaussian_mixture_kernel().fitting_qubit (Optional[int]) – Number of qubits used to represent the output distribution. When less than
circuit.n_qubitsthe higher qubits are marginalized out (z mod 2^fitting_qubit). Defaults tocircuit.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 usingshare_withto 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.
- fit_direct_distribution(p, maxiter=100, n_target_samples=10000, seed=0)[source]
Train against a target probability vector.
Internally samples
n_target_samplesbit strings frompand delegates tofit(). The MMD estimator is sample-based.
- predict(n_shots=None)[source]
Estimate the model’s output probability vector via sampling.