0

I've got a matrix that values are positive integers and want to find the bit representation unpacked into a tensor using numpy

e.g

[[1 , 2],
 [3 , 4]]

to

[[0 , 0],
 [0 , 1]], 

[[0 , 1],
 [1 , 0]],

[[1 , 0],
 [1 , 0]]
6
  • 2
    What is the logic with the binary tensor's values? Commented Sep 14, 2021 at 8:42
  • Actually I want to map a 2D array that its entries are decimal to binary tensor. In this case tensor is 3 - 2D arrays with binary entries Commented Sep 14, 2021 at 9:02
  • depth of tensor is depend on length of max entry , in this case 4 is max entry so 4 equals 100 then depth is 3 Commented Sep 14, 2021 at 9:04
  • 1
    Something like np.unpackbits(x[None,:], axis=0)[-3:] should do the job. Commented Sep 14, 2021 at 9:42
  • That's right I looked it but it doesn't support custom unit length. it just works with unit8 Commented Sep 14, 2021 at 9:44

1 Answer 1

1

This solution is limited to 2D arrays but works with elements larger than np.uint8 and calculates the necessary bit depth.

import numpy as np

M = np.array([[1,2],
              [3,4]])
bits = int(np.log2(M.max())) + 1

(np.where(
     M.reshape(-1,1) & 2**np.arange(bits)[::-1], 1, 0)
   .reshape(*M.shape, -1)
   .transpose(2,0,1))

Output

array([[[0, 0],
        [0, 1]],

       [[0, 1],
        [1, 0]],

       [[1, 0],
        [1, 0]]])

How this works

Construct a range with powers of 2

2**np.arange(bits)[::-1]

Broadcast this range with logical_and over the input elements

(M.reshape(-1,1) & 2**np.arange(bits)[::-1])

Output

array([[0, 0, 1],
       [0, 2, 0],
       [0, 2, 1],
       [4, 0, 0]])

Convert to 1,0 bool array with np.where

array([[0, 0, 1],   # 1 in binary
       [0, 1, 0],   # 2 in binary
       [0, 1, 1],   # 3 in binary
       [1, 0, 0]])  # 4 in binary

Shape to desired output.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks . That's really useful for me :D

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.