Open In App

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

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.

The tf.data.Dataset class .prefetch() function is used to produce a dataset that prefetches the specified elements from this given dataset.

Syntax:

prefetch (bufferSize)

Parameters: This function accepts a parameter which is illustrated below:

  • bufferSize: It is an integer value that specifies the number of elements to be prefetched.

Return Value: It returns a dataset of elements.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Calling the .prefetch() function over
// the specified dataset of some elements
const a = tf.data.array([5, 10, 15, 20]).prefetch(4);
  
// Getting the dataset of prefetched elements
await a.forEachAsync(a => console.log(a));


Output:

5
10
15
20

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Specifying a dataset of some elements
const a = tf.data.array(["a", "b", "c", "d", "e"]);
  
// Calling the .prefetch() function over
// the above dataset along with the 
// batch of size 2
const b = a.batch(2)
const c = b.prefetch(2)
  
// Getting the dataset of prefetched elements
await c.forEachAsync(c => console.log(c));


Output:

Tensor
    ['a', 'b']
Tensor
    ['c', 'd']
Tensor
    ['e']

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


Last Updated : 22 Apr, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads