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


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

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

tf.sum()函數用於在其維度上計算指定張量的元素之和。它沿軸的尺寸減少了給定的輸入元素。如果參數“keepDims”為true,則減小的尺寸保留為長度1,否則張量的等級減小1。如果axes參數沒有條目,則它返回具有所有減小尺寸的單個元素的張量。

用法:

tf.sum(x, axis, keepDims)

參數:此函數接受三個參數,如下所示:

  • x:正在對其求和運算的輸入張量。如果數據類型為布爾值,則將其轉換為int32,並且返回的輸出也將在int32中。
  • axis:指定要減小的尺寸。默認情況下,它會縮小所有尺寸。它是可選參數。
  • keepDims:如果此參數值為true,它將保留長度為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();

輸出:

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]

相關用法


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