Tensorflow.js是Google開發的開源庫,用於在瀏覽器或節點環境中運行機器學習模型和深度學習神經網絡。
tf.train.momemtum() 函數用於創建使用動量梯度下降算法的 tf.MomentumOptimizer。
用法:
tf.train.momentum(learningRate, momentum, useNesterov)
參數:
- learningRate (number):它指定了動量梯度下降算法將使用的學習率。
- momentum (number):它指定了動量梯度下降算法將使用的動量。
- useNesterov (boolean):它指定是否使用 Nesterov 動量。它是一個可選參數。
返回值:它返回一個 tf.MomentumOptimizer
示例 1:通過學習係數 a 和 b,使用動量優化器擬合函數 f=(a*x+b)。在這個例子中,我們將使用 Nesterov 動量。所以 useNestrov 將是真的。
Javascript
// Importing tensorflow
import * as tf from "@tensorflow/tfjs"
const xs = tf.tensor1d([0, 1, 2]);
const ys = tf.tensor1d([1.1, 5.9, 16.8]);
const a = tf.scalar(Math.random()).variable();
const b = tf.scalar(Math.random()).variable();
const f = x => a.mul(x).add(b);
const loss = (pred, label) => pred.sub(label).square().mean();
const learningRate = 0.01;
const momentum = 10;
const useNestrov = true;
const optimizer = tf.train.momentum(learningRate, momentum, useNestrov);
// Train the model.
for (let i = 0; i < 10; i++) {
optimizer.minimize(() => loss(f(xs), ys));
}
// Make predictions.
console.log(
`a:${a.dataSync()}, b:${b.dataSync()}}`);
const preds = f(xs).dataSync();
preds.forEach((pred, i) => {
console.log(`x:${i}, pred:${pred}`);
});
輸出:
a:1982014720, b:1076448384 x:0, pred:1076448384 x:1, pred:3058463232 x:2, pred:5040477696
示例 2:通過學習係數 a 和 b,使用動量優化器擬合二次方程。在這個例子中,我們不會使用 Nesterov 動量。所以 useNestrov 將是假的。
Javascript
// Importing tensorflow
import * as tf from "@tensorflow/tfjs"
const xs = tf.tensor1d([0, 1, 2, 3]);
const ys = tf.tensor1d([1.1, 5.9, 16.8, 33.9]);
const a = tf.scalar(Math.random()).variable();
const b = tf.scalar(Math.random()).variable();
const c = tf.scalar(Math.random()).variable();
const f = x => a.mul(x.square()).add(b.mul(x)).add(c);
const loss = (pred, label) => pred.sub(label).square().mean();
const learningRate = 0.01;
const momentum = 10;
const useNestrov = false;
const optimizer = tf.train.momentum(learningRate, momentum, useNestrov);
// Train the model.
for (let i = 0; i < 10; i++) {
optimizer.minimize(() => loss(f(xs), ys));
}
// Make predictions.
console.log(
`a:${a.dataSync()}, b:${b.dataSync()}, c:${c.dataSync()}`);
const preds = f(xs).dataSync();
preds.forEach((pred, i) => {
console.log(`x:${i}, pred:${pred}`);
});
輸出:
a:892235776, b:331963616, c:134188384 x:0, pred:134188384 x:1, pred:1358387840 x:2, pred:4367058944 x:3, pred:9160201216
參考: https://js.tensorflow.org/api/1.0.0/#train.momentum
相關用法
- PHP imagecreatetruecolor()用法及代碼示例
- p5.js year()用法及代碼示例
- d3.js d3.utcTuesdays()用法及代碼示例
- PHP ImagickDraw getTextAlignment()用法及代碼示例
- PHP Ds\Sequence last()用法及代碼示例
- PHP Imagick floodFillPaintImage()用法及代碼示例
- PHP geoip_continent_code_by_name()用法及代碼示例
- d3.js d3.map.set()用法及代碼示例
- PHP GmagickPixel setcolor()用法及代碼示例
- Tensorflow.js tf.layers.embedding()用法及代碼示例
- PHP opendir()用法及代碼示例
- PHP cal_to_jd()用法及代碼示例
- d3.js d3.bisectLeft()用法及代碼示例
注:本文由純淨天空篩選整理自abhinavjain194大神的英文原創作品 Tensorflow.js tf.train.momentum() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。