Saturday, October 18, 2025
HomeLanguagesJavascriptTensorflow.js tf.cast() Function

Tensorflow.js tf.cast() Function

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.cast() function is used to cast a specified Tensor to a new data type.

Syntax:

tf.cast (x, dtype)

Parameters: This function accepts two parameters which are illustrated below:

  • x: The input tensor which is being casted.
  • dtype: The data type in which input tensor is going to be casted.

Return Value: It returns a casted tensor of new data type.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initializing a tensor of some values
const x = tf.tensor1d([2.3, 1.7, 5, 0, 1, 0.5]);
  
// Calling the .cast() function over the 
// above tensor to cast in "int32" data type
tf.cast(x, 'int32').print();


Output:

 Tensor
   [2, 1, 5, 0, 1, 0]

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Using a tensor of some values
// as the parameter for .cast() function to
// cast into bool data type
tf.cast(tf.tensor1d([0, 1, -3]), 'bool').print();


Output:

Tensor
   [false, true, true]

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

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
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS