Create a uniform tensor
Initialize a constant-valued input or buffer with known dimensions.
TensorFlow · Function
Creates a tensor of a specified shape whose elements are all one. The element type defaults to tf.float32 and can be selected with dtype.
tf.ones constructs a tensor from the requested shape, fills every element with one, and uses the requested element type. If no type is supplied, TensorFlow creates a float32 tensor; an optional name labels the operation, while layout can produce a DTensor with a specified layout.
tf.ones(shape, dtype=tf.dtypes.float32, name=None, layout=None)| Name | Type | Description |
|---|---|---|
shape | list, tuple, or 1-D int32 Tensor | A list or tuple of integers, or a one-dimensional int32 Tensor describing the output dimensions. |
dtype | tf.DType | Optional element type for the output; defaults to tf.float32. |
name | string | Optional operation name. |
layout | tf.experimental.dtensor.Layout | Optional DTensor layout; when supplied, the result is a DTensor with that layout. |
A Tensor with all elements set to one (1).
import tensorflow as tf
x = tf.ones([2, 3], dtype=tf.int32)
print(x)Creates and prints a 2-by-3 integer tensor whose six elements are all one.
Initialize a constant-valued input or buffer with known dimensions.
Control numeric behavior for integer or floating-point computation.
Create distributed tensor data with an explicitly requested arrangement.
tf.ones creates a tensor with the supplied shape and sets every element to one. Its dtype defaults to tf.float32, but callers can request another dtype such as tf.int32.
Follow-up: How would you create ones matching an existing tensor? Use tf.ones_like, which derives the output shape from the input and can optionally use a new dtype.
shape can be a list of integers, a tuple of integers, or a one-dimensional int32 Tensor. The returned Tensor has that shape and contains only ones.
Follow-up: What if the desired values are not all one? Use tf.fill with dimensions and a value, or tf.zeros when the value should be zero.
The layout argument is optional and accepts tf.experimental.dtensor.Layout. When provided, the result is a DTensor with that layout.
Follow-up: How can a layout be requested through DTensor APIs? DTensor documentation shows wrapping tf.ones with dtensor.call_with_layout and passing a layout and shape.
tf.ones_liketf.zerostf.filltf.eye