Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Tensorflow.js tf.data.generator() Function

  • Last Updated : 26 May, 2021

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.

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :