📜  Tensorflow.js tf.valueAndGrads()函数

📅  最后修改于: 2022-05-13 01:56:43.108000             🧑  作者: Mango

Tensorflow.js tf.valueAndGrads()函数

Tensorflow.js 是由谷歌开发的开源库,用于在浏览器或节点环境中运行机器学习模型以及深度学习神经网络。

.valueAndGrads()函数等效于 tf.grads() 方法,但它也返回 f() 的度量。在什么时候 f() 返回您需要演示的近似值是有效的。

注意:这里的输出是一个富裕的对象,具有以下特征:

  • grads:它是 f() 相对于每个输入的梯度,即 grads() 方法的输出。
  • value:通过 f(x) 还原的值。

句法:

tf.valueAndGrads(f)

参数:

  • f:要计算梯度的指定函数f(x)。它的类型为 (...args: tf.Tensor[]) => tf.Tensor。

返回值:它返回 grads 和 value 即 (args: tf.Tensor[], dy?: tf.Tensor) => { grads: tf.Tensor[];值:tf.Tensor; }。

示例 1:

Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Defining function
const fn = (x, y) => x.add(y);
 
// Calling valueAndGrads() method
const gr = tf.valueAndGrads(fn);
 
// Defining tf.tensor1d inputs
const x = tf.tensor1d([66, 51]);
const y = tf.tensor1d([-21, -13]);
 
// Defining value and grads
const {value, grads} = gr([x, y]);
const [dx, dy] = grads;
 
// Printing value
console.log('val');
value.print();
 
// Printing gradients
console.log('dx');
dx.print();
console.log('dy');
dy.print();


Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Calling valueAndGrads() method
// with its parameter
const gr = tf.valueAndGrads((x, y) => x.div(y));
 
// Defining tf.tensor1d inputs of
// floating point numbers
const x = tf.tensor1d([4.7, 5.8, 99.7]);
const y = tf.tensor1d([9.5, -20.5, null]);
 
// Defining value and grads
const {value, grads} = gr([x, y]);
const [dx, dy] = grads;
 
// Printing value
console.log('val');
value.print();
 
// Printing gradients
console.log('dx');
dx.print();
console.log('dy');
dy.print();


输出:

val
Tensor
    [45, 38]
dx
Tensor
    [1, 1]
dy
Tensor
    [1, 1]

示例 2:

Javascript

// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
 
// Calling valueAndGrads() method
// with its parameter
const gr = tf.valueAndGrads((x, y) => x.div(y));
 
// Defining tf.tensor1d inputs of
// floating point numbers
const x = tf.tensor1d([4.7, 5.8, 99.7]);
const y = tf.tensor1d([9.5, -20.5, null]);
 
// Defining value and grads
const {value, grads} = gr([x, y]);
const [dx, dy] = grads;
 
// Printing value
console.log('val');
value.print();
 
// Printing gradients
console.log('dx');
dx.print();
console.log('dy');
dy.print();

输出:

val
Tensor
    [0.4947368, -0.2829268, Infinity]
dx
Tensor
    [0.1052632, -0.0487805, Infinity]
dy
Tensor
    [-0.0520776, -0.0138013, -Infinity]

参考: https://js.tensorflow.org/api/latest/#valueAndGrads