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, 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: 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#
y_norm_range: float = 0.7#
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#
n_qubit: int#
predict_inner_cache: Dict[Tuple[bytes, bytes], ndarray[tuple[int, ...], dtype[float64]]]#
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#

class scikit_quri.qnn.generation.QNNGenerator(circuit, solver, kernel_type, gauss_sigma, fitting_qubit)[source]#

Bases: object

Class 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.

Parameters:
fit_direct_distribution(train_scaled, maxiter)[source]#
Parameters:
Return type:

Tuple[float, List[float]]

predict()[source]#
Return type:

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

conving(data_diff)[source]#
Parameters:

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

Return type:

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

cost_func(theta, train_scaled)[source]#
Parameters:
Return type:

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

scikit_quri.qnn.kernel_tsne module#

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

Bases: object

入力データXに対して,量子回路を計算してcacheしておくClass

Parameters:

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

get(input)[source]#

入力データXに対して,cacheされた量子状態を返す.もしcacheされていない場合は計算してcacheする

Parameters:

input (ndarray[tuple[int, ...], dtype[float64]]) – 入力データX

Returns:

量子状態

Return type:

GeneralCircuitQuantumState

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

Bases: object

quri-partsのoverlap_estimatorの代替Class (n_data:500のとき,x60 faster)

Parameters:

states (List[GeneralCircuitQuantumState]) –

calc_all_qula_states()[source]#

cache用に予め全ての量子状態をqulacsのstateに変換

estimate(i, j)[source]#

与えられた量子状態のi番目とj番目の内積の絶対値の二乗を計算

Parameters:
  • i (int) – 量子状態のindex(ket)

  • j (int) – 量子状態のindex(bra)

Returns:

|<φi|φj>|^2

Return type:

float

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

Bases: object

基本的なTSNEの実装

calc_probabilities_p(X_train)[source]#

p行列を計算する

Parameters:

X_train (NDArray[np.float64]) – 入力データ

Returns:

t-sneのp行列 (X_trainのサイズ, X_trainのサイズ)

Return type:

p_probs (NDArray[np.float64])

calc_probabilities_p_state(X_train_state)[source]#

p行列を計算する

Parameters:

X_train_state (List[GeneralCircuitQuantumState]) – 量子状態に変換した入力データ

Returns:

t-sneのp行列 (X_trainのサイズ, X_trainのサイズ)

Return type:

p_probs (NDArray[np.float64])

calc_probabilities_q(c_data)[source]#

q行列を計算する

Parameters:

c_data (NDArray[np.float64]) – 入力データ(論文ではy)

Returns:

t-sneのq行列 (c_dataのサイズ, c_dataのサイズ)

Return type:

q_probs (NDArray[np.float64])

joint_probabilities(sq_distance, perplexity)[source]#
Parameters:
binary_search_perplexity(sq_distance, perplexity)[source]#

二分探索で分散をperplexityにする

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

Calculate the distances by Euclidean distance between the data

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

Bases: object

quantum kernel t-sneで学習するためのClass

init(pqc_f, theta)[source]#
Parameters:
Return type:

None

calc_loss(p_prob, q_prob)[source]#

最適化するためのlossを計算

Parameters:
  • p_prob (NDArray[np.float64]) – p_ij

  • q_prob (NDArray[np.float64]) – q_ij

calc_grad(alpha, p_prob, fidelity)[source]#
Parameters:
cost_f(alpha, p_prob, fidelity)[source]#
Parameters:
generate_X_train_state(X_train)[source]#

X_train(NDAarray[np.float64])から量子状態のリストを生成

Parameters:

X_train (NDArray[np.float64]) – 64入力データ

Returns:

量子状態のリスト

Return type:

X_train_state (List[GeneralCircuitQuantumState])

train(X_train, y_label, method='Powell')[source]#
Parameters:
transform(X_test)[source]#

学習したαを使ってyを計算

Parameters:

X_test (NDArray[np.float64]) – テストデータ

Returns:

低次元表現

Return type:

y (NDArray[np.float64])

calc_y(fidelity, alpha)[source]#

fidelityとαからyを計算

Parameters:
Return type:

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

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

入力データXとpqc_f,thetaを受け取って、量子状態を計算する

Parameters:
Return type:

GeneralCircuitQuantumState

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

data==data_trの場合,fidelity( |<φi|φj>|^2 ) を計算

Parameters:

pqs_f_helper (pqc_f_helper) –

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

data != data_trの場合,fidelity( |<φi|φj>|^2 )を計算

Parameters:

pqs_f_helper (pqc_f_helper) –

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

yをplotする

Parameters:
  • y (NDArray[np.float64]) – 低次元表現

  • y_label (NDArray[np.int64]) – ラベル

  • title (str) – タイトル

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)[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: Callable[[Sequence[Union[Operator, PauliLabel]], Sequence[Union[CircuitQuantumState, QuantumStateVector]]], Iterable[Estimate[complex]]]#
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#