當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Tensorflow.js tf.train.Optimizer.minimize()用法及代碼示例

Tensorflow.js是Google開發的開源庫,用於在瀏覽器或節點環境中運行機器學習模型和深度學習神經網絡。

.minimize() 方法執行給定的函數 f() 並嘗試通過計算 y 相對於由 varList 表示的給定可訓練變量列表的梯度來最小化 f() 的標量輸出。如果沒有提供列表,它會計算所有可訓練變量的梯度。

用法:

Optimizer.minimize (f, returnCost?, varList?)

參數:

  • f (() => tf.Scalar):它指定要執行的函數及其輸出要最小化。
  • returnCost (boolean):指定是否返回執行 f() 產生的標量成本值。
  • varList (tf.Variable[]):它指定了可訓練變量的列表。

返回值:tf.Scalar |無效的



範例1:

Javascript


// Importing tensorflow
import tensorflow as tf
    
const xs = tf.tensor1d([0, 1, 2]);
const ys = tf.tensor1d([1.3, 2.5, 3.7]);
    
const x = tf.scalar(Math.random()).variable();
const y = tf.scalar(Math.random()).variable();
    
// Define a function f(x, y) = x + y.
const f = x => x.add(y);
const loss = (pred, label) => 
    pred.sub(label).square().mean();
    
const learningRate = 0.05;
    
// Create adagrad optimizer
const optimizer = 
  tf.train.adagrad(learningRate);
    
// Train the model.
for (let i = 0; i < 5; i++) {
   optimizer.minimize(() => loss(f(xs), ys));
}
    
// Make predictions.
console.log(
`x:${x.dataSync()}, y:${y.dataSync()}`);
const preds = f(xs).dataSync();
preds.forEach((pred, i) => {
console.log(`x:${i}, pred:${pred}`);
});

輸出

x:0.9395854473114014, y:1.0498266220092773
x:0, pred:1.0498266220092773
x:1, pred:2.0498266220092773
x:2, pred:3.0498266220092773

範例2:

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]);
    
// Choosing random coefficients
const a = tf.scalar(Math.random()).variable();
const b = tf.scalar(Math.random()).variable();
const c = tf.scalar(Math.random()).variable();
    
// Defing function f = (a*x^2 + b*x + c)
const f = x => a.mul(x.square()).add(b.mul(x)).add(c);
const loss = (pred, label) => pred.sub(label).square().mean();
    
// Setting congigurations for our optimizer
const learningRate = 0.01;
const decay = 0.1;
const momentum = 1;
const epsilon = 0.5;
const centered = true;
    
// Create the ptimizer
const optimizer = tf.train.rmsprop(learningRate, 
        decay, momentum, epsilon, centered);
    
// Train the model.
for (let i = 0; i < 8; 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:3.6799352169036865, 
    b:4.26292610168457, c:4.544136047363281
x:0, pred:4.544136047363281
x:1, pred:12.486997604370117
x:2, pred:27.789730072021484
x:3, pred:50.45233154296875

參考:https://js.tensorflow.org/api/latest/#tf.train.Optimizer.minimize




相關用法


注:本文由純淨天空篩選整理自abhinavjain194大神的英文原創作品 Tensorflow.js tf.train.Optimizer class .minimize() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。