当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。