TensorFlow tf.add()函数
tf.add()函数返回两个 tf.Tensor 对象元素的相加。 tf.Tensor 对象表示数字的多维数组。
句法:
tf.add( 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 add() function to add
// two Tensor objects
arr1.add(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 add() function to add
// two Tensor objects
arr1.add(arr2).print();
Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
// Declare the Tensor array
const arr = tf.tensor1d([5, 10, 15, 20, 25]);
// Declare a number
const num = tf.scalar(30);
// Use add() function to add
// Tensor object and a number
arr.add(num).print();
输出:
Tensor
[15, 30, 45, 60, 75]
示例 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 add() function to add
// two Tensor objects
arr1.add(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([5, 10, 15, 20, 25]);
// Declare a number
const num = tf.scalar(30);
// Use add() function to add
// Tensor object and a number
arr.add(num).print();
输出:
Tensor
[35, 40, 45, 50, 55]
参考: https://js.tensorflow.org/api/latest/#add