Sunday, November 17, 2024
Google search engine
HomeLanguagesJavascriptTensorflow.js tf.range() Function

Tensorflow.js tf.range() Function

Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.

The tf. range() is used to create a new tf.Tensor1D filled with the numbers in the range provided with the help of start, stop, step, and dtype.

Syntax:

tf.range(start, stop, step, dtype)

Parameters:

  • start: It is an integer start value that denotes the starting number of the range.
  • stop: It is an integer stop value that denotes the ending number of the range, and it is not included.
  • step: It is an integer increment which is 1 or -1 by default. It is an optional parameter.
  • dtype: It is the data type of the output tensor. It defaults to ‘float32’. It is an optional parameter.

Return Value: It returns a new Tensor1D object.

Example 1: In this example, we try to generate a range of numbers from 1 to 9 with default step 1.

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating the tensor1D array by tf.range
var val = tf.range(1,10);
  
// Printing the tensor
val.print()


Output:

Tensor
    [1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 2: In this example, we try to generate odd numbers between 1 and 10 using step size 2.

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating the tensor1D array by tf.range
var val = tf.range(1,10,2);
  
// Printing the tensor
val.print()


Output:

Tensor
    [1, 3, 5, 7, 9]

Example 3: In this example, we try to generate even numbers between 0 and 10 using step size 2.

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating the tensor1D array by tf.range
var val = tf.range(0,10,2);
  
// Printing the tensor
val.print()


Output:

Tensor
    [0, 2, 4, 6, 8],

Example 4: In this example, we will try to use the dtype parameter.

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Creating the tensor1D array by tf.range
var val = tf.range(-1,1,1,'bool');
  
// Printing the tensor
val.print()


Output:

​Tensor
    [true, false]

Reference:https://js.tensorflow.org/api/latest/#range

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments