I would like to implement a variational algorithm (similar to VQE but with another cost function, no expectation of a Hamiltonian involved) from zero. Is there any tutorial explaining how to implement a VQE or similar variational algorithm in QISKit tutorial? This means creating the ansatz, implementing the cost function and running on the real quantum computer. I haven't seen it. Thank you!
In this Qiskit Aqua tutorial, they show how to use the Variational Quantum Eigensolver (VQE) for solving a ground state energy problem. Here's another in the context of the travelling salesman problem. Note that both use the Aer simulators as backend and not the real IBMQ devices. You might also want to go through their documentation on VQE, Variational Forms, Optimizers and Initial States.
In Quantum Algorithm Implementations for Beginners (Coles et al., 2018) there's a nice discussion about the theory of VQE and how it's used to simulate a transverse Ising model. However, due to the communication bottlenecks when the quantum device and classical computers are not physically co-located, it could not be run on real quantum processors like the ones on IBMQ Cloud.
For a more high-level interface to coding and running variational quantum algorithms, you can also check out the PennyLane Python library, which has a Qiskit plugin available for using Qiskit simulators and IBM hardware as a backend.
For example, a variational quantum algorithm in PennyLane using qiskit looks like this:
import pennylane as qml dev = qml.device('qiskit.basicaer', wires=2) # use 'qiskit.ibm' instead to run on hardware @qml.qnode(dev) def circuit(x, y, z): qml.RX(x, wires=0) qml.RY(y, wires=1) qml.RZ(z, wires=0) qml.CNOT(wires=[0, 1]) return qml.expval.PauliZ(0) def cost(x, y, z): return (1-circuit(x, y, z))**2 # optimization follows
You can use NumPy, TensorFlow, or PyTorch to do the optimization - check out some of the tutorials.
Disclaimer: I am one of the developers on PennyLane.