How to handle results of qml.expval

The result of qml.expval, qml.sample and qml.probs are objects of ‘ExpectationMP’ type which can not converted into np.array. FOr instance, here in "I.10 What did you expect? " of Pennylane codebook, how can I store results into numpy array;

# An array to store your results
shot_results = []

# Different numbers of shots
shot_values = [100, 1000, 10000, 100000, 1000000]

def fun(shoot):
    dev = qml.device('default.qubit' , wires =1 ,shots=shoot)
    qml.qnode(dev)
    qml.RX(np.pi/4 , 0)
    qml.Hadamard(0)
    qml.PauliZ(0)
    # STORE RESULT IN SHOT_RESULTS ARRAY
    return qml.expval(qml.PauliY(0))

for shots in shot_values: 
    ##################
    # YOUR CODE HERE #
    ##################

    # CREATE A DEVICE, CREATE A QNODE, AND RUN IT
    for shoot in shot_values:
        shot_results.append(fun(shoot)) # I got Error: 'ExpectationMP' object has no attribute 'numpy'

print(qml.math.unwrap(shot_results))

Hi @Afrah, welcome to our community!

I noticed that you defined “fun” outside of the “for” loop. This will cause problems.
The original question looked like the following:

# An array to store your results
shot_results = []
# Different numbers of shots
shot_values = [100, 1000, 10000, 100000, 1000000]
for shots in shot_values: 
    ##################
    # YOUR CODE HERE #
    ##################
    # CREATE A DEVICE, CREATE A QNODE, AND RUN IT
    # STORE RESULT IN SHOT_RESULTS ARRAY
    
print(qml.math.unwrap(shot_results))

Note that you only needed to add code inside the for shots in shot_values:

Also, in your code I see that you added another for shots in shot_values: within the original one so this will cause problems too.

I hope this can help you get going.

Hi @Afrah, this is a late comment, but I leave it for those studying pennylane. What you need to return from the function is not qml.expval(qml.PauliY(0)), but an object that is created from qml.Qnode. There are two ways to do this, one is to use qml.qnode(dev) as the decorator of the function.

@qml.qnode(dev)
def circuit():
## your circuit code
return qml.expval(qml.PauliY(0))

shots_result.append(circuit())

The other way is to create an instance directly.

def circuit():
## your circuit code
return qml.expval(qml.PauliY(0))

qnode = qml.QNode(circuit, dev)
shot_results.append(qnode())

I think it would be good to refer to the corresponding page.
https://docs.pennylane.ai/en/stable/code/api/pennylane.QNode.html

1 Like

Hey @hwarang2014, welcome to the forum! :smile:

Just putting this here for reference: Documentation of expval - #2 by isaacdevlugt

1 Like