W2 | Video lecture- Broadcasting in Python | Reshaping before broadcasting?

Hi,
In the video DLS/C1/W2/Broacasting in Python, Andrew write this command on a notebook:

percentage = 100*A/cal.reshape(1, 4)

No problem with that.
But it seems to me that it is not useful to reshape the ‘cal’ vector. I would even say that it is not intuitive to do so. And by the way, my following code works without any problem:

percentage = 100*A/cal

What do you think?

Thanks,
Regards

Pierre (from France)

I have a reply for myself. In the video, after this formula, Andrew explain that reshaping is not necessary because the matrix as already the good shape. But I desagree because this code:

print(cal.shape)
print(cal.reshape(1, 4).shape)

give the following result:
(4,)
(1, 4)

Regards,

Pierre

(4,) is a vector, and (1,4) is a 2D array.
And, (4,) is a row vector and can be seen like (1,4).
In your case, please try to add two variables, i.e, cal + cal.reshape(1,4) Then, the shape of the result will be (1,4).
Here is another example.

a = np.ones((3,))
print(type(a)) ; print(a.ndim) ; print(a.shape)
b = np.ones((3,1))
print(type(b)) ; print(b.ndim) ; print(b.shape)
c = a+b
print(type(c)) ; print(c.ndim) ; print(c.shape)
a : <class ‘numpy.ndarray’>, dim=1, shape=(3,)
b: <class "numpy.ndarray’>, dim=2, shape=(3,1)
c: <class "numpy.ndarray’>, dim=2, shape=(3,3)

Since “a” acts like (1,3), then, by broadcasting, the output shape becomes (3,3).

Thanks for your clarification: shape=(4,) can be considered as shape(1,4). It’s a bit surprising because the “4” changes places in the ‘shape’ tuple.

But in both cases we have a row vector. And that explains the example given by Andrew in which he added .reshape(1, 4) (out of habit).

That said, there are still differences:

  • dim=1 for shape=(4,) and a display with single brackets “[…]”
  • dim=2 for shape=(1, 4) and a display with double level of brackets “[[…]]”

But all this is very logical.

Thanks,


Pierre

Hi, Pierre Bejian.

Yes, very much! But Prof Ng mentions the same in the later part of the video. Did you go through the whole? He tried explaining these details (just for the freshers, who are new to this field) on how reshaping works in python. Adding a few details while doing the explanation is always an advantage. Right! :slight_smile:

The next part of your query, was very explained by Nobu Asai. And yes, you are right, this all is very logical, depending how are we writing out the numerical based on the asked formats: (4,) ; (1,4); (4,4); (:, 4); :slight_smile: etc.
Here’s a good read, where you can enlighten yourself on certain other combinations.