Salvador Dali
Salvador Dali

Reputation: 222751

Unpackbits only in TF

I am looking for a way to unpack bits in TF in the same way I can do this with np.unpackbits. So revert the operation like:

import numpy as np
import tensorflow as tf
original = np.random.choice(a=[1, 0], size=(100))
data     = np.packbits(original.astype(np.bool), axis=None)

X = tf.constant(data)

Assuming I have access only to X, how to convert it to original in TF. Of course I can use numpy, but this will move data from TF to python and then back to TF.


Few thoughts I had in mind (have not implemented any of them):

  1. use tf.map_fn
  2. use tf.contrib.lookup

For both of them the ideas is to map each number to a vector, concat all the vectors, reshape, remove unneeded elements.

Both of the approaches seems more complicated that they should be. Does anyone has an efficient way (in terms of speed) how to achieve numpy's unpackbits in tensorflow?

Upvotes: 4

Views: 922

Answers (1)

P-Gn
P-Gn

Reputation: 24621

Perhaps something like this:

import tensorflow as tf

x = tf.constant((1, 2, 7, 0, 255), dtype=tf.uint8)

b = tf.constant((128, 64, 32, 16, 8, 4, 2, 1), dtype=tf.uint8)
unpacked = tf.reshape(tf.mod(tf.to_int32(x[:,None] // b), 2), [-1])

unpacked is in int32 due to tf.mod not accepting bytes, you may want to cast it to uint8 again.

Tensorflow 1.3 will have bitwise operations, so this last line could be replaced with

unpacked = tf.reshape(tf.bitwise.bitwise_and(x, b), [-1])

which will hopefully be faster (and the result in uint8).

Upvotes: 4

Related Questions