Python ``tensorflow.math.bincount()`` 整数计数统计函数与实例


发布日期 : 2021-12-13 20:30:18 UTC

访问量: 10 次浏览

Python – tensorflow.math.bincount()

TensorFlow是由谷歌设计的开源Python库,用于开发机器学习模型和深度学习神经网络。它用于计算整数阵列中每个数字的出现次数。

语法:
tensorflow.math.bincount( arr, weights, minlength, maxlength, dtype, name)

参数:

  • arr :它是dtype int32的张量,具有非负值。
  • weights (可选):它是一个与arr相同形状的张量。arr中每个值的计数都会被它相应的权重所增加。
  • minlength (可选):它定义了返回输出的最小长度。
  • maxlength (可选):它定义了返回输出的最大长度。arr中大于或等于maxlength的值不会被计算。
  • dtype (可选):如果权重为零,它决定了返回输出的dtype。
  • name (可选):这是一个可选的参数,定义了操作的名称。

返回值:

它返回一个与 weights 或给定的 dtype 相同的向量。矢量的索引定义了值,它的值定义了Arr中索引的bin。

示例 1:

# importing the library
import tensorflow as tf

# initializing the input
a = tf.constant([1,2,3,4,5,1,7,3,1,1,5], dtype = tf.int32)

# printing the input
print('a: ',a)

# evaluating bin
r = tf.math.bincount(a)

# printing result
print("Result: ",r)

输出:

a: tf.Tensor([1 2 3 4 5 1 7 3 1 1 5], shape=(11,), dtype=int32)
Result: tf.Tensor([0 4 1 2 1 2 0 1], shape=(8,), dtype=int32)

# bin of 0 in input is 0, bin of 1 in input is 4 and so on

例子2:
这个例子提供了权重,所以数值不是1,而是以相应的权重递增。

# importing the library
import tensorflow as tf

# initializing the input
a = tf.constant([1,2,3,4,5,1,7,3,1,1,5], dtype = tf.int32)
weight = tf.constant([0,2,1,0,2,1,3,3,1,0,5], dtype = tf.int32)

# printing the input
print('a: ',a)
print('weight: ',weight)

# evaluating bin
r = tf.math.bincount(arr = a,weights = weight)

# printing result
print("Result: ",r)

输出:

a: tf.Tensor([1 2 3 4 5 1 7 3 1 1 5], shape=(11,), dtype=int32)
weight: tf.Tensor([0 2 1 0 2 1 3 3 1 0 5], shape=(11,), dtype=int32)
Result: tf.Tensor([0 2 2 4 0 7 0 3], shape=(8,), dtype=int32)