Caculations for Cost Function J

Hi, I have a question on my assignment for week 4. When I implement the cost function J (with no for loop), I am not sure which method to use although both work. I used the following:

cost = (-1/m) * (np.dot(Y, np.log(AL.T)) + np.dot((1 - Y), np.log(1 - AL.T)))

AND
cost = (-1/m) * np.sum((Y * np.log(AL)) + (1 - Y) * np.log(1 - AL))

They both work to my surprise, but what is the proper way of calculating it in code ?

Which course are you attending?

You have posted in the “AI Discussions” thread, which is for general topics.

To answer your question: Multiple correct implementations are possible. There is no single proper way.

Since a dot product includes computing the sum of the products of two vectors, it’s easily possible to not require a separate “sum” function.

Sometimes a transposition is necessary to shape the vectors for use in a dot product.

Some implementations might be more computationally efficient. That’s a great experiment you can perform. Please post back your results.

1 Like