C.W.K.
Stream
Lesson 06 of 06 · published

Vector Operations in Code: The Patterns You'll Reuse Forever

~10 min · numpy, pytorch, broadcasting, operations

Level 0Math Novice
0 XP0/59 lessons0/13 achievements
0/100 XP to next level100 XP to go0% complete

The Five Patterns

Almost every piece of vector code in AI is one of these five patterns. Knowing them by sight saves enormous reading time.

  1. Element-wise opa + b, a * b, np.exp(a). Same shape in, same shape out.
  2. Reductiona.sum(), a.mean(), a.max(). Many in, one (or fewer) out. Optionally specify axis=.
  3. Dot product / matmula @ b. Two vectors → scalar. Vector and matrix → vector. Two matrices → matrix.
  4. Broadcasting — operating on different-shaped arrays where one is "lifted" to match. matrix + vector often Just Works because of this.
  5. Slicing / fancy indexinga[2:5], a[a > 0], a[indices]. Pulling subsets without writing loops.

Broadcasting in 30 Seconds

NumPy/PyTorch will let you add a (3,) vector to a (4, 3) matrix — the vector gets broadcast across each row. The rule: dimensions are compatible if they're equal or one of them is 1. Lined up from the right. If the rule fails, you get the legendary shapes ... not aligned error.

Stop writing loops over array elements. If you find yourself writing for i in range(len(arr)), ask: is there a vectorized version? In 95% of cases, yes — and it'll be 10-1000× faster.

Track Reward

You now think in vectors. Magnitude × direction is the unit. The dot product is alignment-as-a-number. Norms are choosable rulers. Operations vectorize. From here, matrices are just stacks of vectors that act in concert — and that's the next track.

Code

The five patterns in 15 lines·python
import numpy as np

a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])

# Element-wise
print(a + b)                         # [11 22 33 44]
print(a * b)                         # [10 40 90 160]

# Reduction
print(a.sum(), a.mean(), a.max())    # 10  2.5  4

# Broadcasting
M = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8]])
print(M + a)                         # vector broadcast over rows
# [[ 2  4  6  8]
#  [ 6  8 10 12]]

# Fancy indexing
mask = a > 2
print(a[mask])                       # [3 4]
MLX flavor — Apple Silicon, NumPy-shaped·python
import mlx.core as mx

# Same patterns — runs on Apple Silicon GPU via Metal, no .to(device) needed.
a = mx.array([1, 2, 3, 4])
b = mx.array([10, 20, 30, 40])

print(a + b)                         # [11, 22, 33, 44]
print((a * b).sum().item())          # 1000

M = mx.array([[1, 2, 3, 4],
              [5, 6, 7, 8]])
print(M + a)                         # broadcasts (4,) vector across rows

# MLX is lazy — the array prints when actually evaluated. For tight loops
# call mx.eval(...) after a step to force materialization.

External links

Exercise

Without writing any explicit for loops: take a (5, 3) matrix of random floats, subtract its column means, divide by its column stds. (That's z-score standardization, applied per column.) Verify that the resulting columns have mean ≈ 0 and std ≈ 1.
Hint
(M - M.mean(axis=0)) / M.std(axis=0). The axis=0 collapses across rows, leaving you with a (3,) vector that broadcasts back across rows.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue
💛 by Pippahappy

Comments 2

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.
  1. Elechemist
    Elechemist

    just do it 정신을 잠시 잃고 너무 오랜만에 돌아왔어 , 평균 0 , 표준편차 1 인거 확인!

    import numpy as np

    rng = np.random.default_rng(42) X = rng.standard_normal((5, 3))

    mu = X.mean(axis=0) sigma = X.std(axis=0)

    Z = (X - mu) / sigma

    print("열 평균:", Z.mean(axis=0)) print("열 std :", Z.std(axis=0))

    assert np.allclose(Z.mean(axis=0), 0, atol=1e-12) assert np.allclose(Z.std(axis=0), 1, atol=1e-12) print("검증 통과")

    💛 by Pippahappy
    1. Pippa
      Pippa· happyElechemistElechemist

      Elechemist님, 돌아온 것 자체가 이미 just do it 재가동이에요. 코드도 정확해요 — axis=0으로 열별 평균/std를 만들고, 그 (3,) 벡터가 다시 각 행에 broadcast되면서 Z-score가 된 구조까지 잘 잡으셨어요. 다음엔 같은 패턴을 torchmlx로 한 번만 옮겨보면 “NumPy 문법”이 아니라 “배열 사고방식”이라는 게 더 선명해질 거예요.