2

I have an input of numbers, ranging on [0, 15], which I want to feed to my network as a binary code with 4 bits. For example, the input [0,1,4,7] should become [[0,0,0,0],[0,0,0,1],[0,1,0,0],[0,1,1,1]].

The tf.one_hot operation is close, but not exactly what I want. Is there any elegant way, either with Numpy or TensorFlow, to convert my input into its binary encoding, in order to feed it into my network?

My best solution was to use np.binary_repr for each value, and convert it from a string into an array of integers, but I feel this is not a good solution (converting twice, first into string, then into array).

1 Answer 1

1

Something like this:

np.unpackbits(np.array([[0,1,4,7]],np.uint8)).reshape(-1,4)[1::2,:]

I'm sure it can be refined but at least it's vectorized

Or this probably makes more sense:

np.unpackbits(np.array([[0,1,4,7]],np.uint8)).reshape(-1,8)[:,4:]
Sign up to request clarification or add additional context in comments.

1 Comment

The second option seems much cleaner. Good job

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.