Problem writing the dropout logic in course2-W1-exercise on regularization

The model defined with layers_dims = [X.shape[0], 20, 3, 1]. So, the dimension of A1=(20,m) but it doesn’t pass the test (as copied below). But passes all tests if I change (20,m) to (2,m).

in forward_propagation_with_dropout(X, parameters, …
42 D1 = np.random.rand(20,m)
43 D1 = (D1<keep_prob).astype(int)
—> 44 A1 = A1*D1
45 A1 = A1/keep_prob

ValueError: operands could not be broadcast together with shapes (2,5) (20,5)

Any help would be appreciated.

It is a mistake to “hardcode” the dimensions on the np.random.rand call. The better idea is to use the “shape” attribute of the relevant A matrix (A1 in the case you are showing).

BTW this is a bug in your code, not a bug in the tests or the grader, so I will take the liberty of editing the title of your post.

It worked by using shape. Thank you so much for your help.

1 Like

I haven’t quite figured out the correct arguments to pass into np.random.rand()… tried a few different approaches and still getting below error. What am I missing?

ValueError Traceback (most recent call last)
1 t_X, parameters = forward_propagation_with_dropout_test_case()
----> 3 A3, cache = forward_propagation_with_dropout(t_X, parameters, keep_prob=0.7)
4 print ("A3 = " + str(A3))

in forward_propagation_with_dropout(X, parameters, keep_prob)
42 D1=np.random.rand(2,A1.shape[0])
43 D1= (D1 < keep_prob).astype(int)
—> 44 A1=A1*D1
45 A1=A1/keep_prob

ValueError: operands could not be broadcast together with shapes (2,5) (2,2)

As D1 is expected to have the same shape of A1, you need to pass the size of A1 as parameters.
If you pass (2, A1.shape[0]), then, the shape of output is (2, 2). On the other hand, the shape of A1 is (2,5). Where “2” comes from ? You can get dimension of A1 as A1.shape, and extract each size like A1.shape[0], A1.shape[1].

1 Like