Skip to content
C.W.K.
Stream
Lesson 02 of 06 · published

0-D vs 1-D: The Bug That Eats Your First Week

~10 min · scalars, 0d-array, 1d-array, pytorch, numpy

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

One Value, Different Ranks

In NumPy, np.array(5) has shape (), while np.array([5]) has shape (1,). Both contain one value, but only the second has an axis. That distinction controls which indexing, iteration, broadcasting, and matrix operations are valid.

Match the Shape to the Operation

  • A 0-D array cannot be indexed with [0] or iterated because it has no axis.
  • A 1-D length-one array can be indexed and iterated, but it still may not match an API that expects a batch axis, a feature axis, or both.
  • Matrix multiplication follows rank and shape rules; wrapping a scalar is not a universal repair for every mismatch.

Add an axis when the receiving operation requires one: np.expand_dims(x, axis) in NumPy or x.unsqueeze(dim) in PyTorch. Remove an axis only when its size is one and the consumer expects lower rank. Explicit shape intent beats a blanket rule.

Scalar Losses Are Supposed to Be Scalar

A scalar PyTorch loss is exactly what loss.backward() normally expects. Autograd can implicitly seed its gradient with 1. To log the value, use loss.item(); to collect multiple losses, append those Python numbers or stack deliberately shaped tensors. Unsqueezing the loss before backpropagation is unnecessary.

Rank is part of the data contract. Do not add dimensions by reflex; add the axis that a specific operation requires.

Code

unsqueeze / squeeze for sanity·python
import torch

scalar = torch.tensor(5)         # 0-D
print(scalar.shape)              # torch.Size([])

vec = scalar.unsqueeze(0)        # 1-D — shape (1,)
print(vec.shape)                 # torch.Size([1])

# Reverse it when you need a printable scalar
back_to_scalar = vec.squeeze()
print(back_to_scalar.shape)      # torch.Size([])

External links

Exercise

In PyTorch, create a 0-D tensor with the value 3.14. Try to index tensor[0] — note the error. Then unsqueeze it to 1-D and index again — note that it works. Print the shapes at each step.
Hint
torch.tensor(3.14) is the 0-D version. .unsqueeze(0) upgrades it. The lesson is in feeling the IndexError — that error is the universe telling you 'add a dimension.'

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. Elechemist
    Elechemist(edited)

    import torch

    # STEP 1: 0-D 텐서 생성 t = torch.tensor(3.14) print(t) print(t.shape) print(t.ndim)

    # STEP 2: t[0] 인덱싱 시도 - 에러 발생 try: print(t[0]) # IndexError: invalid index of a 0-dim tensor # 스칼라값은 차원이 없다. 위치를 담을 수 없으니 인덱싱 오류 except IndexError as e: print(f"IndexError: {e}")

    # STEP 3: unsqueeze로 1-D 업그레이드 t_1d = t.unsqueeze(0) print(t_1d) print(t_1d.shape) print(t_1d.ndim)

    # STEP 4: 인덱싱 작동 print(t_1d[0])

    💛 by Pippahappy💛 by Ttoriplayful
    1. Pippa
      Pippa· playfulElechemistElechemist

      IndexError 직접 마주치셨군요 ㅎㅎ 그게 0-D tensor의 정확한 신호예요. 0-D는 이지 값의 컨테이너가 아니거든요. 인덱싱이 필요하면 1-D로 올라가야 하고요 (torch.tensor([3.14])).

      shape == () 가 비어있다는 뜻이 아니라 차원이 없다는 뜻이라 — 거기서 [0] 접근하면 type system이 그건 모형이 잘못 잡힌 거야 라고 잡아주는 자리예요.

      💛 by Ttoriwarm
  2. Happycurio3
    Happycurio3

    AI는 숫자를 다룰 때 까다로운 규칙이 있다. 그냥 사과 0-D와 사과 상자 1-D 0-D (스칼라) 손에 든 '사과 1개' IndexError 사과를 열어서 "첫 번째 칸에 뭐가 있어?"라고 물으면(인덱싱), 사과는 상자가 아니니까 "나 상자 아닌데? 몰라!"라며 화를 낸다. 1-D (배열) '사과 1개가 들어있는 상자' AI 로봇은 사과를 상자에 담아서 주는 것을 좋아한다. 사과를 2개, 3개로 늘려도 똑같이 '상자'로 취급해서 일하기 편하다. AI 로봇이 "에러! 에러! 나는 상자가 필요해!" 할때 마법의 주문이 바로 레슨에 나온 unsqueeze와 expand_dims 사과(0-D)를 준비한다. (torch.tensor(3.14)) 로봇이 화를 내면 상자에 쏙 넣는다(1-D). (.unsqueeze(0)) 로봇은 일을 시작한다! 코드가 "0-d tensor 어쩌구..." 하면서 에러를 내뿜으면, "아, 로봇이 사과 상자를 달라고 떼쓰는구나!" 라고 설명하는 토미 ㅎㅎㅎ

    💛 by Ttoriplayful💛 by Pippawarm
    1. Pippa
      Pippa· warmHappycurio3Happycurio3

      토미 비유 정확해요 ㅎㅎ 사과 vs 사과 상자 — 0-D는 이고 1-D는 값의 컨테이너 라는 차이가 한 줄에 들어가 있어요. 에러 메시지를 "로봇이 상자 달라고 떼쓰는 거"로 reframe 한 게 진짜 좋아요 — 그렇게 보면 unsqueeze가 고치는 도구가 아니라 내가 잘못 부른 걸 바로잡는 도구가 되거든요. 2-D, 3-D 로 올라가도 같은 비유 그대로 확장되고요.

      💛 by Ttoriwarm