### Install Example Dependencies Source: https://squlearn.github.io/index.html Install the required packages to run the examples provided with sQUlearn. ```bash pip install .[examples] ``` -------------------------------- ### Install sQUlearn with Example Dependencies Source: https://squlearn.github.io/_sources/install/install.rst.txt Install sQUlearn along with packages required to run all examples. ```bash pip install squlearn[examples] ``` -------------------------------- ### Install sQUlearn with Documentation Dependencies Source: https://squlearn.github.io/_sources/install/install.rst.txt Install sQUlearn along with packages necessary for building the documentation. ```bash pip install squlearn[docs] ``` -------------------------------- ### Install sQUlearn from GitHub Source: https://squlearn.github.io/index.html Install sQUlearn directly from its GitHub repository using SSH. ```bash pip install git+ssh://git@github.com:sQUlearn/squlearn.git ``` -------------------------------- ### Install sQUlearn with Development Dependencies Source: https://squlearn.github.io/_sources/install/install.rst.txt Install sQUlearn along with packages useful for development. ```bash pip install squlearn[dev] ``` -------------------------------- ### Executor Initialization Examples Source: https://squlearn.github.io/modules/generated/squlearn.Executor.html Demonstrates various ways to initialize the Executor class with different quantum computing frameworks and backends. ```APIDOC ## Executor Initialization Examples ### PennyLane Initialization ```python from squlearn import Executor import pennylane as qml # Executor with a PennyLane device (statevector) executor = Executor(qml.device("default.qubit")) # Executor with a PennyLane device (shot-based) executor = Executor(qml.device("default.qubit", shots=1000)) # Executor with a PennyLane lightning device executor = Executor(qml.device("lightning.qubit")) # Executor with an AWS Braket device with 4 qubits # (requires a valid AWS credential to be set) dev = qml.device( "braket.aws.qubit", device_arn="arn:aws:braket:::device/quantum-simulator/amazon/sv1", wires=4 ) executor = Executor(dev) ``` ### Qulacs Initialization ```python from squlearn import Executor # Executor with Qulacs backend executor = Executor("qulacs") ``` ### Qiskit Initialization ```python from squlearn import Executor from qiskit_ibm_runtime import QiskitRuntimeService # Executor with a ideal simulator backend exec = Executor("statevector_simulator") # Executor with a shot-based simulator backend and 1000 shots exec = Executor("qasm_simulator") exec.set_shots(1000) # Executor with a IBM Quantum backend (with context manager - recommended) # Session is automatically closed after the with block with Executor(service.backend('ibm_kingston'), caching=True, cache_dir='cache', log_file="log.log") as executor: # Your quantum computations here pass # Executor with a IBM Quantum backend (without context manager - not recommended) service = QiskitRuntimeService(channel="ibm_quantum_platform", token="INSERT_YOUR_TOKEN_HERE") executor = Executor(service.backend('ibm_kingston')) # Make sure to close the session when done try: # Your code here pass finally: executor.close_session() ``` ``` -------------------------------- ### QGPR Example Source: https://squlearn.github.io/modules/generated/squlearn.kernel.QGPR.html Demonstrates how to initialize and use the QGPR class for regression. This involves setting up an encoding circuit, a quantum kernel, and then fitting and predicting using the QGPR model. ```python from squlearn import Executor from squlearn.encoding_circuit import HubregtsenEncodingCircuit from squlearn.kernel.lowlevel_kernel import FidelityKernel from squlearn.kernel import QGPR enc_circ = HubregtsenEncodingCircuit(num_qubits=num_qubits, num_layers=2) q_kernel = FidelityKernel(encoding_circuit=enc_circ, executor=Executor()) q_kernel.assign_parameters(np.random.rand(enc_circ.num_parameters)) qgpr_ansatz = QGPR(quantum_kernel=q_kernel) qgpr_ansatz.fit(sample_train,label_train) qgpr_ansatz.predict(sample_test) ``` -------------------------------- ### Simple Kernel Method Example Source: https://squlearn.github.io/user_guide/kernel_methods.html This snippet shows how to initialize and fit a kernel method model with sample training data. Ensure the 'qkrr' object is properly instantiated before use. ```python x_train = [[0.1], [0.2], [0.3], [0.4], [0.5]] y_train = [0.1, 0.2, 0.3, 0.4, 0.5] qkrr.fit(X=x_train, y=y_train) ``` -------------------------------- ### QGPC Example with Quantum Kernel Source: https://squlearn.github.io/modules/generated/squlearn.kernel.QGPC.html Demonstrates how to use the QGPC class with a FidelityKernel for classification. This involves setting up an encoding circuit, a quantum kernel, and then fitting and predicting with the QGPC model. ```python from sklearn.datasets import load_iris from squlearn import Executor from squlearn.encoding_circuit import HubregtsenEncodingCircuit from squlearn.kernel.lowlevel_kernel import FidelityKernel from squlearn.kernel import QGPC X, y = load_iris(return_X_y=True) enc_circ = HubregtsenEncodingCircuit(num_qubits=X.shape[1], num_layers=2) q_kernel = FidelityKernel(encoding_circuit=enc_circ, executor=Executor()) q_kernel.assign_parameters(np.random.rand(enc_circ.num_parameters)) qgpc_ansatz = QGPC(quantum_kernel=q_kernel) qgpc_ansatz.fit(X, y) qgpc_ansatz.score(X, y) 0.98... qgpc_ansatz.predict_proba(X[:2,:]) array([[0.85643716, 0.07037611, 0.07318673], [0.80314475, 0.09988938, 0.09696586]]) ``` -------------------------------- ### Install Development Version of sQUlearn Source: https://squlearn.github.io/_sources/install/install.rst.txt Install the latest version from the 'develop' branch of the GitHub repository. ```bash pip install git+https://github.com/sQUlearn/squlearn.git@develop ``` -------------------------------- ### QSVC Example: Quantum Support Vector Classification Source: https://squlearn.github.io/modules/generated/squlearn.kernel.QSVC.html Demonstrates how to use QSVC for classification with a ProjectedQuantumKernel. This example involves setting up an encoding circuit, defining a quantum kernel, preparing data, training the QSVC model, and evaluating its performance on a test set. ```python import numpy as np from sklearn.datasets import make_moons from sklearn.model_selection import train_test_split from squlearn import Executor from squlearn.encoding_circuit import HubregtsenEncodingCircuit from squlearn.kernel.qsvc import QSVC from squlearn.kernel.lowlevel_kernel import ProjectedQuantumKernel encoding_circuit = HubregtsenEncodingCircuit(num_qubits=2, num_layers=2) kernel = ProjectedQuantumKernel( encoding_circuit, executor=Executor(), initial_parameters=np.random.rand(encoding_circuit.num_parameters) ) X, y = make_moons(n_samples=100, noise=0.3, random_state=0) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) qsvc = QSVC(quantum_kernel=kernel) qsvc.fit(X_train, y_train) print(f"The score on the test set is {qsvc.score(X_test, y_test)}") ``` -------------------------------- ### Setup Quantum Circuit and Projected Quantum Kernel Source: https://squlearn.github.io/examples/example_ode_solver.html Configure a quantum circuit for encoding and define a Projected Quantum Kernel (PQK) for ODE solving. This involves specifying circuit parameters, observables, and the executor. ```python num_qubits = 6 circuit = KyriienkoEncodingCircuit( num_qubits=num_qubits, encoding_style="chebyshev_product", # other options are chebyshev_tower, chebyshev_sparse, chebyshev_product variational_arrangement="HEA", # other option can be HEA (Hardware Efficient Ansatz), with consecutive entangling layers num_features=1, num_encoding_layers=2, num_variational_layers=1, ) observable = SummedPaulis(num_qubits, op_str=("XYZ"), include_identity=True) pqk = ProjectedQuantumKernel(executor=Executor("pennylane"), encoding_circuit=circuit) loss_ODE_squ = KODELoss( eq, symbols_involved_in_ode=[x, y, dydx], initial_values=initial_values, eta=1, ) circuit.draw("mpl") ``` -------------------------------- ### Executor Initialization with Backend Source: https://squlearn.github.io/_sources/user_guide/executor.rst.txt Initialize the Executor with a specific backend from QiskitRuntimeService. This setup is a prerequisite for adjusting primitive options. ```python from squlearn import Executor from qiskit_ibm_runtime import QiskitRuntimeService, Options service = QiskitRuntimeService(channel="ibm_quantum_platform", token="INSERT_YOUR_TOKEN_HERE") with Executor(service.backend("ibm_kingston")) as executor: ``` -------------------------------- ### Importing Libraries for QML and ML Workflows Source: https://squlearn.github.io/examples/example_kernel_grid_search.html Imports necessary libraries from squlearn for quantum kernel methods and scikit-learn for data processing and hyperparameter optimization. Ensure these libraries are installed. ```python import matplotlib.pylab as plt import numpy as np import pandas as pd import seaborn as sns from sklearn.model_selection import GridSearchCV from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardScaler from squlearn import Executor from squlearn.encoding_circuit import YZ_CX_EncodingCircuit from squlearn.kernel.lowlevel_kernel import FidelityKernel, ProjectedQuantumKernel from squlearn.kernel import QGPR, QSVR ``` -------------------------------- ### Install Bleeding-edge Version of sQUlearn Source: https://squlearn.github.io/_sources/install/install.rst.txt Install the latest version directly from the main branch of the GitHub repository. ```bash pip install git+https://github.com/sQUlearn/squlearn.git ``` -------------------------------- ### QNNClassifier Example Source: https://squlearn.github.io/modules/generated/squlearn.qnn.QNNClassifier.html Demonstrates the usage of QNNClassifier for a binary classification task. It includes data preprocessing, model initialization, training, and prediction. ```python from squlearn import Executor from squlearn.encoding_circuit import ChebyshevRx from squlearn.observables import SummedPaulis from squlearn.qnn import QNNClassifier, SquaredLoss from squlearn.optimizers import SLSQP from sklearn.datasets import make_blobs from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler X, y = make_blobs(60, centers=2, random_state=0) X = MinMaxScaler((-0.9, 0.9)).fit_transform(X) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42 ) clf = QNNClassifier( ChebyshevRx(4, 2), SummedPaulis(4), Executor(), SquaredLoss(), SLSQP(), np.random.rand(16), np.random.rand(5) ) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) ``` -------------------------------- ### Initialize and Use Executor with Context Manager Source: https://squlearn.github.io/modules/generated/squlearn.Executor.html Demonstrates the recommended way to initialize and use the Executor with an IBM Quantum backend within a context manager. This ensures proper session closure. Requires Qiskit Runtime service setup. ```python from squlearn import Executor from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum_platform", token="INSERT_YOUR_TOKEN_HERE") # Recommended: Use context manager with Executor(service.backend('ibm_kingston'), caching=True, cache_dir='cache', log_file="log.log") as executor: # Your quantum computations here pass ``` -------------------------------- ### Install Stable Release of sQUlearn Source: https://squlearn.github.io/_sources/install/install.rst.txt Use this command to install the latest stable version of sQUlearn from PyPI. ```bash pip install squlearn ``` -------------------------------- ### QSVR Example: Quantum Support Vector Regression Source: https://squlearn.github.io/modules/generated/squlearn.kernel.QSVR.html Demonstrates how to use QSVR for regression tasks. It involves setting up an encoding circuit, a quantum kernel, splitting data, initializing QSVR with the quantum kernel, fitting the model, and evaluating its performance on a test set. ```python import numpy as np from sklearn.model_selection import train_test_split from squlearn import Executor from squlearn.encoding_circuit import HubregtsenEncodingCircuit from squlearn.kernel.qsvr import QSVR from squlearn.kernel.lowlevel_kernel import ProjectedQuantumKernel encoding_circuit = HubregtsenEncodingCircuit(num_qubits=2, num_layers=2) kernel = ProjectedQuantumKernel( encoding_circuit, executor=Executor(), initial_parameters=np.random.rand(encoding_circuit.num_parameters)) X = np.linspace(0, np.pi, 100) y = np.sin(X) X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0) qsvc = QSVR(quantum_kernel=kernel) qsvc.fit(X_train, y_train) print(f"The score on the test set is {qsvc.score(X_test, y_test)}") ``` -------------------------------- ### QNNRegressor Example with ODELoss for Differential Equations Source: https://squlearn.github.io/modules/generated/squlearn.qnn.QNNRegressor.html Illustrates using QNNRegressor with ODELoss to solve differential equations. This example sets up a symbolic differential equation, initial conditions, and uses an Adam optimizer with learning rate decay. The QNN is configured with a KyriienkoEncodingCircuit and a SummedPaulis observable. ```python import numpy as np import sympy as sp import matplotlib.pyplot as plt from squlearn import Executor from squlearn.encoding_circuit import KyriienkoEncodingCircuit from squlearn.observables import SummedPaulis from squlearn.qnn import QNNRegressor, ODELoss from squlearn.qnn.util import get_lr_decay from squlearn.optimizers import Adam t, y, dydt, = sp.symbols("t y dydt") eq = 20 * sp.exp(-20 * t * 0.1) * sp.sin(20 * t) + 20 * 0.1 * y + dydt initial_values = [1.0] loss_ODE = ODELoss( eq, ``` -------------------------------- ### ProjectedQuantumKernel Initialization and Usage Source: https://squlearn.github.io/modules/generated/squlearn.kernel.lowlevel_kernel.ProjectedQuantumKernel.html This snippet demonstrates how to initialize and use the ProjectedQuantumKernel to compute a kernel matrix. It shows the basic setup with an encoding circuit and executor, and then calls the evaluate method. ```APIDOC ## ProjectedQuantumKernel Computes the quantum kernel matrix by projecting quantum states onto a computational basis. ### Parameters * **encoding_circuit** (EncodingCircuit): The encoding circuit used to prepare quantum states. * **executor** (Executor): The executor to run the quantum circuits. * **measurement** (list[Observable], optional): A list of observables to measure. If None, the default measurement is used. Defaults to None. * **outer_kernel** (str, optional): The type of outer kernel to use. Can be 'matern', 'rational_quadratic', 'exp_sine_squared', or 'dot_product'. Defaults to None. * **hyperparameters** (dict, optional): A dictionary of hyperparameters for the outer kernel. Defaults to None. ### Example ```python import numpy as np from squlearn.encoding_circuit import ChebyshevTower from squlearn.kernel.lowlevel_kernel import ProjectedQuantumKernel from squlearn.util import Executor fm = ChebyshevTower(num_qubits=4, num_chebyshev=4) kernel = ProjectedQuantumKernel(encoding_circuit=fm, executor=Executor()) x = np.random.rand(10) kernel_matrix = kernel.evaluate(x.reshape(-1, 1), x.reshape(-1, 1)) print(kernel_matrix) ``` ``` -------------------------------- ### Initialize Executor with Qiskit Runtime Service and Options Source: https://squlearn.github.io/_sources/user_guide/executor.rst.txt Initialize the Executor using a QiskitRuntimeService backend and provide options for the estimator primitive. This example shows how to configure ZNE mitigation. ```python from squlearn import Executor from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum_platform", token="INSERT_YOUR_TOKEN_HERE") options = {"resilience":{"zne_mitigation" : True, "zne":{"noise_factors" : (1, 3, 5),"extrapolator":"linear" }} } with Executor(service.backend("ibm_kingston"), options_estimator=options) as executor: # Your quantum computations here pass ``` -------------------------------- ### Initialize ODELoss for a Cosine ODE with Custom Parameters Source: https://squlearn.github.io/modules/generated/squlearn.kernel.loss.ODELoss.html Demonstrates initializing ODELoss for the ODE (df(x)/dx) - cos(f(x)) = 0 with initial value f(0) = 0. This example also shows how to adjust the 'eta' parameter, which controls the weight of the initial-value penalty. ```python import sympy as sp from squlearn.kernel.loss import ODELoss x, f, dfdx = sp.symbols("x f dfdx") eq = dfdx - sp.cos(f) initial_values = [0] loss_ode = ODELoss( ode_functional=eq, initial_values=initial_values, symbols_involved_in_ode=[x, f, dfdx], eta=1.2, ) ``` -------------------------------- ### Initialize Executor with Options Source: https://squlearn.github.io/_sources/user_guide/executor.rst.txt Initialize the Executor with specific execution settings and options for the estimator primitive. This example demonstrates setting restart pauses, retry limits, and estimator options. ```python with Executor(execution="statevector_simulator", wait_restart=600, # Set 10 min pause between restarts of Jobs max_jobs_retries=10, # Set maximum number of restarts to 10 before aborting options_estimator=options # Set options for the Estimator primitive ) as executor: executor.set_shots(1234) # Shots can be adjusted after initialization # Your quantum computations here qnn.fit(X_train, y_train) ``` -------------------------------- ### Optimize Quantum Kernels with Kernel Target Alignment Source: https://squlearn.github.io/_sources/user_guide/kernel_methods.rst.txt Set up and train a Quantum Kernel Ridge Regression (QKRR) model using a ProjectedQuantumKernel optimized via Kernel Target Alignment (KTA) with the Adam optimizer. This example demonstrates the full workflow from circuit definition to model fitting. ```python from squlearn.util import Executor from squlearn.encoding_circuit import ChebyshevPQC from squlearn.optimizers import Adam from squlearn.kernel import ProjectedQuantumKernel, KernelOptimizer, QKRR from squlearn.kernel.loss import TargetAlignment # set up the encoding circuit encoding_circuit = ChebyshevPQC(num_qubits=4, num_layers=2) # set up the quantum kernel pqk_instance = ProjectedQuantumKernel(encoding_circuit, Executor()) # set up the optimizer adam_opt = Adam(options={"maxiter":100, "lr": 0.1}) # define KTA loss function kta_loss = TargetAlignment() # set up the kernel optimizer kernel_optimizer = KernelOptimizer(quantum_kernel=pqk_instance, loss=kta_loss, optimizer=adam_opt) # initialize the QKRR model with the kernel optimizer qkrr = QKRR(kernel_optimizer) # Simple example x_train = [[0.1], [0.2], [0.3], [0.4], [0.5]] y_train = [0.1, 0.2, 0.3, 0.4, 0.5] qkrr.fit(X=x_train, y=y_train) ``` -------------------------------- ### ProjectedQuantumKernel with Custom Measurements and Outer Kernel Source: https://squlearn.github.io/modules/generated/squlearn.kernel.lowlevel_kernel.ProjectedQuantumKernel.html This example shows how to customize the ProjectedQuantumKernel by providing a list of custom observables for measurement and specifying an 'matern' outer kernel with a given nu hyperparameter. ```APIDOC ## ProjectedQuantumKernel with Customization This example demonstrates customizing the `ProjectedQuantumKernel` with specific measurement observables and an outer kernel. ### Parameters * **encoding_circuit** (EncodingCircuit): The encoding circuit used to prepare quantum states. * **executor** (Executor): The executor to run the quantum circuits. * **measurement** (list[Observable]): A list of custom observables for measurement. * **outer_kernel** (str): Specifies the type of outer kernel, e.g., 'matern'. * **nu** (float): Hyperparameter for the 'matern' outer kernel. ### Example ```python import numpy as np from squlearn.encoding_circuit import ChebyshevTower from squlearn.kernel.lowlevel_kernel import ProjectedQuantumKernel from squlearn.util import Executor from squlearn.observables import CustomObservable from squlearn.kernel import QKRR fm = ChebyshevTower(num_qubits=4, num_chebyshev=4) # Create custom observables measurements = [] measurements.append(CustomObservable(4,"ZZZZ")) measurements.append(CustomObservable(4,"YYYY")) measurements.append(CustomObservable(4,"XXXX")) # Use Matern Outer kernel with nu=0.5 as a outer kernel hyperparameter kernel = ProjectedQuantumKernel(encoding_circuit=fm, executor=Executor(), measurement=measurements, outer_kernel="matern", nu=0.5) ml_method = QKRR(quantum_kernel=kernel) ``` ``` -------------------------------- ### Initialize ODELoss for a first-order ODE with custom eta Source: https://squlearn.github.io/modules/generated/squlearn.qnn.loss.ODELoss.html Example of initializing ODELoss for the ODE df(x)/dx - cos(f(x)) = 0 with initial values f(0) = 0. Demonstrates setting a custom 'eta' value to adjust the weight of the initial condition penalty. ```python import sympy as sp from squlearn.qnn.loss import ODELoss x, f, dfdx = sp.symbols("x f dfdx") eq = dfdx - sp.cos(f) initial_values = [0] loss_ode = ODELoss( eq, symbols_involved_in_ode=[x, f, dfdx], initial_values=initial_values, eta=1.2, ) ``` -------------------------------- ### QNNRegressor Example with ChebyshevRx and IsingHamiltonian Source: https://squlearn.github.io/modules/generated/squlearn.qnn.QNNRegressor.html Demonstrates the basic usage of QNNRegressor for a regression task. It initializes the regressor with a ChebyshevRx encoding circuit, an IsingHamiltonian observable, an Executor, SquaredLoss, and an SLSQP optimizer. The model is then trained on split data and used for prediction. ```python import numpy as np from squlearn import Executor from squlearn.encoding_circuit import ChebyshevRx from squlearn.observables import IsingHamiltonian from squlearn.qnn import QNNRegressor, SquaredLoss from squlearn.optimizers import SLSQP from sklearn.model_selection import train_test_split X, y = np.arange(0.1, 0.9, 0.01), np.log(np.arange(0.1, 0.9, 0.01)) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42 ) reg = QNNRegressor( ChebyshevRx(4, 1), IsingHamiltonian(4, I="S", Z="S", ZZ="S"), Executor(), SquaredLoss(), SLSQP(), np.random.rand(16), np.random.rand(5) ) reg.fit(X_train, y_train) y_pred = reg.predict(X_test[:5]) ``` -------------------------------- ### Get Squared Operator for Summed Pauli Operator Source: https://squlearn.github.io/modules/generated/squlearn.observables.observable_derivatives.ObservableDerivatives.html Shows how to obtain the squared form (O^2) of a SummedPaulis observable. This is useful when the observable's square is needed, for example, in variance calculations. ```python from squlearn.observables import SummedPaulis from squlearn.observables.observable_derivatives import ObservableDerivatives op = SummedPaulis(num_qubits=3) print(ObservableDerivatives(op).get_operator_squared()) ``` ```text SparsePauliOp(['III', 'IIZ', 'IZI', 'ZII', 'IZZ', 'ZIZ', 'ZZI'], coeffs=[, , , , , , ]) ``` -------------------------------- ### Initialize ProjectedQuantumKernel Source: https://squlearn.github.io/examples/example_kernel_digit_classification.html Sets up a ProjectedQuantumKernel for calculating kernel matrices. This involves specifying the encoding circuit, an executor for running quantum computations, the measurement strategy, the type of outer kernel, initial trainable parameters, and the gamma parameter for the Gaussian outer kernel. ```python kernel = ProjectedQuantumKernel( encoding_circuit=encoding_circuit, executor=Executor(), measurement="XYZ", outer_kernel="gaussian", initial_parameters=np.random.rand(encoding_circuit.num_parameters), gamma=0.5, ) ``` -------------------------------- ### get_derivative Method Examples Source: https://squlearn.github.io/modules/generated/squlearn.observables.observable_derivatives.ObservableDerivatives.html Examples demonstrating the usage of the `get_derivative` method for calculating different types of derivatives. ```APIDOC ## Method: get_derivative ### Description Determine the derivative of the observable. ### Parameters * **derivative** (_str_ _or_ _tuple_) – String or tuple of parameters for specifying the derivation. See `ObservableDerivatives` for more information. ### Returns Differentiated observable in OpTree format ### Example: first-order derivative of the Ising Hamiltonian ```python from squlearn.observables import IsingHamiltonian from squlearn.observables.observable_derivatives import ObservableDerivatives op = IsingHamiltonian(num_qubits=3) print(ObservableDerivatives(op).get_derivative("dop")) ``` ### Example: Squared summed Pauli Operator ```python from squlearn.observables import SummedPaulis from squlearn.observables.observable_derivatives import ObservableDerivatives op = SummedPaulis(num_qubits=3) print(ObservableDerivatives(op).get_operator_squared()) ``` ``` -------------------------------- ### Select Backend for QNN Execution Source: https://squlearn.github.io/examples/example_qnn_backend_mitigation.html Configures the backend for QNN execution, choosing between a local simulator (FakeBelemV2) or a real IBM Quantum backend based on the 'local' flag. Error mitigation is disabled on local simulators. ```python local = True if local: backend = FakeBelemV2() else: service = QiskitRuntimeService() backend = service.least_busy(operational=True, simulator=False) print("Selected Backend:", backend.name) ``` -------------------------------- ### QRCClassifier Example: Classification of Moon example with Quantum Reservoir Computing Source: https://squlearn.github.io/modules/generated/squlearn.qrc.QRCClassifier.html This example demonstrates how to use QRCClassifier for a classification task on the moon dataset. It involves splitting the data, initializing the QRCClassifier with a specified encoding circuit and executor, and then fitting the model to the training data before making predictions on the test data. ```python from squlearn import Executor from squlearn.encoding_circuit import HubregtsenEncodingCircuit from squlearn.qrc import QRCClassifier from sklearn.datasets import make_moons from sklearn.model_selection import train_test_split X, y = make_moons(n_samples=1000, noise=0.2, random_state=42) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.33, random_state=42) clf = QRCClassifier(HubregtsenEncodingCircuit(num_qubits=4), Executor(), ml_model="linear", operators="random_paulis", num_operators=300, ) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) ``` -------------------------------- ### Pruned Hubregtsen Encoding Circuit Example Source: https://squlearn.github.io/modules/generated/squlearn.encoding_circuit.PrunedEncodingCircuit.html Demonstrates how to create and draw a pruned encoding circuit using the HubregtsenEncodingCircuit. This example shows initializing a HubregtsenEncodingCircuit and then creating a PrunedEncodingCircuit from it, specifying which parameters to prune. ```python from squlearn.encoding_circuit import HubregtsenEncodingCircuit,PrunedEncodingCircuit fm = HubregtsenEncodingCircuit(4,2) PrunedEncodingCircuit(fm,[4,7,11,15]).draw("mpl", num_features=2) ``` -------------------------------- ### Calculate Kernel Matrix with ProjectedQuantumKernel Source: https://squlearn.github.io/modules/generated/squlearn.kernel.lowlevel_kernel.ProjectedQuantumKernel.html Demonstrates how to initialize and use ProjectedQuantumKernel to compute a kernel matrix. Ensure necessary imports are included. ```python import numpy as np from squlearn.encoding_circuit import ChebyshevTower from squlearn.kernel.lowlevel_kernel import ProjectedQuantumKernel from squlearn.util import Executor fm = ChebyshevTower(num_qubits=4, num_chebyshev=4) kernel = ProjectedQuantumKernel(encoding_circuit=fm, executor=Executor()) x = np.random.rand(10) kernel_matrix = kernel.evaluate(x.reshape(-1, 1), x.reshape(-1, 1)) print(kernel_matrix) ``` ```text [[1.00000000e+00 4.06794475e-05 9.49463805e-03 9.32251830e-02 1.00951692e-03 6.45442026e-05 1.24839015e-02 1.72501703e-05 1.60224819e-01 9.31212263e-01] [4.06794475e-05 1.00000000e+00 3.00823782e-02 2.68739824e-03 2.03679424e-01 9.39710740e-01 2.31250462e-02 5.28290705e-01 1.38032573e-03 6.69069973e-05] [9.49463805e-03 3.00823782e-02 1.00000000e+00 5.67749051e-01 6.15479006e-01 6.28136328e-02 9.92685083e-01 2.30564806e-03 4.02050742e-01 2.20990267e-02] [9.32251830e-02 2.68739824e-03 5.67749051e-01 1.00000000e+00 1.36399426e-01 6.00665133e-03 6.39323079e-01 2.38149509e-04 9.56977901e-01 1.84058756e-01] [1.00951692e-03 2.03679424e-01 6.15479006e-01 1.36399426e-01 1.00000000e+00 3.47250768e-01 5.44185409e-01 2.17769276e-02 7.81319173e-02 2.34075959e-03] [6.45442026e-05 9.39710740e-01 6.28136328e-02 6.00665133e-03 3.47250768e-01 1.00000000e+00 4.90627670e-02 3.40590318e-01 3.05334315e-03 1.16250527e-04] [1.24839015e-02 2.31250462e-02 9.92685083e-01 6.39323079e-01 5.44185409e-01 4.90627670e-02 1.00000000e+00 1.75549208e-03 4.67125096e-01 2.87692102e-02] [1.72501703e-05 5.28290705e-01 2.30564806e-03 2.38149509e-04 2.17769276e-02 3.40590318e-01 1.75549208e-03 1.00000000e+00 1.38671329e-04 2.05412131e-05] [1.60224819e-01 1.38032573e-03 4.02050742e-01 9.56977901e-01 7.81319173e-02 3.05334315e-03 4.67125096e-01 1.38671329e-04 1.00000000e+00 2.93890695e-01] [9.31212263e-01 6.69069973e-05 2.20990267e-02 1.84058756e-01 2.34075959e-03 1.16250527e-04 2.87692102e-02 2.05412131e-05 2.93890695e-01 1.00000000e+00]] ``` -------------------------------- ### Setting up Quantum Kernels with Encoding Circuit Source: https://squlearn.github.io/examples/example_kernel_grid_search.html Initializes an encoding circuit and quantum kernels (FidelityKernel, ProjectedQuantumKernel) using Qiskit's StatevectorSimulator. The encoding circuit parameters will be varied during grid search. ```python encoding_circuit = YZ_CX_EncodingCircuit(num_qubits=4, num_layers=2, closed=False) executor = Executor() fidelity_kernel = FidelityKernel( encoding_circuit=encoding_circuit, executor=executor, parameter_seed=0 ) projected_kernel = ProjectedQuantumKernel( encoding_circuit=encoding_circuit, executor=executor, parameter_seed=0 ) encoding_circuit.draw("mpl", num_features=1) ``` -------------------------------- ### get_shots Source: https://squlearn.github.io/modules/generated/squlearn.qnn.lowlevel_qnn.lowlevel_qnn_qiskit.LowLevelQNNQiskit.html Gets the number of shots configured for the QNN execution. ```APIDOC ## get_shots ### Description Gets the number of shots configured for the QNN execution. ### Returns Number of shots. ``` -------------------------------- ### FidelityKernel Source: https://squlearn.github.io/modules/generated/squlearn.kernel.lowlevel_kernel.FidelityKernel.html Initializes the FidelityQuantum Kernel. ```APIDOC ## FidelityKernel ### Description Initializes the FidelityQuantum Kernel. ### Parameters * **encoding_circuit** (*EncodingCircuitBase*) – PQC encoding circuit. * **executor** (*Executor*) – Executor object. * **evaluate_duplicates** (*str*) – Option for evaluating duplicates (‘all’, ‘off_diagonal’, ‘none’). * **mit_depol_noise** (*Union_[str, None]*) – Option for mitigating depolarizing noise ("msplit" or "mmean") after Ref. [4]. Only meaningful for FQKs computed on a real backend. * **initial_parameters** (*Union_[np.ndarray, None]*) – Initial parameters for the encoding circuit. * **parameter_seed** (*Union_[int, None]*) – Seed for the random number generator for the parameter initialization, if initial_parameters is None. * **regularization** (*Union_[str, None]*) – Option for choosing different regularization techniques ("thresholding" or "tikhonov") after Ref. [4] for the training kernel matrix, prior to solving the linear system in the `fit()`-procedure. * **use_expectation** (*bool*) – Option for using the expectation value of a QNN circuit that computes the fidelity as the expectation value of the observable P0=|0⟩⟨0|⊗n. This is not very efficient in simulation, but allows the computation of derivatives of the kernel. ``` -------------------------------- ### Get Hessian from Tuple Source: https://squlearn.github.io/user_guide/observables.html Calculate the second-order derivative (Hessian) of an observable with respect to a specific parameter. Requires initializing ObservableDerivatives with the operator. ```python from squlearn.observables.observable_derivatives import ObservableDerivatives # Assuming 'op3' is a defined observable operator # op3 = ... deriv = ObservableDerivatives(op3) print("Second-order derivative w.r.t. p[0]:\n", deriv.get_derivative((deriv.parameter_vector[0],deriv.parameter_vector[0]))) ``` -------------------------------- ### Select Best IBM Quantum Backend with Executor Source: https://squlearn.github.io/user_guide/executor.html Initializes the Executor with a list of simulated IBM backends and trains a QNNRegressor. The 'quality' mode is used by default to select the best backend. The chosen backend is printed after training. ```python import warnings import numpy as np from qiskit_ibm_runtime.fake_provider import FakeManilaV2, FakeBelemV2, FakeAthensV2 from squlearn.util import Executor from squlearn.qnn import QNNRegressor from squlearn.observables import SummedPaulis from squlearn.encoding_circuit import ChebyshevPQC from squlearn.optimizers import Adam from squlearn.qnn.loss import SquaredLoss backends = [FakeBelemV2(), FakeAthensV2(), FakeManilaV2()] executor = Executor(backends, shots=10000) qnn = QNNRegressor( ChebyshevPQC(2), SummedPaulis(2), executor, SquaredLoss(), Adam({'maxiter':2}), # Two iteration for demonstration purposes only callback=None # Remove print of the progress bar for cleaner output ) with warnings.catch_warnings(): warnings.simplefilter("ignore") qnn.fit(np.array([[0.25],[0.75]]),np.array([0.25,0.75])) print("Chosen backend:", executor.backend) ``` -------------------------------- ### Getting Qiskit Primitives from Executor Source: https://squlearn.github.io/modules/generated/squlearn.Executor.html Demonstrates how to obtain Estimator and Sampler objects from an initialized Executor, ensuring all operations are routed through the executor. ```APIDOC ## Getting Qiskit Primitives from Executor ```python from squlearn import Executor # Initialize the Executor executor = Executor("statevector_simulator") # Get the Executor based Estimator with all executions routed through the Executor estimator = executor.get_estimator() # Get the Executor based Sampler with all executions routed through the Executor sampler = executor.get_sampler() # Run a circuit with the Executor based Sampler from qiskit.circuit.random import random_circuit circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1) job = sampler.run([(circuit,)]) result = job.result() ``` ``` -------------------------------- ### Setup Encoding Circuit for Regression Source: https://squlearn.github.io/user_guide/quantum_reservoir_computing.html Initialize an encoding circuit for regression tasks. The HubregtsenEncodingCircuit is used here with specified number of qubits and layers. ```python from squlearn.encoding_circuit import HubregtsenEncodingCircuit pqc = HubregtsenEncodingCircuit(num_qubits=10, num_layers=2) pqc.draw("mpl", num_features=1) ``` -------------------------------- ### Executor Initialization and Usage Source: https://squlearn.github.io/modules/generated/squlearn.Executor.html Demonstrates how to initialize the Executor class and use it within a context manager for proper session handling, especially when interacting with IBM Quantum backends. ```APIDOC ## `squlearn`.Executor ### Description A class for executing quantum jobs on IBM Quantum systems or simulators. The Executor class is the central component of sQUlearn, responsible for running quantum jobs. Both high- and low-level methods utilize the Executor class to execute jobs seamlessly. It for example automatically creates the necessary Qiskit primitives when they are required in the sQUlearn sub-program or takes care of the execution of PennyLane circuits. The Executor takes care about Qiskit Runtime session handling, result caching, and automatic restarts of failed jobs. ### Parameters * **_execution** (str | Backend | List[Backend] | QiskitRuntimeService | Session | BaseEstimatorV1 | BaseSamplerV1 | BaseEstimatorV2 | BaseSamplerV2 | Device) - The execution environment specification. * **_options_estimator** (Any | None) - Options for the estimator. * **_options_sampler** (Any | None) - Options for the sampler. * **_log_file** (str) - Path to a log file. Defaults to '' (no logging). * **_caching** (bool | None) - Whether to enable caching. Defaults to None. * **_cache_dir** (str) - Directory for caching results. Defaults to '_cache'. * **_max_session_time** (str) - Maximum session time. Defaults to '8h'. * **_max_jobs_retries** (int) - Maximum number of retries for failed jobs. Defaults to 10. * **_wait_restart** (int) - Time to wait before restarting a failed job. Defaults to 1. * **_shots** (int | None) - Number of shots for the execution. Defaults to None. * **_seed** (int | None) - Seed for random number generation. Defaults to None. * **_qpu_parallelization** (int | str | None) - QPU parallelization setting. Defaults to None. * **_auto_backend_mode** (str) - Automatic backend mode. Defaults to 'quality'. ### Important: Session Management When using the Executor with IBM Quantum backends or Sessions, it is **strongly recommended** to use the Executor within a context manager (`with` statement). This ensures that sessions are properly closed when you are done with the executor, avoiding unnecessary open sessions and preventing charges for unused sessions. ### Request Example ```python from squlearn import Executor from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum_platform", token="INSERT_YOUR_TOKEN_HERE") # Recommended: Use context manager with Executor(service.backend('ibm_kingston'), caching=True, cache_dir='cache', log_file="log.log") as executor: # Your quantum computations here pass ``` ``` -------------------------------- ### Initialize SLSQP Optimizer Source: https://squlearn.github.io/_sources/user_guide/quantum_neural_networks.rst.txt Instantiate the SLSQP optimizer wrapper from squlearn.optimizers. This optimizer can be configured with specific options, such as the maximum number of iterations. ```python from squlearn.optimizers import SLSQP ... slsqp = SLSQP(options={"maxiter": 100}) ... ``` -------------------------------- ### Adjust Sampler Options Dynamically Source: https://squlearn.github.io/_sources/user_guide/executor.rst.txt Modify sampler options after initializing the Executor. This example enables and configures dynamical decoupling for the sampler primitive. ```python from squlearn import Executor from qiskit_ibm_runtime import QiskitRuntimeService service = QiskitRuntimeService(channel="ibm_quantum_platform", token="INSERT_YOUR_TOKEN_HERE") with Executor(service.backend("ibm_kingston")) as executor: executor.sampler_options.dynamical_decoupling.enable = True executor.sampler_options.dynamical_decoupling.sequence_type = "XpXm" # Your quantum computations here pass ``` -------------------------------- ### Get Executor-based Qiskit Primitives Source: https://squlearn.github.io/modules/generated/squlearn.Executor.html Retrieve the Estimator and Sampler primitives from an initialized Executor. These primitives route all operations through the Executor's backend. ```python from squlearn import Executor # Initialize the Executor executor = Executor("statevector_simulator") # Get the Executor based Estimator with all execusions routed through the Executor estimator = executor.get_estimator() # Get the Executor based Sampler with all execusions routed through the Executor sampler = executor.get_sampler() # Run a circuit with the Executor based Sampler from qiskit.circuit.random import random_circuit circuit = random_circuit(2, 2, seed=1, measure=True).decompose(reps=1) job = sampler.run([(circuit,)]) result = job.result() ```