About Numpy broadcast

What is broadcast?

Numpy has a function that automatically converts to an appropriate form when performing operations between matrices with different dimensions, and this is called broadcasting. I think it's faster to see it, so I'll write it below.

A = np.array([1, 2, 3, 4, 5])
print(f'{"="*20}A')
print(A)
print(f'{"="*20}A-1')
# (1, 5)Matrix and scalar value arithmetic
print(A - 1)
====================A
[1 2 3 4 5]
====================A-1
[0 1 2 3 4]

Internal behavior

Numpy automatically adjusts the dimensions when performing operations on matrices with different dimensions. For example, the operation of $ (m, n) + (1, n) $ expands $ (1, n) $ and converts it to $ (m, n) $.

\begin{bmatrix} 1 & 2 & 3 & 4 & 5\\\ 6 & 7 & 8 &9 & 10 \end{bmatrix} \- \begin{bmatrix} 1 & 2 & 3 & 4 & 5 \end{bmatrix}\\\ \= \begin{bmatrix} 1 & 2 & 3 & 4 & 5\\\ 6 & 7 & 8 &9 & 10 \end{bmatrix} \- \begin{bmatrix} 1 & 2 & 3 & 4 & 5\\\ 1 & 2 & 3 & 4 & 5 \end{bmatrix}
A = np.array([
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10]])
B = np.array([1, 2, 3, 4, 5])
print(f'{"="*20}A')
print(A)
print(f'{"="*20}B')
print(B)
print(f'{"="*20}A - B')
print(A - B)
====================A
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]]
====================B
[1 2 3 4 5]
====================A - B
[[0 0 0 0 0]
 [5 5 5 5 5]]

Recommended Posts

About Numpy broadcast
About numpy
About all of numpy (2nd)
About Numpy array and asarray
About LangID
About CAGR
numpy practice 1
About virtiofs
Numpy [Basic]
About Permission
About sklearn.preprocessing.Imputer
About gunicorn
About requirements.txt
About locale
numpy part 1
About permissions
NumPy basics
About Opencv ②
Numpy Memorandum_Matrix
About axis = 0, axis = 1
numpy tips
About Opencv ③
About import
About pip
About Linux
About numpy.newaxis
Use Numpy
About endian
numpy part 2
About Linux
About import
About Opencv ①
About Linux
About Linux
About Linux ①
About cv2.imread
About _ and __
About wxPython
About cumulative assignment of lists and numpy arrays