Saturday, October 25, 2025
HomeLanguagesJavascriptTensorflow.js tf.keep() Function

Tensorflow.js tf.keep() 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 .keep() function is used to hold a tensor input that is formed within a tf.tidy() method from being spontaneously discarded.

Syntax:  

tf.keep(result)

Parameters:  

  • result: It is the stated tensor input which is to be held from being discarded.

Return Value: It returns tf.Tensor object.

Example 1:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Declaring a variable
let res1;
  
// Calling tidy method
const res2 = tf.tidy(() => {
     
  // Defining result parameter
  const result = tf.scalar(121);
     
  // Calling tf.keep() method
  res1 = tf.keep(result.sqrt());
});
  
// Printing output
res1.print();


Output:

Tensor
    11

Example 2:

Javascript




// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Declaring a variable
let res1;
  
// Calling tidy method
const res2 = tf.tidy(() => {
     
  // Calling tf.keep() method with its
  // parameter
  res1 = tf.keep(tf.tensor1d(
    [1.3, 0.5, 0, NaN, null, -.5]).cos());
});
  
// Printing output
res1.print();


Output:

Tensor
    [0.2675007, 0.8775977, 1, NaN, 1, 0.8775977]

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

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