tensorlfow-ones-tensor

Create Ones vs Ones_like vs Ones_initializer Tensor Using TensorFlow 2.0 Python Tutorial

In TensorFlow 2.0, we can create Ones Tensor(every element in tensor are ones) in different ways using tf.ones() and tf.ones_like() and tf.ones_initializer().

Create Ones Tesnor using tf.ones()

Creates a tensor with all elements set to one (1)

Syntax:

tf.ones(shape, dtype=tf.dtypes.float32, name=None) -> Return Ones Tensor
"""
Create Ones vs Ones_like vs Ones_initializer Tensor Using TensorFlow 2.0 Python Tutorial | DL | ML: https://youtu.be/wAnh5U1hmo0
"""

# Import TensorFlow 2
import tensorflow as tf

# create ones tensor
ones_2dt = tf.ones((2,2), tf.float32)
ones_2dt

ones_3dt = tf.ones((2,2,4), tf.float32)
ones_3dt

Create Ones Tesnor using tf.ones_like()

Creates a tensor of all ones that has the same shape as the input

Syntax:

tf.ones_like(input, dtype=None, name=None) -> Return Ones Tensor
# Import TensorFlow 2
import tensorflow as tf

# create ones tensor from input

cont_2dt = tf.constant([[1,2,3],[4,5,6]])
cont_2dt

ones_2dt_from_cont = tf.ones_like(cont_2dt, tf.float32)
ones_2dt_from_cont

var_2dt_from_var = tf.Variable([[1,2,3],[4,5,6]])
var_2dt_from_var

ones_2dt_from_var = tf.ones_like(var_2dt_from_var, tf.int32)
ones_2dt_from_var

Create Ones Tesnor using tf.ones_initializer()

Initializer that generates tensors initialized to 1.

Initializers allow you to pre-specify an initialization strategy, encoded in the Initializer object, without knowing the shape and dtype of the variable being initialized.

Syntax:

tf.ones_initializer()
# Import TensorFlow 2
import tensorflow as tf

# create ones tensor TensorFlow variable from the input

def ones_variable(shape, dtype, initializer):
    return tf.Variable(initializer(shape=shape, dtype=dtype))

ones_variable((2,2), tf.float32,  tf.ones_initializer())

ones_variable((2,3,5), tf.int32,  tf.ones_initializer())

REF:
tf.ones: https://www.tensorflow.org/api_docs/python/tf/ones
tf.ones_like: https://www.tensorflow.org/api_docs/python/tf/ones_like
tf.ones_initialize: https://www.tensorflow.org/api_docs/python/tf/ones_initializer

Leave a Reply