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


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

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

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

用法:

tf.valueAndGrad (f)

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

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

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



範例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 .valueAndGrad() function over
// the above function as its parameter which
// calculates f'(x) = 2x
const g = tf.valueAndGrad(f);
  
// Initializing a Tensor of values at which
// value of gradient is calculated
const x = tf.tensor1d([0, 1, 2, 3]);
  
// Returning the value of f() and 
// gradient of f(x)
const {value, grad} = g(x);
  
// Getting the value of f()
console.log('value');
value.print();
  
// Getting the gradient of f(x) at 
// the above tensor values
console.log('grad');
grad.print();

輸出:

value
Tensor
   [0, 1, 4, 9]
grad
Tensor
   [0, 2, 4, 6]

範例2:

Javascript


// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Using a function f(x) = x^3 as the parameter
// for the .valueAndGrad() function which
// calculates f'(x) = 3x^2
const g = tf.valueAndGrad(x => x.pow(tf.scalar(3, 'int32')));
  
// Using a Tensor of values at which
// value of gradient is calculated 
const {value, grad} = g(tf.tensor1d([-1, 0, 0.3, 4]));
  
// Getting the value of f()
console.log('value');
value.print();
  
// Getting the gradient of f(x)
console.log('grad');
grad.print();

輸出:

value
Tensor
   [-1, 0, 0.027, 64]
grad
Tensor
   [3, 0, 0.27, 48]

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

相關用法


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