W3 assignment: Exercise 5 - compute cost

Hello, I’m stuck on Week3 assignment - Exercise 5 (computer cost). Here’s my code:

logprobs = np.multiply(np.log(A2), Y)
cost = - np.sum(logprobs)

which is recommended from above. However, I got

AssertionError: Wrong value. Expected: 0.5447066599017815 got: 1.0493608309109266

Any idea ? Thanks!

The code they show you is not the complete answer: it’s just a demonstration of the general technique to use. Compare your code to the math formula for the cost shown above and ask yourself two questions:

  1. What happened to the factor of 1/m?

  2. Why is there only one term? What happened to the Y = 0 term?

That makes perfect sense. Thanks!

I’m on the last part of the W3 exercise (Exercise 9 - predict). Per the instruction, I should do this in approximately two lines of code:

A2, cache = forward_propagation(X, parameters)
predictions = 1 if A2[1,:] > 0.5 else 0

I’m confident with A2 & cache. However, for predictions, because A2 is a matrix and because I’m not allowed to use for-loop, I’m not sure how to achieve this (predictions) in one line.

You could use a for loop if you want: the grader doesn’t care about anything but the answer. The number of lines is just a hint: it is not enforced. But the point is to find a better way. The “list comprehension” style code you show should work, but that’s more elaborate than you really need. I should not write the explicit code for you, but you can do direct Boolean comparisons with numpy arrays. Try this and watch what happens:

A = np.random.rand(3, 4)
print(A)
B = (A > 0.7)
print(B)
C = (A > 0.7).astype(float)
print(C)