ML Grind

Tensor Creation - PyTorch Basics

Implement Tensor Creation in Python with NumPy. easy exercise with examples, hints, and instant feedback. No setup or signup required.

Tensor Creation

What you'll build: create_tensors(), which returns a dictionary of eight tensors made with the standard creation functions.

Background

Every model starts from tensors: weights from random normals, biases from zeros, position indices from arange, masks from eye or full. PyTorch's creation API mirrors NumPy's almost one to one, with two differences worth memorising:

  • Sizes: PyTorch takes them as separate arguments (torch.zeros(3, 4)), NumPy as a tuple (np.zeros((3, 4))). Both accept a tuple.
  • Default dtypes: PyTorch makes floats float32 and integers int64; NumPy makes floats float64. Mixing the two is a classic source of dtype errors.

API Reference

KeyPyTorchNumPy
'from_list'torch.tensor([1, 2, 3, 4], dtype=torch.float32)np.array([1, 2, 3, 4], dtype=np.float32)
'zeros'torch.zeros(3, 4)np.zeros((3, 4))
'ones'torch.ones(2, 3)np.ones((2, 3))
'randn'torch.randn(2, 3)np.random.randn(2, 3)
'arange'torch.arange(10)np.arange(10)
'linspace'torch.linspace(0, 1, 5)np.linspace(0, 1, 5)
'eye'torch.eye(4)np.eye(4)
'full'torch.full((2, 3), 7.0)np.full((2, 3), 7.0)

Expected Return Format

Return a dictionary with these keys:

  • 'from_list': the values [1, 2, 3, 4] with dtype float32, shape (4,)
  • 'zeros': zeros, shape (3, 4)
  • 'ones': ones, shape (2, 3)
  • 'randn': standard-normal samples, shape (2, 3)
  • 'arange': the integers 0, 1, ..., 9, shape (10,)
  • 'linspace': 5 evenly spaced values from 0 to 1 inclusive: [0.0, 0.25, 0.5, 0.75, 1.0]
  • 'eye': the 4x4 identity matrix
  • 'full': shape (2, 3), every entry 7.0

Conventions

  • The starter code seeds the generator with 42 (torch.manual_seed(42) or np.random.seed(42)). Keep that line, so 'randn' is reproducible: two calls to create_tensors() must return the same values.
  • Only 'from_list' needs an explicit dtype; the others use the library defaults.

Constraints

Use the creation functions in the table; no Python loops.

Follow-up

  • torch.tensor(arr) copies its input, while torch.from_numpy(arr) shares memory with the NumPy array. When does that matter?
  • Why does torch.arange(0, 1, 0.1) sometimes give a surprising number of elements, and why is linspace safer for float ranges?

Examples

Input: r = create_tensors(); r["linspace"]
Output: array([0.  , 0.25, 0.5 , 0.75, 1.  ])

linspace includes both endpoints, so 5 points are spaced 0.25 apart.

Input: r["from_list"].dtype, r["zeros"].shape, r["arange"][-1]
Output: (dtype('float32'), (3, 4), 9)

from_list asks for float32 explicitly; arange stops before 10.

Practice in Python

import numpy as np

def create_tensors() -> dict:
    """
    Create tensors with the standard creation functions.

    Returns:
        dict with keys 'from_list' (float32 [1, 2, 3, 4]), 'zeros' (3, 4),
        'ones' (2, 3), 'randn' (2, 3), 'arange' (0..9), 'linspace'
        (5 values from 0 to 1), 'eye' (4x4 identity) and 'full' ((2, 3) of 7.0)
    """
    np.random.seed(42)  # keep: makes 'randn' reproducible

    # Your code here
    pass

The interactive editor loads with Python and NumPy. Run your implementation against 6 tests, or use the progressive hints.

More exercises in this section →