v9.1.1
Menu

Initialize Special Tensors

easyFREEBasic OpsPyTorch BasicsPytorch

Problem Statement

Create a tensor filled with a chosen pattern.

Background

PyTorch provides functions to create tensors with specific initial values:

  • torch.zeros(shape) - every element is 0
  • torch.ones(shape) - every element is 1
  • torch.rand(shape) - uniform random values in [0, 1)

These are the building blocks for weight initialization, masks and padding.

Your Task

Write a function create_special_tensor(shape, fill_type) that returns a tensor of the given shape:

  • "zeros" → a tensor of zeros
  • "ones" → a tensor of ones
  • "random" → a tensor of uniform random values in [0, 1)
  • any other fill_type → return None

Output Format

Return a PyTorch tensor (float32), or None for an invalid fill_type.

Example

Input
(2, 2), "ones"
Output
tensor([[1., 1.],
        [1., 1.]])
Reasoning
  • Inputs: shape is (2, 2), meaning 2 rows and 2 columns, so the result holds 2×2=42 \times 2 = 4 elements. fill_type is "ones", which says every one of those elements should have the value 11.
  • Math: the output is the constant matrix T∈R2×2T \in \mathbb{R}^{2 \times 2} with Tij=1T_{ij} = 1 for every row ii and column jj, i.e. T=(1111)T = \begin{pmatrix} 1 & 1 \\ 1 & 1 \end{pmatrix}. Nothing depends on position, only on the pattern name.
  • Output: the tensor tensor([[1., 1.], [1., 1.]]). The trailing dots mark the entries as floating-point numbers (32-bit, as the output format requires), not integers.
  • Notice that shape only controls how many entries there are and how they are arranged: a 1×41 \times 4 shape with the zeros pattern gives a single row of four 00s. With the random pattern, each entry is instead drawn uniformly from [0,1)[0, 1), so values change on every call, and an unknown fill_type gives None instead of a tensor.

Constraints

  • shape is a tuple of positive integers
  • fill_type is one of: "zeros", "ones", "random"
  • Return None for invalid fill_type

Learn this in

More from Pytorch

solution.py

Test results

Sign in to run your code against the test cases.