Create Zeros vs Zeros _like vs Zeros _initializer Tensor Using TensorFlow 2.0 Python Tutorial

In TensorFlow 2.0, we can create Zeros Tensor(every element in tensor are zeros) in different ways using tf.zeros() and tf.zeros_like() and tf.zeros_initializer().

Create Zeros Tesnor using tf.zeros()

Creates a tensor with all elements set to zero (0)

Syntax:

tf.zeros(shape, dtype=tf.dtypes.float32, name=None) -> Return ZerosTensor
"""
Create Zeros vs Zeros _like vs Zeros _initializer Tensor Using TensorFlow 2.0 Python Tutorial | DL | ML: https://youtu.be/uIzg8RG1IZo
"""

# ### Import TensorFlow 2
import tensorflow as tf

# ### Creates a tensor with all elements set to zero.
zeros_2dt = tf.zeros((2,2), dtype=tf.int32)
zeros_2dt

zeros_3dt = tf.zeros((2,2,4), dtype=tf.int8)
zeros_3dt

zeros_3dt.shape

zeros_3dt.dtype

zeros_3dt.numpy()

zeros_3dt.numpy().tolist()

Create Zeros Tesnor using tf.zeros_like()

Creates a tensor with all elements set to zero.

Syntax:

tf.zeros_like(input, dtype=None, name=None) -> Return Zeros Tensor
# #### Creates a tensor with all elements set to zero.

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

zl_2dt_from_cont = tf.zeros_like(cont_2dt)
zl_2dt_from_cont

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

zl_2dt_from_var = tf.zeros_like(var_2dt, dtype=tf.bool)
zl_2dt_from_var

Create Zeros Tesnor using tf.zeros_initializer()

Initializer that generates tensors initialized to 0.

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.zeros_initializer()
def zeros_variable(shape, dtype, initializer):
    return tf.Variable(initializer(shape=shape, dtype=dtype))

zi_t_var= zeros_variable((2,2), tf.float32, tf.zeros_initializer())
zi_t_var

zeros_variable((3,2,5), tf.bool, tf.zeros_initializer())

tf.Variable(tf.zeros_initializer()((2,2), tf.float32))

REF:
tf.zeros: https://www.tensorflow.org/api_docs/python/tf/zeros
tf.zeros_like: https://www.tensorflow.org/api_docs/python/tf/zeros_like
tf.zeros_initializer: https://www.tensorflow.org/api_docs/python/tf/zeros_initializer

Leave a Reply

Top