C3_W2_Collaborative_RecSys_Assignment - For loop vs np.sum

For the Exercise 1 of C3_W2 Assignment, could I just use “For loop” or “np.sum” to code up the math function of summation (Σ). If it is not possible to complete the task in just one of the method, may I know what is the reason of that?

Because I am not clear about when to use “For loop” and “np.sum”

Remark: I understand that Numpy vectorization will speed up the computation.

Any responses would be appreciated. Thank you.

Hi @PHX,
Exercise 1 is a little unusual in that it asks you to first implement using a for loop (non-vectorized), and then later it asks you to implement a vectorized solution, where you can use np.sum.

The main difference between the for loop and the np.sum is exactly that one is vectorized, and, as you point out, the advantage of that is that it speeds up the computation.

I think the reason the assignment asks you to implement these two approaches is to help make sure you get the concept - with the idea that it might be easiest to see at first how the for-loop corresponds to the equation. But it also shows you that the vectorized version can be simpler once you get used to it (or at least fewer lines :slight_smile: ).

The for-loop version of the function is there only as a learning aid. The training code later in the exercise only uses the vectorized version of the function (because it is faster).

2 Likes

Hello @PHX, use whichever you prefer :wink:

Raymond

Thank you very much for the explanation. It is clear for me now. :pray: