Open In App

Tensorflow.js tf.initializers.ones() Function

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:



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.




//import tensorflow.js
const tf=require("@tensorflow/tfjs")
//use tf.ones()
var GFG=tf.ones([3, 4]);
 
//print tensor
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.




//import tensorflow.js
const tf=require("@tensorflow/tfjs")
 
//create tensor of shape 1*4
var GFG=tf.ones([3]);
 
//print tensor
GFG.print()

Output

Tensor
   [1, 1, 1]

Example 3: tf.ones() with different dtype.




//import tensorflow.js
const tf=require("@tensorflow/tfjs")
 
// create tensor with default dtype as float32
tf.ones([3, 3]).print();
 
// create tensor with complex values
tf.ones([3, 3],'complex64').print();
 
// create tensor with boolean values by default all
// values true because initialization by ones
tf.ones([3, 3],'bool').print();
 
//create tensor with integer values
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

 


Article Tags :