concept tf.tidy in category deep learning

This is an excerpt from Manning's book Deep Learning with JavaScript: Neural networks in TensorFlow.js.
Listing 3.7. The code for calculating and rendering an ROC curve and the AUC
function drawROC(targets, probs, epoch) { return tf.tidy(() => { const thresholds = [ #1 0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, #1 0.5, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, #1 0.9, 0.92, 0.94, 0.96, 0.98, 1.0 #1 ]; #1 const tprs = []; // True positive rates. const fprs = []; // False positive rates. let area = 0; for (let i = 0; i < thresholds.length; ++i) { const threshold = thresholds[i]; const threshPredictions = #2 utils.binarize(probs, threshold).as1D(); #2 const fpr = falsePositiveRate( #3 targets, #3 threshPredictions).arraySync(); #3 const tpr = tf.metrics.recall(targets, threshPredictions).arraySync(); fprs.push(fpr); tprs.push(tpr); if (i > 0) { #4 area += (tprs[i] + tprs[i - 1]) * (fprs[i - 1] - fprs[i]) / 2; #4 } #4 } ui.plotROC(fprs, tprs, epoch); return area; }); }
In the second approach, you can wrap the body of the for loop with tf.tidy():
for (let i = 0; i < 3; ++i) { tf.tidy(() => { #1 const y = model.predict(x); y.print(); console.log(`# of tensors: ${tf.memory().numTensors}` ); }); }With either approach, you should see the number of allocated tensors become constant over the iterations, indicating that there is no tensor memory leak anymore. Which approach should you prefer? In general, you should use tf.tidy() (the second approach), because it gets rid of the need to keep track of what tensors to dispose. tf.tidy() is a smart function that disposes all tensors created within the anonymous function passed to it as the argument (except those that are returned by the function—more on that later), even for the tensors not bound to any JavaScript objects. For example, suppose we modify the previous inference code slightly in order to obtain the index of the winning class using argMax():