LoginSignup
0
0

More than 1 year has passed since last update.

OpflowQNN; Quantum Neural Networks【Qiskit】

Last updated at Posted at 2022-04-26

Assumption

Environments

  • JupyterNotebook
  • python3

About neural network

The NeuralNetwork represents the interface for all neural networks available in Qiskit Machine Learning. It exposes a forward and a backward pass taking the data samples and trainable weights as input. A NeuralNetwork does not contain any training capabilities, these are pushed to the actual algorithms / applications. Thus, a NeuralNetwork also does not store the values for trainable weights. In the following, different implementations of this interfaces are introduced.

What is Opflow QNN

Opflow Quantum Neural Network.

Instllation

$ pip install qiskit_machine_learning

Setting

import numpy as np

from qiskit import Aer, QuantumCircuit
from qiskit.circuit import Parameter
from qiskit.circuit.library import RealAmplitudes, ZZFeatureMap
from qiskit.opflow import StateFn, PauliSumOp, AerPauliExpectation, ListOp, Gradient
from qiskit.utils import QuantumInstance, algorithm_globals

algorithm_globals.random_seed = 42
expval = AerPauliExpectation()
gradient = Gradient()
qi_sv = QuantumInstance(Aer.get_backend("aer_simulator_statevector"))
qi_qasm = QuantumInstance(Aer.get_backend("aer_simulator"), shots=10)

Suppose a NeuralNetwork called nn. Then, the nn.forward(input, weights) pass takes either flat inputs for the data and weights of size nn.num_inputs and nn.num_weights, respectively. NeuralNetwork supports batching of inputs and returns batches of output of the corresponding shape.

Coding

from qiskit_machine_learning.neural_networks import OpflowQNN

params1 = [Parameter("input1"), Parameter("weight1")]
qc1 = QuantumCircuit(1)
qc1.h(0)
qc1.ry(params1[0], 0)
qc1.rx(params1[1], 0)
qc_sfn1 = StateFn(qc1)

H1 = StateFn(PauliSumOp.from_list([("Z", 1.0), ("X", 1.0)]))

op1 = ~H1 @ qc_sfn1
print(op1)

↓ Out

image.png

qnn1 = OpflowQNN(op1, [params1[0]], [params1[1]], expval, gradient, qi_sv)
input1 = algorithm_globals.random.random(qnn1.num_inputs)
weights1 = algorithm_globals.random.random(qnn1.num_weights)
qnn1.forward(input1, weights1)

↓Out

image.png

qnn1.backward(input1, weights1)

↓Out

image.png

qnn1.backward([input1, input1], weights1)

↓Out

image.png

op2 = ListOp([op1, op1])
qnn2 = OpflowQNN(op2, [params1[0]], [params1[1]], expval, gradient, qi_sv)
qnn2.forward(input1, weights1)

↓Out
image.png

Result

image.png

image.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0