Open utterances-bot opened 1 year ago
Can I obtain the prob and density matrix at the same time?Besides, if I want to insert a measurement to get the prob in the middle of circuit, and compute the density matrix at the end of circuit.
Very good question! One thing you can do to get the probabilities at a given time, is to use qml.Snapshot
. This class will store the state in a particular time. By squaring the amplitude you can get the probabilities 😄 Here is an example:
import pennylane as qml
dev = qml.device("default.qubit", wires = 2)
@qml.qnode(dev)
def circuit():
qml.Hadamard(wires = 0)
qml.Snapshot("quantum state here")
return qml.density_matrix(wires = [0,1])
qml.snapshots(circuit)()
{'quantum state here': array([0.70710678+0.j, 0. +0.j, 0.70710678+0.j, 0. +0.j]),
'execution_results': tensor([[0.5+0.j, 0. +0.j, 0.5+0.j, 0. +0.j],
[0. +0.j, 0. +0.j, 0. +0.j, 0. +0.j],
[0.5+0.j, 0. +0.j, 0.5+0.j, 0. +0.j],
[0. +0.j, 0. +0.j, 0. +0.j, 0. +0.j]], requires_grad=True)}
Note that here we are not measuring the state, we are obtaining the state to calculate the probabilities so there will not be a collapse of the wave function. On the other hand note that this method works in simulator, we cannot access the wave function in real hardware I hope it helps you! 🚀
Thanks, I want use the density matrix in my QNN model. However, it doesn't make it, and the error is 'TypeError: Grad only applies to real scalar-output functions. Try jacobian, elementwise_grad or holomorphic_grad.'; What should I do?
How to do measurements in PennyLane
When using PennyLane to design quantum circuits we need to consider both the sequence of gates that we want to apply and also the kind of output that we want to obtain. At the end of the day, we will get back a quantity through a specific measurement. In this how-to, we go through the different type of measurements offered by PennyLane and we discuss when to use them.
https://pennylane.ai/blog/2022/06/how-to-do-measurements-in-pennylane/