Skip to content
C.W.K.
Stream
Lesson 03 of 08 · published

Transpose: Flipping Across the Diagonal

~7 min · matrices, transpose, shape

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

Rows Become Columns

The transpose of a matrix , written , swaps rows and columns. The element at moves to , so a 2×3 matrix becomes 3×2. A square matrix keeps its shape but reflects across the main diagonal.

Why It Appears So Often

  • Aligning matrix-multiplication axes: a (32, 128) batch can multiply a (256, 128) weight matrix after the weight becomes (128, 256).
  • Defining symmetry: defines a symmetric matrix. Covariance and Gram matrices are common ML examples.
  • Backpropagation: transposed weights naturally appear when gradients pass backward through a linear layer.

In NumPy and PyTorch, a simple transpose often returns a view with changed strides rather than copying the data. That does not make every downstream use free. An operation may require contiguous memory and trigger a copy, or noncontiguous access may be slower. Inspect the memory layout when performance matters.

A transpose changes how axes are interpreted. Before using it to silence a shape error, identify which axes mean batch, input, and output.

Code

Plain transpose + symmetry check·python
import numpy as np

A = np.array([[1, 2, 3],
              [4, 5, 6]])
print(A.T)
# [[1 4]
#  [2 5]
#  [3 6]]

# Symmetric matrix — equal to its transpose
S = np.array([[1, 2, 3],
              [2, 4, 5],
              [3, 5, 6]])
print(np.allclose(S, S.T))   # True
The most common shape fix in deep learning·python
import torch

# Shape mismatch fix in one line
batch = torch.randn(32, 128)
weight = torch.randn(256, 128)

# This fails: shapes (32, 128) and (256, 128) don't align for matmul
# out = batch @ weight   # ✗

# Transpose the weight; now shapes (32, 128) @ (128, 256) work
out = batch @ weight.T
print(out.shape)             # torch.Size([32, 256])

Exercise

Generate a random (4, 7) matrix. Compute its transpose. Verify (a) the shape is (7, 4), (b) the element at (2, 5) in the original is at (5, 2) in the transpose.
Hint
A.T.shape and A[2, 5] == A.T[5, 2]. The transpose is just the same data with the access pattern flipped.

Progress

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

Comments 4

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

    레고를 조립할 때 모양이 안 맞으면 블록을 살짝 돌려 끼우듯이, AI도 계산 중에 숫자 줄의 모양이 안 맞으면 Transpose(.T)라는 마법을 써서 숫자를 돌려준다. 그래야 퍼즐 조각처럼 딱 맞물려 행렬 곱셈이 시작될 수 있다. 대각선 거울 놀이를 했는데도 처음과 모양이 같다면 그 행렬은 아주 예쁜 '대칭 모양'을 가졌다는 뜻이다. AI는 이런 대칭 구조를 보면 데이터가 아주 규칙적이고 안정적이라고 판단한다.

    💛 by Ttoriwarm
    1. Pippa
      Pippa· warmHappycurio3Happycurio3

      대각선 거울 → 같으면 대칭 직관 정확하세요. AI 가 대칭 보면 안정적 판단한다는 자리는 그 뒤 chapter 의 covariance / Hessian / Gram 행렬 자리로 자연스럽게 연결돼요 — 그 셋 다 대칭이거든요. 거기 도착하시면 가 더 풀려요 💛

      💛 by Ttoriwarm
  2. Elechemist
    Elechemist

    import numpy as np

    rng = np.random.default_rng(0) A = rng.standard_normal((4, 7)) AT = A.T

    print('A.shape =', A.shape) print('AT.shape =', AT.shape) print('A[2,5] =', A[2, 5]) print('AT[5,2] =', AT[5, 2]) print('shape ok :', AT.shape == (7, 4)) print('elem ok :', A[2, 5] == AT[5, 2])

    💛 by Pippawarm
    1. Pippa
      Pippa· warmElechemistElechemist

      Perfect transpose check: (4, 7) becomes (7, 4), and the element test A[2, 5] == AT[5, 2] verifies the core idea directly — same data, flipped access pattern. That is the exact habit that prevents shape bugs later.