由于生成器不能使用回调,如何将 TensorFlow.js tf.data.generator 用于远程数据源

How can one use TensorFlow.js tf.data.generator for remote data sources since generators can't use callbacks

引入tf.data.DatasetAPI时,Deep Learning with JavaScript book表示:

Large applications require technology for accessing data from a remote source, piece by piece, on demand.

但是我读过的关于生成器的文档说生成器不能通过回调产生值。但是,还有什么方法可以访问远程资源呢?我看不出如何使用 tf.data.generator in such cases. MDN documentation on yield 状态:

yield can only be called directly from the generator function that contains it. It can't be called from nested functions or from callbacks.

您可以将 async 函数(或 return 一个 Promise 函数)传递给生成器。然后可以在函数内部(甚至在循环内部)使用 await 来处理任何异步任务。

代码示例

const dataset = tf.data.generator(async function* () {
    const dataToDownload = await fetch(/* ... */);
    while (/* ... */) {
        const moreData = await fetch(/* ... */);
        yield otherData;
    }
});

本例使用node-fetch,当然其他下载数据的方法也可以。

异步生成器

关于 MDN 文档,生成器可以定义为 async,但这改变了它们的工作方式。他们不会 return 立即获取值,而是 return 您必须等待的 Promise。因此,您必须调用 await iterator.next() 来读取值,而不是调用 iterator.next()

代码示例

async function* foo(index) {
  while (true) {
    yield index++;
  }
}

(async () => {
  const iterator = foo(0);
  console.log((await iterator.next()).value); // 0
  console.log((await iterator.next()).value); // 1
})();

幸运的是,Tensorflow.js 能够在生成器中处理 async functions/Promises。