TensorFlow tf.sub()函数
tf.sub()函数返回两个 tf.Tensor 对象元素的减法。 tf.Tensor 对象表示数字的多维数组。
句法:
tf.sub( a, b )
参数:
- a:它包含第一个 tf.Tensor 对象。该参数的值可以是 tf.TensorTypedArray|Array。
- b:它包含从第一个 tf.Tensor 对象中减去的第二个 tf.Tensor 对象。该参数的值可以是 (tf.Tensor|TypedArray|Array)。该参数的类型与a的类型相同。
返回值:此函数返回 tf.Tensor 对象。
示例 1:
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Declare the Tensor array
const arr1 = tf.tensor1d([10, 20, 30, 40, 50]);
const arr2 = tf.tensor1d([5, 10, 15, 20, 25]);
// Use sub() function to subtract
// two Tensor objects
arr1.sub(arr2).print();
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Declare the Tensor array
const arr1 = tf.tensor1d([30, 40, 50]);
const arr2 = tf.tensor1d([5, 10, 15, 20, 25]);
// Use sub() function to subtract
// two Tensor objects
arr1.sub(arr2).print();
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Declare the Tensor array
const arr = tf.tensor1d([15, 10, 25, 20, 35]);
// Declare a number
const num = tf.scalar(30);
// Use sub() function to subtract number
// from Tensor object
arr.sub(num).print();
输出:
Tensor
[5, 10, 15, 20, 25]
示例 2:
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Declare the Tensor array
const arr1 = tf.tensor1d([30, 40, 50]);
const arr2 = tf.tensor1d([5, 10, 15, 20, 25]);
// Use sub() function to subtract
// two Tensor objects
arr1.sub(arr2).print();
输出:
An error occured on line: 7
Operands could not be broadcast together with shapes 3 and 5.
示例 3:
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Declare the Tensor array
const arr = tf.tensor1d([15, 10, 25, 20, 35]);
// Declare a number
const num = tf.scalar(30);
// Use sub() function to subtract number
// from Tensor object
arr.sub(num).print();
输出:
Tensor
[-15, -20, -5, -10, 5]
参考: https://js.tensorflow.org/api/latest/#sub