Numpy Array Broadcasting

1 minute read

Numpy Array Broadcasting

Docs says:

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is โ€œbroadcastโ€ across the larger array so that they have compatible shapes.


array๊ฐ€ ๋‹ค๋ฅธ shape์ผ๋•Œ, ํŠน์ • ์ œ์•ฝ์กฐ๊ฑด์ด ์žˆ๊ธดํ•˜์ง€๋งŒ,
๋” ์ž‘์€ array๊ฐ€ ๋” ํฐ array ์ „๋ฐ˜์— ๊ฑธ์ณ โ€œbroadcastโ€ ๋œ๋‹ค๋Š” ๊ฒƒ.


Example from docs

import numpy as np
a = np.array([0.0, 10.0, 20.0, 30.0])
b = np.array([1.0, 2.0, 3.0])
c = a[:, np.newaxis] + b
print(a)
print("\nnp.newaxis: \n",a[:, np.newaxis])
print("newaxis shape:  ",a[:, np.newaxis].shape)
print("b shape:   \t\t",b.shape,"\n")
print(a[:, np.newaxis] + b)
print("broadcasted shape: ",c.shape)

######### output #########
# [ 0. 10. 20. 30.]

# np.newaxis: 
#  [[ 0.]
#  [10.]
#  [20.]
#  [30.]]
# newaxis shape:   (4, 1)
# b shape:         (3,) 

# [[ 1.  2.  3.]
#  [11. 12. 13.]
#  [21. 22. 23.]
#  [31. 32. 33.]]
# broadcasted shape:  (4, 3)

Example of Addition: add +1 to 2nd row

import numpy as np
a = np.arange(1,10).reshape(3,3)
b = np.array(
    [[0,0,0],
    [1,1,1],
    [0,0,0]])
print(a,"\n")
print(b,"\n")
print(a+b,"\n")

#### OUTPUT ####
# [[1 2 3]
#  [4 5 6]
#  [7 8 9]] 

# [[0 0 0]
#  [1 1 1]
#  [0 0 0]] 

# [[1 2 3]
#  [5 6 7]
#  [7 8 9]] 

Example of Multiplication: not matrix multiplication

import numpy as np
a = np.arange(1,10).reshape(3,3)
b = np.array(
    [[0,1,-1],
    [0,1,-1],
    [0,1,-1]])
print(a,"\n")
print(b,"\n")
print(a*b,"\n")

# [[1 2 3]
#  [4 5 6]
#  [7 8 9]] 

# [[ 0  1 -1]
#  [ 0  1 -1]
#  [ 0  1 -1]] 

# [[ 0  2 -3]
#  [ 0  5 -6]
#  [ 0  8 -9]] 

Then, Matrix multiplication ?

print(a.dot(b))
# [[  0   6  -6]
#  [  0  15 -15]
#  [  0  24 -24]]

np.dot VS. np.matmul

np.dot()

๋งŒ์•ฝ a๊ฐ€ N์ฐจ์› ๋ฐฐ์—ด์ด๊ณ  b๊ฐ€ 2์ด์ƒ์˜ M์ฐจ์› ๋ฐฐ์—ด์ด๋ผ๋ฉด, dot(a,b)๋Š” a์˜ ๋งˆ์ง€๋ง‰ ์ถ•๊ณผ b์˜ ๋’ค์—์„œ ๋‘๋ฒˆ์งธ ์ถ•๊ณผ์˜ ๋‚ด์ ์œผ๋กœ ๊ณ„์‚ฐ๋œ๋‹ค.

np.matmul()

๋งŒ์•ฝ ๋ฐฐ์—ด์ด 2์ฐจ์›๋ณด๋‹ค ํด ๊ฒฝ์šฐ, ๋งˆ์ง€๋ง‰ 2๊ฐœ์˜ ์ถ•์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ํ–‰๋ ฌ์„ ๋‚˜๋จธ์ง€ ์ถ•์— ๋”ฐ๋ผ ์Œ“์•„๋†“์€ ๊ฒƒ์ด๋ผ๊ณ  ์ƒ๊ฐํ•œ๋‹ค.

์ถœ์ฒ˜: https://ebbnflow.tistory.com/159 [Dev Log : ์‚ถ์€ ํ™•๋ฅ ์˜ ๊ตฌ๋ฆ„]


numpy docs: https://numpy.org/doc/stable/user/basics.broadcasting.html
np.dot VS. np.matmul: https://ebbnflow.tistory.com/159

Leave a comment