Open In App

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

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

The .mapAsync() method is used to map the stated dataset over an asynchronous one to one conversion.



Syntax:

mapAsync(transform)

Parameters:



Return Value: It returns tf.data.Dataset.

Example 1:  




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining dataset formed of an array of
// numbers and calling mapAsync() method
const res = tf.data.array([16, 12, 13]).mapAsync(
    y => new Promise(function(rsol){
        setTimeout(() => {
            rsol(y + y);
        }, Math.sqrt()*400 + 300);
}));
  
// Calling toArray() method and
// Printing output
console.log(await res.toArray());

Output:

32, 24, 26

Example 2:




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Calling mapAsync() method and
// Printing output
console.log(await tf.data.array([4.5, 8.5])
    .mapAsync(y => new Promise(function(tm) {
        setTimeout(() => {
            tm(y * y);
        })
    })).toArray());

Output:

20.25, 72.25

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


Article Tags :