ZFTurbo
ZFTurbo

Reputation: 3732

Bitwise operation on single matrix in tensorflow 2

Let's say I have a matrix

M = np.array([
    [0, 1, 0, 0, 0],
    [1, 0, 1, 1, 1],
    [1, 1, 1, 1, 1],
    [0, 1, 1, 0, 1],
], dtype=np.int32)

And I want to make bitwise operation (bitwise_and for example) for all rows.

In numpy I can do it like that:

res = np.bitwise_and.reduce(M, axis=1)
print(res)

How can I do the same in tensorflow? Currently I do it like that:

tensor = tf.Variable(M)
res = tensor[:, 0]
for i in range(1, M.shape[1]):
    res = tf.bitwise.bitwise_and(res, tensor[:, i])
print(res.numpy())

I want to avoid the cycle.

Upvotes: 1

Views: 311

Answers (1)

javidcf
javidcf

Reputation: 59731

You can do that with reduction operations like tf.reduce_all:

import tensorflow as tf

tensor = tf.constant([[True, False, True], [False, True, False], [True, True, True]])
res = tf.reduce_all(tensor, axis=1)
print(res.numpy())
# [False False  True]

EDIT: If you want specifically the bitwise operation (i.e. your input is not binary), then I don't think there is a reduction operation for that, but you can do something similar with tf.scan (although it probably won't be so fast):

import tensorflow as tf

tensor = tf.constant([
    [0, 1, 2],
    [3, 6, 7],
], dtype=tf.int32)
# Put reduction dimension first
tensor_t = tf.transpose(tensor)
# Compute cumulative bitwise and
res_cum = tf.scan(tf.bitwise.bitwise_and, tensor_t)
# The last result is the total reduction
res = res_cum[-1]
print(res.numpy())
# [0 2]

Upvotes: 1

Related Questions