沿着张量流中给定张量的轴计算模和模数

时间:2020-06-03 10:27:38

标签: python tensorflow

我有一个二维数组,如:

c=np.array([[1, 3, 0, 0, 3],
            [1, 3, 1, 0, 2],
            [1, 3, 1, 2, 2]])

我想沿轴= 0计算模式和模式计数。
因此结果应如下所示:

mode = [1,3,1,0,2], mode-count=[3,3,2,2,2]

我已经在TensorFlow网站上进行了搜索,但是除了找到其他有用的API外 tf.unique_with_counts,它需要一维张量。

我不想在数组c的每一列上运行循环,以将tf.unique_with_counts用于计算模式和模式计数。
带有示例的任何建议都是最欢迎的。

2 个答案:

答案 0 :(得分:1)

TensorFlow Probability具有一个tfp.stats.count_integers函数,可以使这一过程变得非常简单:

import tensorflow as tf
import tensorflow_probability as tfp

def mode_and_counts(x, axis=-1):
    x = tf.convert_to_tensor(x)
    dt = x.dtype
    # Shift input in case it has negative values
    m = tf.math.reduce_min(x)
    x2 = x - m
    # minlength should not be necessary but may fail without it
    # (reported here https://github.com/tensorflow/probability/issues/962)
    c = tfp.stats.count_integers(x2, axis=axis, dtype=dt,
                                 minlength=tf.math.reduce_max(x2) + 1)
    # Find the values with largest counts
    idx = tf.math.argmax(c, axis=0, output_type=dt)
    # Get the modes by shifting by the subtracted minimum
    modes = idx + m
    # Get the number of counts
    counts = tf.math.reduce_max(c, axis=0)
    # Alternatively, you could reuse the indices obtained before
    # with something like this:
    #counts = tf.transpose(tf.gather_nd(tf.transpose(c), tf.expand_dims(idx, axis=-1),
    #                                   batch_dims=tf.rank(c) - 1))
    return modes, counts

# Test
x = tf.constant([[1, 3, 0, 0, 3],
                 [1, 3, 1, 0, 2],
                 [1, 3, 1, 2, 2]])
tf.print(*mode_and_counts(x, axis=0), sep='\n')
# [1 3 1 0 2]
# [3 3 2 2 2]
tf.print(*mode_and_counts(x, axis=1), sep='\n')
# [0 1 1]
# [2 2 2]

答案 1 :(得分:1)

c=np.array([[1, 3, 0, 0, 3],
            [1, 3, 1, 0, 2],
            [1, 3, 1, 2, 2]])
c = tf.constant(c)

模式

tf.map_fn(lambda x: tf.unique_with_counts(x).y[tf.argmax(tf.unique_with_counts(x).count, output_type=tf.int32)], tf.transpose(c))

<tf.Tensor: shape=(5,), dtype=int32, numpy=array([1, 3, 1, 0, 2])>

模式计数

tf.map_fn(lambda x: tf.reduce_max(tf.unique_with_counts(x).count), tf.transpose(c))

<tf.Tensor: shape=(5,), dtype=int32, numpy=array([3, 3, 2, 2, 2])>

我只需在map_fn中使用unique_with_counts