Expectation Value from Counts

Hello,

I am wondering if there is a way in Pennylane to calculate the expectation of an observable based on counts outside of a qnode circuit?

For example, with this circuit is there method within pennylane to easily calculate the expectation value as if we would have returned [qp.expval(qp.PauliX(i)) for i in device.wires] in the qnode?

device = qp.device("default.qubit", 4)

@qp.set_shots(1000)
@qp.qnode(device)
def circuit():
    qp.H(wires=[i])

    return qp.counts(wires=device.wires)

counts = circuit()

Thank you!

Hi @movingwaters ,

You can return more than one measurement. In the example below the qnode returns both the counts and the expvals. I don’t think there’s an easy function to calculate the expvals directly from the counts though.

import pennylane as qp
device = qp.device("default.qubit", 4)

@qp.set_shots(1000)
@qp.qnode(device)
def circuit():
  for i in range(2):
    qp.H(wires=[i])

  return qp.counts(wires=device.wires), [qp.expval(qp.PauliX(i)) for i in device.wires]

counts, expvals = circuit()
print(expvals)

I hope this helps!

Okay great, thank you!