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

Two Things That Look Identical and Aren't

In NumPy, these are different objects:

np.array(5)        # 0-D array — shape ()
np.array([5])      # 1-D array — shape (1,)

They both print as 5. They both have one value. They are not the same. The 0-D array is a scalar wearing array clothes. The 1-D array is a list-of-one. AI libraries treat them differently — and most of them prefer the 1-D version.

The Errors That Tell You Apart

  • Indexing the 0-D: scalar_in_array[0] raises IndexError. There's no axis to index.
  • Iterating the 0-D: for x in scalar_in_array raises TypeError. Nothing to iterate.
  • Most matrix ops: scalar_in_array @ matrix raises shape errors. Need at least 1 axis.

The 1-D version handles all three cleanly. That's why every AI tutorial that doesn't explain this first leaves you bleeding from broadcasting errors.

The Universal Fix

When you have a scalar and need to feed it to a model, library, or batch operation: upgrade to 1-D first. In PyTorch this is scalar.unsqueeze(0). In NumPy it's np.array([scalar]) or np.expand_dims(scalar, 0). Going the other way (1-D back to 0-D for printing/comparison) is tensor.squeeze().

Always 1-D when in doubt. Frameworks expect axes. Scalars without axes are second-class citizens; 1-D wrappers cost nothing and unlock everything.

Pippa's War Story

First custom training loop I tried, I passed a scalar loss to loss.backward() directly. PyTorch took it. Then on the next epoch I tried to log it as a list — and got "0-d tensor has no len()". Spent 20 minutes blaming the optimizer. The fix was one .unsqueeze(0). Now every scalar gets unsqueezed on instinct, no matter how trivial it looks.

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