LolAsdOmgWtfAfk
LolAsdOmgWtfAfk

Reputation: 109

How to perform reduce_op on multiple dimensions at once?

Let's say I have a list of rank N tensors expressed as a rank N+1 tensor. For example, a list of 100 10x20 matrices as a rank 3 tensor with shape (100,10,20). I need to perform the same operations on each of those matrices: summing all the elements, mean and median of the values of the ith matrix, for each matrix. Is it possible to do something like tf.math.reduce_sum, tf.math.reduce_mean, tf.contrib.distributions.percentile, along axis 0, but computing the whole matrix at once for each element along the 0 axis?

E.G.:

matricesList = tf.constant([[[1,1],[1,1]],
                           [[2,2],[2,2]]])

op = sum_matrices_along_axis(matrixList)

With expected op = [4,8]

Upvotes: 3

Views: 1542

Answers (1)

javidcf
javidcf

Reputation: 59731

You can pass multiple dimensions to the axis parameter of reduction operations:

import tensorflow as tf

matricesList = tf.constant([[[1, 1], [1, 1]],
                            [[2, 2], [2, 2]]])
matricesSum = tf.reduce_sum(matricesList, axis=[1, 2])
with tf.Session() as sess:
    print(sess.run(matricesSum))
    # [4 8]

Even if you do not know the number of dimensions in advance, you can still reduce "all but the first" dimensions:

import tensorflow as tf

# The number of dimensions of tensorsList is unspecified
tensorsList = tf.placeholder(tf.int32)
# Dimensions from one to the last one
reduceDims = tf.range(1, tf.rank(tensorsList))
tensorsSum = tf.reduce_sum(tensorsList, axis=reduceDims)
with tf.Session() as sess:
    matrices = [[[1, 1], [1, 1]],
                [[2, 2], [2, 2]]]
    print(sess.run(tensorsSum, feed_dict={tensorsList: matrices}))
    # [4 8]

Upvotes: 3

Related Questions