Week 1 Assignment 2 Exercise 1 - compute_cost_with_regularization

I am trying to compute the cost for weights W1,W2,W3. Basic test is passed but other test cases are failed.
I’ve tried implementing it in different ways but getting the same error. I’ll be glad to get a hint about my mistake. Thank you

Hi @Shan.ali

Your way of calculating L2_regularization_cost is within the ‘for’ loop when it is multiplied by 1/m * λ/2. which is incorrect. It needs to be outside of the ‘for’ loop. Please see the implementation instruction.

I tried outside of the loop also, but it was not working however I’ll try again

Hi @Shan.ali ,

L2_regularization_cost has to be the sum of all W1, W2, W3. What you are doing here is that
L2_regularization_cost get replaced each time it loops through the loop.

okay thanks, I am trying to fix this and will get back to you for help if needed

Hi @Kic ,
I am trying to do it without a for loop. Is it possible? I get an error for this (1 Tests Passed, 1 Tests Failed):

L2_regularization_cost = (1/m)*(lambd/2)*np.sum([np.sum(np.square(W1)),np.sum(np.square(W2)),np.sum(np.square(W2))])

Hi @Rohit_Borooah,

Could you try this:
L2_regularization_cost = 1/m * lambd/2 * (np.sum(np.square(W1))

to see if it helps.
The way you use np.sum() to sum all the W’s could be the problem, because of different dimensions between those W’s. Whist adding allows broadcasting.

I tried this too. I get the same error :slightly_frowning_face:

Hi @Rohit_Borooah ,

Try refresh the kernel and rerun the code cell:
from the kernel tab ->restart & clear output
from the cell tab → run all above

Finally this worked! Thanks @Kic