📜  Tensorflow.js tf.sum()函数

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

Tensorflow.js tf.sum()函数

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

tf.sum()函数用于计算指定张量在其维度上的元素之和。它沿轴的维度减少给定的输入元素。如果参数“keepDims”为真,则保留长度为 1 的缩减维度,否则 Tensor 的等级会减少 1。如果轴参数没有条目,则返回一个包含所有缩减维度的单个元素的 Tensor。

句法:

tf.sum(x, axis, keepDims)

参数:此函数接受三个参数,如下所示:

  • x:计算求和运算的输入张量。如果数据类型为布尔值,则转换为int32,返回的输出也为int32。
  • 轴:要减少的指定维度。默认情况下,它会减少所有维度。它是可选参数。
  • keepDims:如果此参数值为真,则保留长度为 1 的缩减维度,否则 Tensor 的秩减少 1。它也是可选参数。

返回值:它为求和运算的结果返回一个张量。

示例 1:

Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initializing a some tensors 
const a = tf.tensor1d([0, 1]);
const b = tf.tensor1d([3, 5]);
const c = tf.tensor1d([2, 4, 7]);
  
// Calling the .sum() function over 
// the above tensors
a.sum().print();
b.sum().print();
c.sum().print();


Javascript
// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initializing a some tensors 
const a = tf.tensor1d([0, 1]);
const b = tf.tensor2d([3, 5, 2, 8], [2, 2]);
const c = tf.tensor1d([2, 4, 7]);
  
// Initializing a axis parameters
const axis1 = -1;
const axis2 = -2;
const axis3 = 0;
  
// Calling the .sum() function over 
// the above tensors
a.sum(axis1).print();
b.sum(axis2, true).print();
c.sum(axis1, false).print();
b.sum(axis3, false).print();


输出:

Tensor
   1
Tensor
   8
Tensor
   13

示例 2:

Javascript

// Importing the tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initializing a some tensors 
const a = tf.tensor1d([0, 1]);
const b = tf.tensor2d([3, 5, 2, 8], [2, 2]);
const c = tf.tensor1d([2, 4, 7]);
  
// Initializing a axis parameters
const axis1 = -1;
const axis2 = -2;
const axis3 = 0;
  
// Calling the .sum() function over 
// the above tensors
a.sum(axis1).print();
b.sum(axis2, true).print();
c.sum(axis1, false).print();
b.sum(axis3, false).print();

输出:

Tensor
   1
Tensor
    [[5, 13],]
Tensor
   13
Tensor
   [5, 13]