Open In App

Tensorflow.js tf.data.Dataset class .forEachAsync() Method

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. It also helps the developers to develop ML models in JavaScript language and can use ML directly in the browser or in Node.js.

The tf.data.Dataset.forEachAsync() function is used after applying a function to each and every element of the dataset. We can use this method to print an array, modifying the values of the array etc.



Syntax:

forEachAsync(f)

Parameters:



Return Value: It returns a promise

Example 1:




// Creating an array
const arr = tf.data.array([10, 20, 30, 40, 50]);
  
// Applying the function on the array
await arr.forEachAsync(element => console.log(element));

Output:

10
20
30
40
50

Example 2: In this example we will pass a function that calculates the square of an element.




// Creating an array
const arr = tf.data.array([1, 2, 3, 4, 5]);
  
// Applying the function on the array
await arr.forEachAsync(element => console.log(element*element));

Output:

1
4
9
16
25

Reference: https://js.tensorflow.org/api/latest/#tf.data.Dataset.forEachAsync

Article Tags :