The factory functions you'll actually use
You'll create tensors three ways: from Python data, from a shape, or from another tensor. The factory zoo is wide; in practice, six functions cover ~95% of real code.
| Function | What it gives you | Typical use |
|---|---|---|
torch.tensor | Tensor from Python list / scalar | Quick test data, labels |
torch.zeros / ones | Filled with 0 or 1 | Bias init, masks, accumulators |
torch.randn | Normal(0, 1) | Weight init, dummy inputs |
torch.rand | Uniform [0, 1) | Probabilities, dropout-style noise |
torch.arange | Integer / float range | Positional encodings, indices |
torch.full | Filled with constant | Padding values, masks |
The like family — torch.zeros_like(x), torch.randn_like(x), torch.empty_like(x) — copies x's shape, dtype, AND device, which is exactly what you want when allocating a sibling tensor for a result. It's the small comfort that prevents 90% of "expected cuda:0 got cpu" errors.
Two stylistic rules to commit to
- Prefer
torch.randn(N)overtorch.tensor(np.random.randn(N)). Detour through NumPy is unnecessary and breaks dtype/device contracts silently. - Pass
device=...at creation time when you can. Allocating on CPU then.to('cuda')doubles allocation traffic for no reason.