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


Tensorflow.js tf.variableGrads()用法及代碼示例

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

.variableGrads() 函數用於計算和返回 f(x) 的梯度,與由參數 varList 提供的規定的可管理變量列表相比。此外,如果未給出列表,則默認情況下它是所有可管理的變量。

用法:

tf.variableGrads(f, varList?)

Parameters: 

  • f:它是要執行的規定函數。其中, f() 必須返回一個標量。它的類型是 (() => tf.Scalar)。
  • varList:它是用於計算梯度的規定變量列表,默認情況下它是所有可管理的變量。它是 tf.Variable[] 類型。

返回值:它返回類型為 tf.Scalar 的值,它還返回類型為 {[name:string]:tf.Tensor} 的 grads。



範例1:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining list of variables
const p = tf.variable(tf.tensor1d([9, 6]));
const q = tf.variable(tf.tensor1d([7, 8]));
  
// Defining tf.tensor1d
const r = tf.tensor1d([3, 4]);
  
// Defining the function that is to
// be executed
const fn = () => p.add(r.square()).mul(q.add(r)).sum();
  
// Calling tf.variableGrads method
const {val, grads} = tf.variableGrads(fn);
  
// Printing output
Object.keys(grads).forEach(
    variable_Name => grads[variable_Name].print());

輸出:

Tensor
    [10, 12]
Tensor
    [18, 22]

範例2:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Defining list of variables containing
// float values
const p = tf.variable(tf.tensor1d([3.1, 5.2]));
const q = tf.variable(tf.tensor1d([4.4, 6.7]));
  
// Defining tf.tensor1d with float values
const r = tf.tensor1d([7.1, 3.2]);
  
// Calling tf.variableGrads method
const {val, grads} = tf.variableGrads(
    () => p.add(r.square()).mul(q.add(r)).sum());
  
// Printing output
Object.keys(grads).forEach(
    variable_Name => grads[variable_Name].print());

輸出:

Tensor
    [11.5, 9.8999996]
Tensor
    [53.5099983, 15.4400005]

參考: https://js.tensorflow.org/api/latest/#variableGrads

相關用法


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