Change the cost function in the ExpvalCost

Hi,
I’m new to the pennylane API. So far it looks great!
I was working through the VQE tutorial.
My question is about changing the content of cost_fn attribute of an object of the ExpvalCost class. Specifically, I would like to change the cost function. For example, I have:

cost_fn_1 = qml.ExpvalCost(circuit, hamiltonian_1, dev)
cost_fn_2 = qml.ExpvalCost(circuit, hamiltonian_2, dev)

Now I want to add the cost function of the object cost_fn_2 to the cost function of the object cost_fn_1 like so

cost_fn_1.cost_fn = cost_fn_1.cost_fn + foo*cost_fn_2.cost_fn - C

where foo and C are some variables. The above code gives an error because I’m trying to add function types.
So the solution was to create a lambda function like so:

final_cost_fn = lambda x: cost_fn_1.cost_fn(x) + foo*cost_fn_2.cost_fn(x) - C

And then assigning final_cost_fn as so

 cost_fn_1.cost_fn = final_cost_fn

This approach works, but I’m not sure if this is the best way of altering the cost function given that this object will be further used by optimizers and other pennylane objects.

Thank you

Hi @Einar_Gabbassov! Welcome.

So the solution was to create a lambda function like so… This approach works, but I’m not sure if this is the best way of altering the cost function given that this object will be further used by optimizers and other pennylane objects.

The approach you have for extending the cost function is the recommended approach :slight_smile:

Let us know if you run into any issues with this approach!

1 Like