How to implement elements comparsion in tensor by Tensorflow?

In my custom loss function, I want to implement this specific computation:

Input:

tensor A: placeholder([None, 1])
tensor B: placeholder([None, 1])

And A, B has the same shape.

Output:

tensor res: placeholder([None, 1]).

For example:

tensor   A: [0, 0, 1, 2, 2, 2, 3,...]
tensor   B: [4, 9, 2, 3, 5, 9, 4,...]
tensor res: [4, 4, 2, 3, 3, 3, 4,...]

At first, res[0] = B[0], if A[i] == A[i-1], then res[i] = res[i-1]; else, res[i] = B[i]. So we get res=[4, 4, 2, 3, 3, 3, 4,...].

I'm really troubled in the question, and I'm not expected in tensorflow.Hope to answer, thx.

1 answer

  • answered 2018-01-17 08:20 layog

    I do not think that there is a direct way to deal with this in tensorflow. But, you can create your own operation or implement this in a crude way in tensorflow

    1. condition - Create an array with 1s at index which pass the condition and 0s at the rest. (Can be easily parallelized and in tensorflow use tf.while_loop)

    2. prefixedSum - Use prefix sum on condition to create this array. (No direct implementation, but this can help)

    3. reducedB - use the condition to create an array of selected elements choosing index from prefixedSum array. (can be implemented using tf.while_loop)

    4. ans - create the final array using the index from prefixedSum and looking up that index in reducedB. (Again can be implemented using tf.while_loop)