I wish to convert a tensor of binary numbers, for example, [0,1,0,1,1] to an integer in tensorflow. In my case, the tensor is quite large, with a length of approximately 80 elements. Is there a way to do this efficiently?
-
What kind of integer are you hoping to get? 160000 bits is a bit more than will fit in a 64-bit integer. Is there some sort of batching going on?Allen Lavoie– Allen Lavoie2017-02-10 01:32:41 +00:00Commented Feb 10, 2017 at 1:32
-
@AllenLavoie Sorry. It is 80 bits in total.Ray.R.Chua– Ray.R.Chua2017-02-10 08:35:13 +00:00Commented Feb 10, 2017 at 8:35
Add a comment
|
1 Answer
This will almost certainly lead to overflows with length-80 binary Tensors, but the basic strategy would be to do a vectorized multiplication with a Tensor which has powers of two:
import tensorflow as tf
binary_string = tf.constant([1, 0, 0, 1, 1])
result = tf.reduce_sum(
tf.cast(tf.reverse(tensor=binary_string, axis=[0]), dtype=tf.int64)
* 2 ** tf.range(tf.cast(tf.size(binary_string), dtype=tf.int64)))
with tf.Session():
print(result.eval())
Prints:
19