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


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

簡介:Tensorflow.js 是穀歌開發的一個開源庫,用於在瀏覽器或節點環境中運行機器學習模型以及深度學習神經網絡。 Tensorflow.js tf.bincount() 函數生成具有相同數據類型的提供大小的張量。張量的值將是提供的權重張量的索引處的數字之和,該索引對應於輸入張量中的索引號的索引。

用法:

tf.bincount( x ,weights ,size )

Parameters: 

  • x:所述變量是輸入張量。它應該是一維張量。
  • weights:所述變量是與 x 大小相同的張量。它是與 x 張量中的值對應的值。
  • size:狀態值是輸出張量的大小。

返回值:tf.tensor1D

tf.bincount() 函數的基本示例:

範例1:在這個例子中,我們創建一個張量並計算大小之間數字的出現並打印它。

Javascript


// Importing tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initializing the input
const geek_input = tf.tensor([1, 2, 9, 6, 5, 4, 7,
    4, 7, 4, 3, 2, 4, 2, 5, 1], [1, 16], 'int32');
// Printing Input tensor
console.log('Input tensor:',geek_input)
// Weight and size  for the bincount
const geek_Weight = [];
const geek_size = 5;
// Applying bincount to input tensor
const r = tf.bincount(geek_input, geek_Weight,geek_size)
// Printing result
console.log("Number of Index Number in tensor:",r)
// Printing Occurrence of index in tensor
const r1 = r.arraySync();
r1.map((e,i) => {console.log(`Index ${i} occurs`, e ,"times")})

輸出:

Input tensor: Tensor
     [[1, 2, 9, 6, 5, 4, 7, 4, 7, 4, 3, 2, 4, 2, 5, 1],]

Number of Index Number in tensor: 
Tensor
    [0, 2, 3, 1, 4]

Index 0 occurs 0 times
Index 1 occurs 2 times
Index 2 occurs 3 times
Index 3 occurs 1 times
Index 4 occurs 4 times

範例2:在這個例子中,我們創建了一個輸入張量和權重張量,並將其傳遞給 bincount 函數,看看 bincount 如何計算輸出張量的值。

Javascript


// Importing tensorflow.js library
import * as tf from "@tensorflow/tfjs"
  
// Initializing the input
const geek_input = tf.tensor([1, 2, 9, 6, 5,
    4, 7, 4, 7, 4, 3], [1, 11], 'int32');
// Printing Input tensor
console.log('Input tensor:',geek_input)
// Weight and size  for the bincount
const geek_Weight = tf.tensor(
    [0, 2, 5, 8, 9, 3, 5, 5, 3, 8, 2]);
const geek_size = 8;
// Applying bincount to input tensor
const r = tf.bincount(geek_input,geek_Weight,geek_size)
// Printing result
console.log("Output tensor:",r)

輸出:

Input tensor: Tensor
     [[1, 2, 9, 6, 5, 4, 7, 4, 7, 4, 3],]
Output tensor: Tensor
    [0, 0, 2, 2, 16, 9, 8, 8]

參考:https://js.tensorflow.org/api/latest/#bincount


相關用法


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