Codercise PF4.5b - Requested array has an inhomogeneous shape after 1 dimension

G’day, this is Mack again, starting a new project with PennyLane and revamping the quanvolutional neural network before this summer.

Being a followup of PF4.5a, I am now stuck on PF4.5b where I have to implement the actual machine learning part (gradient descent).

The code for PF4.5a is based on the corresponding related theory, where the opt.step(cost_function, params) are repeatedly ran.

The circuit from PF4.5a consists of four elements. Thus, there are four elements in the init_params. However, whenever I attempt to run the code using a four-element init_params, the output errors out with

Error: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.

Even then, after adding the print function to see the results, I can see that the optimization is still working. This is my code so far:

def optimize(cost_function, init_params, steps):

    opt = qml.GradientDescentOptimizer(stepsize = 0.2) # Change this as you see fit

    params = init_params

    for i in range(steps):
        print(params)
        params = opt.step(cost_function, params)

    return params, cost_function(params)

minimum = optimize(cost_function, np.array([0.7,0.3,0.2,0.5], requires_grad = True), 1) # An np.tensor of shape () containing the minimum of cost_function.

Hint: You are really outputting two pieces, namely the params and the cost function given params after optimization. You need to index the output!

Hi @mack.attack !
Thanks for your question.
You are on the right track, quite close to the solution! There are two things that I would recommend:

  1. Use the hint and select the part of the output that contains the minimum value. The output is a tuple with two objects, take the second one. minimum = optimize(cost_function, np.array([0.7,0.3,0.2,0.5], requires_grad = True), 1)[1]
  2. Remember that this is an optimization and you need several steps in order to get a minimum value within certain tolerance. Our evaluation code is checking if your minimum value is close enough to the answer within certain tolerance. Try increasing the number of steps; currently, your program is only doing one.

Let us know if this helped!

1 Like

I am able to figure this shortly after reading the question more closely, what they are precisely looking for.

1 Like