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, y_norm_range=0.7, do_x_scale=True, do_y_scale=True, n_outputs=1, y_exp_ratio=2.2, trained_param=None, predict_inner_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) –
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]]) –
predict_inner_cache (Dict[Tuple[bytes, bytes], ndarray[tuple[int, ...], dtype[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#
- class scikit_quri.qnn.generation.QNNGenerator(circuit, solver, kernel_type, gauss_sigma, fitting_qubit)[source]#
Bases:
objectClass to generation problems by quantum neural networks. This class is only working with a simulator. depending on qulacs. It is not working with real quantum computers.
- Parameters:
circuit (LearningCircuit) – The learning circuit to be used.
solver (Optimizer) – The optimizer to be used for training.
kernel_type (Literal['gauss', 'exp_hamming', 'same']) – The type of kernel to be used. exp_hamming is not implemented yet.
gauss_sigma (float) – The sigma value for Gaussian kernel.
fitting_qubit (int) – The number of qubits to be used for fitting.
- fit(train_data, maxiter=100)[source]#
- Params:
train_data: The training data to be used for fitting. maxiter: The maximum number of iterations for the optimizer. Default is 100.
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:
objectAlternative implementation of quri-parts’ overlap estimator using qulacs directly. Approximately 60x faster than the quri-parts implementation for n_data=500.
- Parameters:
states (List[GeneralCircuitQuantumState]) –
- 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_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.
- 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]#
Compute the numerical gradient of the loss with respect to alpha using central differences.
- 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:
Gradient array of the same shape as 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.
- 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
"adam","COBYLA", or"Powell". 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)[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, y_norm_range=0.7, do_x_scale=True, do_y_scale=True, n_outputs=1, y_exp_ratio=2.2, trained_param=None, predict_inner_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) –
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]]) –
predict_inner_cache (Dict[Tuple[bytes, bytes], ndarray[tuple[int, ...], dtype[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).
- 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)[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
- class scikit_quri.qnn.QNNGenerator(circuit, solver, kernel_type, gauss_sigma, fitting_qubit)[source]#
Bases:
objectClass to generation problems by quantum neural networks. This class is only working with a simulator. depending on qulacs. It is not working with real quantum computers.
- Parameters:
circuit (LearningCircuit) – The learning circuit to be used.
solver (Optimizer) – The optimizer to be used for training.
kernel_type (Literal['gauss', 'exp_hamming', 'same']) – The type of kernel to be used. exp_hamming is not implemented yet.
gauss_sigma (float) – The sigma value for Gaussian kernel.
fitting_qubit (int) – The number of qubits to be used for fitting.
- fit(train_data, maxiter=100)[source]#
- Params:
train_data: The training data to be used for fitting. maxiter: The maximum number of iterations for the optimizer. Default is 100.