📜  Tensorflow.js tf.bincount()函数

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

Tensorflow.js tf.bincount()函数

简介: Tensorflow.js 是谷歌开发的一个开源库,用于在浏览器或节点环境中运行机器学习模型以及深度学习神经网络。 Tensorflow.js tf.bincount()函数生成具有相同数据类型的提供大小的张量。张量的值将是提供的权重张量的索引处的数字之和,该索引对应于输入张量中的索引号的索引。

句法:

tf.bincount( x ,weights ,size )

参数:

  • x:所述变量是输入张量。它应该是一维张量。
  • 权重:所述变量是与 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")})


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, 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