Numpy Array Broadcasting
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