【问题标题】:Binary matrix to integer二进制矩阵到整数
【发布时间】:2015-03-30 09:07:58
【问题描述】:

我有一个二进制 MxN 矩阵,如下所示:

matrix([[0, 0, 0, ..., 0, 0, 0],
    [0, 1, 0, ..., 0, 0, 0],
    [0, 0, 1, ..., 0, 0, 0],
    ..., 
    [0, 0, 0, ..., 1, 0, 0],
    [0, 0, 0, ..., 0, 0, 0],
    [0, 0, 0, ..., 0, 0, 1]])

如何将此矩阵逐行转换为整数表示?目标是得到一个 Mx1 矩阵。每行包含前一个二进制行的整数表示。

【问题讨论】:

标签: numpy matrix representation


【解决方案1】:

另一种方法是使用 numpy 中的 packbits。然而,为此,numpy 将用零填充列,直到它们变成字节形状 (length % 8)。为了避免numpy被0填充,我们可以在开头添加零(不改变数组的二进制值)。

使用来自@Oliver W 的数据。

>>> import numpy as np
>>> b = np.random.random_integers(0,1,(3,5))
>>> b
array([[0, 1, 1, 1, 0],
       [1, 0, 1, 0, 1],
       [0, 1, 0, 0, 1]])
# Fill the begining with zeros to form bytes
>>> diff = 8 - b.shape[1] % 8
>>> if diff > 0: b = np.c_[np.zeros((b.shape[0], diff), int), b]
>>> b
array([[0, 0, 0, 0, 1, 1, 1, 0],
       [0, 0, 0, 1, 0, 1, 0, 1],
       [0, 0, 0, 0, 1, 0, 0, 1]])
# Get the integer number
>>> p = np.packbits(b, axis=1)
>>> p
array([[14],
       [21],
       [ 9]], dtype=uint8)

【讨论】:

  • 有效 (+1),但请注意:它仅适用于 Mx1。
  • Ops,谢谢@Oliver W.,我不知道。我猜如果列具有某种结构(即表示 8、16、32、64 或 128 位整数),可以通过添加 p.view('u4') 来修复(对于 32 位整数,其他类似)。它将为列返回一个新视图
【解决方案2】:

您可以将行的每个元素与其对应的乘法因子 2**exponent 相乘,其中指数取决于行中数字的位置(顺便说一句,这适用于任何位置数字系统,例如 base-60 和十六进制):

>>> import numpy as np
>>> 
>>> b = np.random.random_integers(0,1,(3,5))  # example array
>>> b
array([[0, 1, 1, 1, 0],
       [1, 0, 1, 0, 1],
       [0, 1, 0, 0, 1]])
>>> c = 2**np.arange(b.shape[1])[::-1] # reverse order: assumes the last column corresponds with the decimal number 1
>>> b.dot(c) # matrix multiplication
array([14, 21,  9])

如果你有 numpy 的矩阵类的实例,结果相同。

【讨论】:

    【解决方案3】:

    您可以将每一行的所有 0 和 1 作为字符串连接起来,从那里很容易获得整数表示。我必须将 matrix 转换为 array 才能使其正常工作,但也许有一个直接的解决方案:

    import numpy as np
    A = np.matrix([[0, 1, 1, 1, 0],
                   [1, 0, 1, 0, 1],
                   [0, 1, 0, 0, 1]])
    
    B = np.asarray(A)
    #join all 0/1s together as string and convert to integer
    C = np.matrix([int(''.join(str(x) for x in column),2) for column in B]).reshape((B.shape[0],1))
    
    print C
    >>>
    [[14]
     [21]
     [ 9]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2017-10-11
      • 1970-01-01
      • 2021-09-09
      相关资源
      最近更新 更多