tf.ones() works identically to tf.zeros(), but fills every element with 1 instead of 0 — it's commonly used to build a mask that starts as everything included before selectively zeroing entries out, to initialize scaling factors that should start as a neutral multiplier, or in test/debugging code where a predictable, uniform input tensor is useful.
1Understanding tf.ones()
tf.ones() works identically to tf.zeros(), but fills every element with 1 instead of 0 — it's commonly used to build a mask that starts as everything included before selectively zeroing entries out, to initialize scaling factors that should start as a neutral multiplier, or in test/debugging code where a predictable, uniform input tensor is useful.
Use tf.ones_like(other_tensor) instead of tf.ones(other_tensor.shape) when you want a ones-filled tensor matching another tensor's shape and dtype exactly, without needing to read and pass those properties yourself.
import tensorflow as tf
ones = tf.ones([4])
print(ones)2Practical Example
Here is a real-world application of tf.ones() showing how it is used in production TensorFlow code.
import tensorflow as tf
mask = tf.ones([3, 3])
print(mask * 5)3Best Practices
Follow these guidelines when working with tf.ones():
1. Use tf.ones() to initialize masks or scaling factors that should conventionally start as a neutral, all-included value
2. Use tf.ones_like() instead of manually reading and passing another tensor's shape and dtype, when you want a matching ones-filled tensor
3. Multiply by tf.ones() and a scalar, or use tf.fill(), when you actually need a tensor filled with a specific constant other than 0 or 1
Tip: Use tf.ones_like(other_tensor) instead of tf.ones(other_tensor.shape) when you want a ones-filled tensor matching another tensor's shape and dtype exactly, without needing to read and pass those properties yourself.
import tensorflow as tf
ones = tf.ones([4])
print(ones)