【问题标题】:Convert integer to pytorch tensor of binary bits将整数转换为二进制位的 pytorch 张量
【发布时间】:2020-08-28 20:05:01
【问题描述】:

给定一个数字和一个编码长度,如何将数字转换为张量的二进制表示形式?

例如,给定数字6 和宽度8,我如何获得张量:

(0, 0, 0, 0, 0, 1, 1, 0)

【问题讨论】:

标签: pytorch


【解决方案1】:

def binary(x, bits):
    mask = 2**torch.arange(bits).to(x.device, x.dtype)
    return x.unsqueeze(-1).bitwise_and(mask).ne(0).byte()

如果您想颠倒位顺序,请改用torch.arange(bits-1,-1,-1)

【讨论】:

  • 这太优雅了
【解决方案2】:

Tiana's answer 是一个很好的。顺便说一句,要将 Tiana 的 2 基结果转换回 10 基数,可以这样做:

import torch
import numpy as np


def dec2bin(x, bits):
    # mask = 2 ** torch.arange(bits).to(x.device, x.dtype)
    mask = 2 ** torch.arange(bits - 1, -1, -1).to(x.device, x.dtype)
    return x.unsqueeze(-1).bitwise_and(mask).ne(0).float()


def bin2dec(b, bits):
    mask = 2 ** torch.arange(bits - 1, -1, -1).to(b.device, b.dtype)
    return torch.sum(mask * b, -1)


if __name__ == '__main__':
    NUM_BITS = 7
    d = torch.randint(0, 16, (3, 6))
    b = dec2bin(d, NUM_BITS)
    # print(d)
    # print(b)
    # print(b.shape)
    # print("num of total bits: {}".format(np.prod(b.shape)))

    d_rec = bin2dec(b, NUM_BITS)

    # print(d_rec)
    print(abs(d - d_rec).max())  # should be 0.

【讨论】:

  • 为什么按照参考答案.float() 而不是.byte()
  • 是的,一般情况下你可以在这里使用.byte()。我使用了.float(),因为我需要将结果传递给第三方评估程序,该程序需要float 格式的位。无论如何,所有数字仍然是01
【解决方案3】:

如果输入为无符号字节,输出宽度为8位:

>>> binary = np.unpackbits(np.array([0xaa, 0xf0], dtype=np.uint8))
>>> print(torch.tensor(binary))
tensor([1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0], dtype=torch.uint8)

请注意,unpackbits()np.uint8 一起使用。

【讨论】:

    【解决方案4】:
    def decimal_to_binary_tensor(value, width=0):
        string = format(value, '0{}b'.format(width))
        binary = [0 if c == '0' else 1 for c in string]
        return torch.tensor(binary, dtype=torch.uint8)
    

    例子:

    >>> print(decimal_to_binary_tensor(6, width=8))
    tensor([0, 0, 0, 0, 0, 1, 1, 0], dtype=torch.uint8)
    
    >>> print(decimal_to_binary_tensor(6))
    tensor([1, 1, 0], dtype=torch.uint8)
    

    【讨论】:

      猜你喜欢
      • 2018-06-28
      • 2019-05-02
      • 2022-10-17
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 2020-08-05
      • 2019-07-29
      相关资源
      最近更新 更多