Open In App

Tensorflow.js tf.data.generator() Function

Last Updated : 26 May, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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.generator() function is used to create a dataset using provided JavaScript generator which produces each element.

Syntax:

tf.data.generator(generator)

Parameters:

  • generator: It is a JavaScript generator function which returns a JavaScript iterator.

Return value: It returns tf.data.Dataset.

Example 1: This example illustrates how to create a dataset from an iterator factory.

Javascript




// Importing the tensorflow library
import * as tf from "@tensorflow/tfjs"
  
// Invoking .generator() function
let geek = tf.data.generator(function () {
  
    // Initializing variables used i.e.  
    // elements, index, result.
    let numbers = 4;
    let indices = 1;
    let outcome;
  
    // Creating and returning.next() function
    // in the format {value: TensorContainer,
    // done:boolean}.
    let repeator = {
        next: function () {
            if (indices <= numbers) {
                outcome =
                {
                    value: indices,
                    done: false
                };
                indices++;
                return outcome;
            }
            else {
                outcome =
                {
                    value: indices,
                    done: true
                };
                return outcome;
            }
        }
    };
    return repeator;
});
  
// Printing the result of returned promise
await geek.forEachAsync(function (geeks) {
    console.log(geeks);
});


Output:

1
2
3
4

Example 2: This example illustrates how to create a dataset from a generator.

Javascript




// Importing the tensorflow library
import * as tf from "@tensorflow/tfjs"
  
// Creating dataset from .generator() function 
let geek = tf.data.generator(function* () {
  
    // Initializing variables used i.e.  
    // data, and a.
    let data = 3;
    let a;
    for (i = 0; i <= data; ++i) {
        a = i;
        yield a;
    }
});
  
// Printing the result of returned promise
await geek.forEachAsync(function (geeks) {
    console.log(geeks);
});


Output:

0
1
2
3

Reference: https://js.tensorflow.org/api/3.6.0/#data.generator



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads