And*_*rew 3 node.js tensorflow.js
对于tensorflow.js,如何设置node.js中Adam优化器的学习率?我收到错误:
model.optimizer.setLearningRate 不是一个函数
const optimizer = tf.train.adam(0.001)
model.compile({
loss: 'sparseCategoricalCrossentropy',
optimizer,
shuffle: true,
metrics: ['accuracy']
});
await model.fit(trainValues, trainLabels, {
epochs: 50,
validationData: [testValues, testLabels],
callbacks: {
onEpochBegin: async (epoch) => {
const newRate = getNewRate();
model.optimizer.setLearningRate(newRate);
}
}
});
Run Code Online (Sandbox Code Playgroud)
当您调用 时model.compile,您可以传递 的实例tf.train.Optimizer而不是传递字符串。这些实例是通过tf.train.*工厂创建的,您可以将学习率作为第一个参数传递。
代码示例
model.compile({
optimizer: tf.train.sgd(0.000001), // custom learning rate
/* ... */
});
Run Code Online (Sandbox Code Playgroud)
在训练期间更改学习率
目前,只有sgd优化器setLearningRate实现了方法,这意味着以下代码仅适用于通过以下方式创建的优化器实例tf.train.sgd:
const optimizer = tf.train.sgd(0.001);
optimizer.setLearningRate(0.000001);
Run Code Online (Sandbox Code Playgroud)
使用非官方API
优化器实例有一个protected属性learningRate,您可以更改该属性。该属性不是公共的,但由于这是 JavaScript,您可以通过learningRate在对象上设置来简单地更改该值,如下所示:
const optimizer = tf.train.adam();
optimizer.learningRate = 0.000001;
// or via your model:
model.optimizer.learningRate = 0.000001;
Run Code Online (Sandbox Code Playgroud)
请记住,您正在使用 API 的非官方部分,这可能随时会中断。