Thursday, September 4, 2025
HomeLanguagesJavascriptTensorflow.js tf.data.Dataset class .shuffle() Method

Tensorflow.js tf.data.Dataset class .shuffle() 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.

The tf.data.Dataset.shuffle() method randomly shuffles a tensor along its first dimension.

Syntax:

tf.data.Dataset.shuffle(
    buffer_size, seed=None, 
    reshuffle_each_iteration=None
)

Parameters:

  • buffer_size: This is the number of elements from which the new dataset will be sampled.
  • seed[optional]: It is an optional parameter used to create a random seed for the distribution, to see the same results use same seed.
  • reshuffle_each_iteration: A Boolean, which is true indicates that the dataset should be pseudo randomly reshuffled each time it is iterated over. Default value is true. It is Optional parameter.

Return Value: A tensor with same shape and data type as value, but shuffled along its first dimension.

Example 1: In this example first we will create a tensor and then shuffle it, In this example reshuffle_each_iteration is True

Javascript




async function shuffle() {
  
    // Creating a Tensor
    const a = tf.data.array([1, 2, 3, 4, 5, 6]).shuffle(3);
    await a.forEachAsync(e => console.log(e)); //print 1
    await a.forEachAsync(e => console.log(e)); //print 2
}
  
shuffle();


Output:

3 4 1 2 5 6
3 4 2 5 6 1

Example 2: In this example, seed is set to an Integer, whenever a specific integer is used it will generate that specific output

Javascript




async function shuffleseed() {
    const a = tf.data.array([1, 2, 3]).shuffle(3, seed = 42);
    await a.forEachAsync(e => console.log(e));
  
    const b = tf.data.array([1, 2, 3]).shuffle(3, seed = 42);
    await b.forEachAsync(e => console.log(e));
}
  
shuffleseed();


Output:

2 1 3
2 1 3

Reference: https://js.tensorflow.org/api/3.6.0/#tf.data.Dataset.shuffle

RELATED ARTICLES

Most Popular

Dominic
32263 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6627 POSTS0 COMMENTS
Nicole Veronica
11799 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11858 POSTS0 COMMENTS
Shaida Kate Naidoo
6749 POSTS0 COMMENTS
Ted Musemwa
7025 POSTS0 COMMENTS
Thapelo Manthata
6696 POSTS0 COMMENTS
Umr Jansen
6716 POSTS0 COMMENTS