Open In App

Tensorflow.js tf.initializers.ones() Function

Last Updated : 09 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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




//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.

Javascript




//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.

Javascript




//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

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads