Luca
Luca

Reputation: 10996

Problems with numpy divide

I am trying to use numpy divide to perform division on arrays and I have two arrays and I call it as follows:

log_norm_images = np.divide(diff_images, b_0)

I get the error:

operands could not be broadcast together with shapes (96,96,55,64) (96,96,55).

These are the shapes of the ndarrays respectively.

Now, in my python shell, I do the following tests:

 x = np.random.rand((100, 100, 100))
 y = np.random.rand((100, 100))

and

np.divide(x, y)

runs without any errors. I am not sure why this works and not my case.

Upvotes: 2

Views: 1451

Answers (1)

rchang
rchang

Reputation: 5236

You are attempting to broadcast a 4-D array together with a 3-D array. Based on NumPy's broadcasting behavior, this will only succeed if for each corresponding dimension, the dimensions are either equal or one of them is 1. Here's why it mismatches:

Your 4-D array:  96 x 96 x 55 x 64
Your 3-D array:       96 x 96 x 55
                           ^     ^
                           Mismatching dimensions

Your operation will probably work if your pad out/reshape your 3-D array (which would no longer be 3-D I suppose) to explicitly have the shape (96, 96, 55, 1). Then it would look like:

Your 4-D array:  96 x 96 x 55 x 64
Your 3-D array:  96 x 96 x 55 x 1
                                 ^
                                This is acceptable for the broadcast behavior

This link to the SciPy/NumPy documentation gets into this in more detail:

http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

Upvotes: 4

Related Questions