tidy
2025年02月11日
一、认识
tf.tidy(nameOrFn, fn?)
函数的作用是执行提供的函数 fn
,并在其执行后,清理 fn
内部创建的所有中间张量(Tensors
),除了 fn
返回的张量。注意:fn
不能是 async
函数(不允许返回 Promise
)。返回的结果可以是一个复杂对象。
使用 tf.tidy()
可以帮助防止内存泄漏。通常,建议在 tf.tidy()
内包装 TensorFlow.js
操作,以实现自动内存管理。注意: 变量(Variables
) 不会被 tf.tidy()
自动清理。如果需要清理变量,请使用 tf.disposeVariables()
,或者直接对变量调用 dispose()
方法。
二、语法
// y = 2 ^ 2 + 1
const y = tf.tidy(() => {
// a, b, and one will be cleaned up when the tidy ends.
const one = tf.scalar(1);
const a = tf.scalar(2);
const b = a.square();
console.log('numTensors (in tidy): ' + tf.memory().numTensors);
// The value returned inside the tidy function will return
// through the tidy, in this case to the variable y.
return b.add(one);
});
console.log('numTensors (outside tidy): ' + tf.memory().numTensors);
y.print();