Course 1, week 1, exercise 7: vectorization of predictions

I’ve used a for-loop for converting the predictions to 0 and 1. I’d be interested to know what the vectorized solution looks like.

Hi, Ivana.

There are several ways to implement a vectorized solution for this in numpy. A sophisticated way would be to use the np.where function (google “numpy where”). But I like the straightforward approach of doing a direct Boolean comparison of an array with a scalar. Create a new cell in your notebook (“Insert → Cell Below”) and copy/paste this code and try it:

np.random.seed(42)
A = np.random.rand(3,4)
print("A = " + str(A))
B = (A > 0.7)
print("B = " + str(B))
C = B.astype(float)
print("C = " + str(C))
D = (A > 0.7).astype(float)
print("D = " + str(D))

That’s not a direct solution to your problem, but using that idea you can write this in one simple and expressive line of python code with no loop required.

2 Likes

Thanks very much! I’ll try it :slight_smile:
Best,
iv.