Tensorflow.js is an open-source library for running machine learning models and deep learning neural networks in the browser or node environment. The tf.ones() function is used to create a new tensor where all elements are set to 1.
Syntax:
tf.ones(shape, dtype, name)
Parameters:
- shape: It takes the shape of the tensor. It can be a multi-dimensional array or an int32
- dtype: It takes the data type of the 1 we are inserting. It is by default set to float32, however, it can be int32 as well. It is an optional parameter.
- name: It takes the name of the operation we are performing. It is None by default. It is an optional parameter.
Return Value: It returns a tensor with the same data type.
Example 1: In this example, we will create a 2D Tensor with all values set to 1 of integer data type.
JavaScript
// Import tensorflow import tensorflow as tf // Get a Tensor val = tf.ones([10, 10], tf.int32) // Print the Tensor print(val) |
Output:
tf.Tensor( [[1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1] [1 1 1 1 1 1 1 1 1 1]], shape=(10, 10), dtype=int32)
Example 2: In this example, we will create a 1D Tensor with all values set to 1 of float data type.
JavaScript
// Import tensorflow import tensorflow as tf // Get a Tensor val = tf.ones(5, tf.float32) // Print a Tensor print(val) |
Output:
tf.Tensor([1. 1. 1. 1. 1.], shape=(5,), dtype=float32)
Reference:https://js.tensorflow.org/api/latest/#ones