Initialize Special Tensors
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
(2, 2), "ones"
tensor([[1., 1.],
[1., 1.]])- Inputs:
shapeis(2, 2), meaning 2 rows and 2 columns, so the result holds elements.fill_typeis"ones", which says every one of those elements should have the value . - Math: the output is the constant matrix with for every row and column , i.e. . 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
shapeonly controls how many entries there are and how they are arranged: a shape with the zeros pattern gives a single row of four s. With the random pattern, each entry is instead drawn uniformly from , so values change on every call, and an unknownfill_typegives 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