[NumPy] Broadcasting

2022. 9. 27. 12:58·Programming/DIP
728x90
728x90

0. Broadcasting이란?

tensor와 scalar를 연산시킬 때 

scalar를 상대 tensor와 같은 shape이면서 해당 scalar의 값을 가진 tensor로 변경시키고나서
이 scalar로부터 만들어진 tensor와 상대 tensor를 동작
시키는 방식으로
elementwise연산이 수행되는 기능.

 

주의할 것은 scalar 를 확장시키는 것이 기본이라는 점임.

 

 

참고로 broadcasting은
scalar와 tensor간의 연산을 확장하여
차원이 다른 tensor간의 연산에도 사용된다:
단, scalar에서 출발하므로 size가 1인 축(=scalar)을 추가하는 padding을 이용함.

 

PyTorch나 TensorFlow의 텐서도 NumPy와 같은 방식으로 broadcasting이 수행된다.

 

이를 정리하면 다음과 같은 Rule에 따른다고 생각할 수 있음.


1. Rules of Broadcasting

1-1. Rule 1

두 ndarray의 차원의 수(number of dimensions)가 같지 않을 경우, 

적은 ndarray의 shape가 leading side쪽(shape에서 왼쪽)으로 1로 padding됨 (shape가 padding되는 것 주의)

  • A의 shape가 (3,4,1) 이고,
    B의 shape가 (1,2)이면,
    B가 2차원(ndim=2)이므로 3차원(ndim=3)으로 늘어나고,
    leading side(왼쪽)로 1로 padding된 shape가 됨.
  • 즉, B는 (1,2)에서 (1,1,2)이 됨.

1-2. Rule 2

shape에서 대응되는 값들이 일치하지않을 경우, 

ndarray 각각에서 shape가 1인 차원이 상대방의 해당하는 차원의 shape로 변경됨.

  • A의 shape가 (3,4,1) 이고,
    B의 shape가 (1,1,2)이면,
    A의 첫번째 차원의 shape수인 3에 맞춰 B의 첫번째 차원의 shape도 3이 됨.
  • 두번째 차원(두번째 축)의 경우,
    A의 4에 맞춰 B도 4로 늘어남.
  • 세번째 차원의 경우 B의 2에 맞춰 A의 1이 2로 늘어남 (stretched)

1-3. Rule 3

Rule2를 적용하려고 할 때, shape가 일치하지 않으면서 어느 한 쪽 ndarray가 1이 아닌 경우엔 broadcasting이 실패함.


2. 예제

import numpy as np
import tensorflow as tf
import torch

# ------------------

a = np.ones((3,4,1))
b = np.ones((1,2))
c = a+b
print(c.shape) # (3,4,2)

# -------------------

a_torch = torch.ones((3,4,1))
b_torch = torch.ones((2))
c_torch = a_torch + b_torch
print(c_torch.shape) # (3,4,2)

# -------------------

a_tf = tf.ones((3,4,1))
b_tf = tf.ones((2))
c_tf = a_tf + b_tf
print(c_tf.shape) # (3,4,2)

numpy, tensorflow, pytorch 모두 같은 방식으로 동작한다.

이후로는 numpy 중심으로 예제를 작성함.


 

import numpy as np

a = np.ones((2, 3))
b = np.arange(3)

a+b

# 2 x 3
import numpy as np

a = np.arange(3).reshape((3, 1))
b = np.arange(3)
a+b

# 3 x 3
import numpy as np

a = np.ones((3, 2))
b = np.arange(3)

a+b
# Value Error

 

'Programming > DIP' 카테고리의 다른 글

[DIP] OpenCV : Region of Interest (ROI) : Callback으로 구현.  (0) 2022.10.03
[DIP] opencv : Region of Interest (ROI) : cv2.selectROI  (1) 2022.10.03
[DIP] Signal to Noise : Amplitude, Power, and Differential SNR  (0) 2022.09.26
[DIP] Line pairs per millimeters and Bar phantom  (0) 2022.09.26
[DIP] Full Width at Half Maximum (FWHM)  (1) 2022.09.26
'Programming/DIP' 카테고리의 다른 글
  • [DIP] OpenCV : Region of Interest (ROI) : Callback으로 구현.
  • [DIP] opencv : Region of Interest (ROI) : cv2.selectROI
  • [DIP] Signal to Noise : Amplitude, Power, and Differential SNR
  • [DIP] Line pairs per millimeters and Bar phantom
dsaint31x
dsaint31x
    반응형
    250x250
  • dsaint31x
    Dsaint31's blog
    dsaint31x
  • 전체
    오늘
    어제
    • 분류 전체보기 (770)
      • Private Life (13)
      • Programming (200)
        • DIP (116)
        • ML (28)
      • Computer (119)
        • CE (53)
        • ETC (33)
        • CUDA (3)
        • Blog, Markdown, Latex (4)
        • Linux (9)
      • ... (362)
        • Signals and Systems (110)
        • Math (175)
        • Linear Algebra (33)
        • Physics (43)
        • 인성세미나 (1)
      • 정리필요. (59)
        • 의료기기의 이해 (6)
        • PET, MRI and so on. (5)
        • PET Study 2009 (1)
        • 방사선 장해방호 (5)
        • 방사선 생물학 (3)
        • 방사선 계측 (9)
        • 기타 방사능관련 (3)
        • 고시 (9)
        • 정리 (18)
      • RI (0)
      • 원자력,방사능 관련법 (2)
  • 블로그 메뉴

    • Math
    • Programming
    • SS
    • DIP
  • 링크

    • Convex Optimization For All
  • 공지사항

    • Test
    • PET Study 2009
    • 기타 방사능관련.
  • 인기 글

  • 태그

    Probability
    numpy
    Programming
    linear algebra
    Term
    Convolution
    opencv
    fourier transform
    signal_and_system
    SS
    cv2
    인허가제도
    random
    function
    Vector
    signals_and_systems
    Optimization
    Python
    math
    SIGNAL
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dsaint31x
[NumPy] Broadcasting
상단으로

티스토리툴바