C.W.K.
Stream
Lesson 02 of 07 · published

Vectorization & Broadcasting — 사고 전환

~14 min · numpy, broadcasting, vectorization

Level 0구경꾼
0 XP0/47 lessons0/11 achievements
0/120 XP to next level120 XP to go0% complete

Loop 그만 써

비-배열 언어에서 가져오는 가장 깊은 습관은 요소별 연산을 loop 로 쓰는 거: for i in range(len(x)): result[i] = x[i] * 2. NumPy 에선 result = x * 2 라고 말하면 같은 답을, 더 빠르게, 더 적은 코드로, (이게 underrated 인데) off-by-one 에러 여지 적게 생산.

더 어려운 전환은 두-배열 연산. Python 리스트로는 zip(a, b) + comprehension. NumPy 로는 a * b — shape 만 호환되면 NumPy 가 알아서 처리.

Broadcasting 한 단락 요약

Broadcasting 은 다른 shape 의 배열을 결합하는 NumPy 규칙들이야. 규칙: 후행 차원 align, size 1 차원은 stretching, 빠진 차원은 size 1 으로 취급. 왜 신경 써야 하냐면 — "이 row 벡터를 이 행렬의 모든 row 에 더해" 또는 "모든 요소에서 이 스칼라 빼" 를 loop 한 줄도 안 쓰고, 중간 copy 도 할당 안 하고 표현할 수 있어.

Code

Vectorization — loop 없는 요소별 연산·python
import numpy as np

x = np.arange(10)            # 0..9

doubled = x * 2              # 요소별 스칼라 곱
shifted = x + 100            # 요소별 스칼라 덧셈
squared = x ** 2             # 요소별 거듭제곱
evens   = x[x % 2 == 0]      # boolean mask 필터

y = np.linspace(0, 1, 10)    # 0~1 사이 10개 float
weighted_sum = (x * y).sum() # vectorized 곱, 그리고 reduce
Broadcasting — 다른 shape, 같은 연산·python
import numpy as np

# 2D 행렬과 1D row 벡터
matrix = np.arange(12).reshape(3, 4)        # shape (3, 4)
row    = np.array([10, 20, 30, 40])         # shape (4,)

# Broadcasting: (4,) 가 (1, 4) 로 취급되고 (3, 4) 로 stretching
result = matrix + row
# matrix 의 모든 row 에 row 더해짐

# Column 벡터 — (3, 1) shape 명시 주의
col = np.array([100, 200, 300]).reshape(3, 1)  # shape (3, 1)
result_col = matrix + col
# matrix 의 모든 column 에 col 더해짐

# Z-score 정규화 — 양방향 broadcasting
data = np.random.default_rng(0).normal(size=(1000, 5))
z = (data - data.mean(axis=0)) / data.std(axis=0)   # column 별 평균/표준편차로

External links

Exercise

(1000, 3) 모양의 random 3D 점 배열 만들어. Python loop 없이 각 점의 원점까지 거리 계산. Broadcasting + np.sqrt 활용. 그리고 argmin / argmax 로 가장 가까운/먼 점 인덱스.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.