Reduce tensor by concatenating numbers in last dimension

Viewed 139

To identify unique sequences, I need to use tensorflow functions to reduce a 2D int tensor to a 1D int tensor by concatenating the numbers in the last dimension.

For example,

[[1, 0], [2, 1], [1, 3], [2, 0], [0, 1]]

should become

[10, 21, 13, 20, 1]

What I have so far is

def reduce_concat(input):
  def join(x):
    dec = tf.range(0, x.shape[-1], 1)
    dec = tf.map_fn(lambda x: tf.math.pow(10, x), dec)
    return tf.math.reduce_sum(x * dec)
  return tf.map_fn(join, input)

This almost works, but it ignores zeroes and is not very elegant.

I would be grateful if anyone could provide an elegant solution for this problem - thanks.

2 Answers

You can try the following:

def reduce_concat(input):
  dec = 10**tf.range(input.shape[-1]-1, -1, -1)
  return tf.reduce_sum(input * dec, axis=-1)

Result for your input:

[10, 21, 13, 20,  1]

The trick I used is to create a factor matric with the same shape as your input which contains the power of 10 to use. Then, you do an element wise multiplication and finally apply the reduce sum.

Here's the code :

import tensorflow as tf

vector = tf.constant([[1, 0], [2, 1], [1, 3], [2, 0], [0, 1]])
factor = tf.constant([list(reversed([10**power for power in 
range(vector.shape[1])]))])
output = tf.reduce_sum(tf.multiply(vector, factor), axis=1)
Related