Wednesday, December 24, 2025
HomeLanguagesJavascriptTensorflow.js tf.expandDims() Function

Tensorflow.js tf.expandDims() Function

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 .expandDims() function is used to find tf.Tensor object whose rank is expanded with the help of tensor’s shape by inserting a dimension into it.

Syntax: 

tf.expandDims(x, axis?)

Parameters:  

  • x: It is the stated tensor input whose size is to be extended, and it can be of type tf.Tensor, TypedArray, or Array.
  • axis: It is the stated size index at which the shape of 1 is to be inserted. The by default value is zero i.e. the first dimension, and it is of type number.

Return Value: It returns tf.Tensor object.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining tensor input and axis
const y = tf.tensor1d([5, 6, 7, 8]);
const axs = 1;
  
// Calling tf.expandDims() method and
// Printing output
y.expandDims(axs).print();


Output:

Tensor
    [[5],
     [6],
     [7],
     [8]]

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Calling tf.expandDims() method and
// Printing output
tf.expandDims(tf.tensor1d([1.2, 3.5, 7.6, 9.7]), 1).print();


Output:

Tensor
    [[1.2      ],
     [3.5      ],
     [7.5999999],
     [9.6999998]]

Reference: https://js.tensorflow.org/api/latest/#expandDims

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32456 POSTS0 COMMENTS
Milvus
111 POSTS0 COMMENTS
Nango Kala
6825 POSTS0 COMMENTS
Nicole Veronica
11960 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12038 POSTS0 COMMENTS
Shaida Kate Naidoo
6959 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6912 POSTS0 COMMENTS
Umr Jansen
6893 POSTS0 COMMENTS