Tensorflow.js tf.initializers.ones() Function
Last Updated :
09 Aug, 2021
Tensorflow.js is a very well-known machine learning library that used to develop a machine learning model using JavaScript. The main purpose to use this library is to run and deploy a machine learning model directly from the browser or in Node.js. Tensorflow.js is an open-source hardware-accelerated JavaScript library. In this article, we’re going to discuss tf.ones() function in Tensorflow.js.
tf.ones() creates a Tensor with all elements set to 1, or it initializes tensor with value 1.
Syntax:
tf.ones (shape, dtype)
Parameters:
- Shape: This represents the shape of the result array. The shape is an array of integer which represent a number of row and columns.
- dtype: These are a type of the values which return in result. The default value of type is float. It can be int32,complex64,bool, string or float32.
Return type:
This method returns the tensor of type dtype with the shape of order (row*column) and initialized with 1.
Example 1: In this example, we are going to create a tensor of order 3*4 and applying tf.ones() on it.
Javascript
const tf=require( "@tensorflow/tfjs" )
var GFG=tf.ones([3, 4]);
GFG.print()
|
​Output:
Tensor
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]
Example 2: In this example, we are going to create a tensor of order 1×4 by giving a single element in a shape array.
Javascript
const tf=require( "@tensorflow/tfjs" )
var GFG=tf.ones([3]);
GFG.print()
|
Output
Tensor
[1, 1, 1]
Example 3: tf.ones() with different dtype.
Javascript
const tf=require( "@tensorflow/tfjs" )
tf.ones([3, 3]).print();
tf.ones([3, 3], 'complex64' ).print();
tf.ones([3, 3], 'bool' ).print();
tf.ones([3, 3], 'int32' ).print();
|
Output:
Tensor
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
Tensor
[[1 + 0j, 1 + 0j, 1 + 0j],
[1 + 0j, 1 + 0j, 1 + 0j],
[1 + 0j, 1 + 0j, 1 + 0j]]
Tensor
[[true, true, true],
[true, true, true],
[true, true, true]]
Tensor
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
Reference:https://js.tensorflow.org/api/latest/#initializers.ones
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...