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.
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])