torch.ones_like
function ones_like<S extends Shape, D extends DType = DType, Dev extends DeviceType = DeviceType>(input: Tensor<S, D, Dev>, options: TensorOptions = {}): Tensor<S, D, Dev>Create a one-filled tensor with the same shape as another tensor.
Returns a new tensor with identical shape to the input but filled with ones. Useful for masks, weights, scaling factors, or normalization operations where all elements start at 1.0 and are then modified.
By default, matches input's dtype, device, and gradient requirements. Override any of these with the options parameter.
- Shape matching: Automatically infers shape from input
- Dtype preservation: By default inherits input's dtype
- Device consistency: Stays on same device as input
- Neutral element: Ones act as multiplicative identity
Parameters
inputTensor<S, D, Dev>- Tensor to match shape from
optionsTensorOptionsoptional- Optional overrides: -
dtype: Data type (default: same as input) -requires_grad: Gradient tracking (default: same as input) -device: Compute device (default: same as input)
Returns
Tensor<S, D, Dev>– A one-filled tensor with shape = input.shapeExamples
// Match input shape
const x = torch.randn(3, 4, 5);
const ones = torch.ones_like(x); // [3, 4, 5] of ones, float32
// Initialize weights (uniform scale)
const batch = torch.randn(32, 64);
const scale = torch.ones_like(batch).mul(0.5); // Half scale
// Create multiplicative mask
const mask = torch.ones_like(x);
mask[invalid_indices] = 0; // Zero out invalid positions
const filtered = x.mul(mask);
// Compute statistics
const ones = torch.ones_like(batch); // [32, 64]
const count = ones.sum(1); // Count elements per sampleSee Also
- PyTorch torch.ones_like()
- ones - Create one tensor with explicit shape
- zeros_like - Zero-filled tensor with same shape
- full_like - Constant-filled tensor with same shape
- empty_like - Uninitialized tensor with same shape