等待 Tensorflow.js 的 model.fit 不工作
Await not working on model.fit of Tensorflow.js
我正在关注 Tensorflow.js 示例
但由于某种原因,浏览器在 model.fit
.
前面抱怨 await
关键字
错误信息:
Uncaught SyntaxError: await is only valid in async function
示例代码我运行:
const model = tf.sequential({
layers: [tf.layers.dense({units: 1, inputShape: [10]})]
});
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
for (let i = 1; i < 5 ; ++i) {
const h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
batchSize: 4,
epochs: 3
});
console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
}
我已经验证 model.fit returns 一个 Promise
我已经在 safari 和 chrome.
上试过了
我可以使用 .then 来解决这个问题,但如果可以的话,我想使用 await。
有谁知道为什么?
您需要将封闭函数声明为 async
函数,例如:
async function yourFunction() {
const model = tf.sequential({
layers: [tf.layers.dense({ units: 1, inputShape: [10] })]
});
model.compile({ optimizer: "sgd", loss: "meanSquaredError" });
for (let i = 1; i < 5; ++i) {
const h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
batchSize: 4,
epochs: 3
});
console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
}
}
否则,您需要使用 then
:
await
关键字只能在异步函数中使用,因此您必须将其包装在一个函数中。
保持范围的最简单方法是:
(async () => {
yourStuffHere
})();
创建一个匿名异步箭头函数,该函数在创建时调用自身。
或者如果你不需要整个事情都是异步的,你可以使用异步函数的 "older" 方法,通过使用 .then()
在异步函数运行时运行给定的回调函数完成:
model.fit(...).then(h => {
console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
});
我正在关注 Tensorflow.js 示例
但由于某种原因,浏览器在 model.fit
.
await
关键字
错误信息:
Uncaught SyntaxError: await is only valid in async function
示例代码我运行:
const model = tf.sequential({
layers: [tf.layers.dense({units: 1, inputShape: [10]})]
});
model.compile({optimizer: 'sgd', loss: 'meanSquaredError'});
for (let i = 1; i < 5 ; ++i) {
const h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
batchSize: 4,
epochs: 3
});
console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
}
我已经验证 model.fit returns 一个 Promise
我已经在 safari 和 chrome.
我可以使用 .then 来解决这个问题,但如果可以的话,我想使用 await。 有谁知道为什么?
您需要将封闭函数声明为 async
函数,例如:
async function yourFunction() {
const model = tf.sequential({
layers: [tf.layers.dense({ units: 1, inputShape: [10] })]
});
model.compile({ optimizer: "sgd", loss: "meanSquaredError" });
for (let i = 1; i < 5; ++i) {
const h = await model.fit(tf.ones([8, 10]), tf.ones([8, 1]), {
batchSize: 4,
epochs: 3
});
console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
}
}
否则,您需要使用 then
:
await
关键字只能在异步函数中使用,因此您必须将其包装在一个函数中。
保持范围的最简单方法是:
(async () => {
yourStuffHere
})();
创建一个匿名异步箭头函数,该函数在创建时调用自身。
或者如果你不需要整个事情都是异步的,你可以使用异步函数的 "older" 方法,通过使用 .then()
在异步函数运行时运行给定的回调函数完成:
model.fit(...).then(h => {
console.log("Loss after Epoch " + i + " : " + h.history.loss[0]);
});