Friday, May 15, 2026
HomeLanguagesTensorFlow – How to create a tensor with all elements set to...

TensorFlow – How to create a tensor with all elements set to one

TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning  neural networks.

Methods Used:

  • tf.ones: This methods accepts the shape and type and returns a tensor of given shape and type having all values set to 1.
  • tf.fill: This method accepts shape, value and type and returns a tensor of given shape and type having all values set to value.

Example 1: This example uses ones() method to create a tensor with all elements set to one.

Python3




# importing the library
import tensorflow as tf
 
# Generating a Tensor of shape (2, 3)
res = tf.ones(shape = (2, 3))
 
# Printing the resulting Tensors
print("Res: ", res )


Output:

Res:  tf.Tensor(
[[1. 1. 1.]
 [1. 1. 1.]], shape=(2, 3), dtype=float32)

Example 2: This example uses fill() method with value = 1 to create a tensor with all elements set to one.

Python3




# importing the library
import tensorflow as tf
 
# Generating a Tensor of shape (2, 3)
res = tf.fill(dims = (2, 3), value = 1)
 
# Printing the resulting Tensors
print("Res: ", res )


Output:

Res:  tf.Tensor(
[[1 1 1]
 [1 1 1]], shape=(2, 3), dtype=int32)
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32514 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6892 POSTS0 COMMENTS
Nicole Veronica
12012 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12107 POSTS0 COMMENTS
Shaida Kate Naidoo
7016 POSTS0 COMMENTS
Ted Musemwa
7262 POSTS0 COMMENTS
Thapelo Manthata
6975 POSTS0 COMMENTS
Umr Jansen
6963 POSTS0 COMMENTS