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


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

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

tf.grad()函數用於返回指定函數f(x)相對於x的梯度。

用法:

tf.grad (f)

參數:此函數接受如下所示的參數:

  • f:正在為其計算梯度的指定函數f(x)。

返回值:它返回指定函數f(x)相對於x的梯度。



範例1:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initializing a function f(x) = x^2
const f = x => x.square();
  
// Calling the .grad() function which 
// calculates f'(x) and gives value as 2x
const g = tf.grad(f);
  
// Initializing a tensor of values for
// which gradient will be returned
const x = tf.tensor1d([1, 2, 3]);
  
// Getting the values of gradient of the
// function f(x) for the above specified
// tensor 
g(x).print();

輸出:

Tensor
   [2, 4, 6]

範例2:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Using the function f(x) = x^3 as the 
// parameter for the .grad() function which 
// calculates f'(x) and gives value as 3x^2
const g = tf.grad(x => x.pow(tf.scalar(3, 'int32')));
  
// Initializing a tensor of values for
// which gradient will be returned
const x = tf.tensor1d([0, 1, 2]);
  
// Getting the values of gradient of the
// function f(x) for the above specified
// tensor 
g(x).print();

輸出:

Tensor
   [0, 3, 12]

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

相關用法


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