给定一个数字和一个编码长度,如何将数字转换为张量的二进制表示?
例如,给定 number6
和 width 8
,我怎样才能获得张量:
(0, 0, 0, 0, 0, 1, 1, 0)
Run Code Online (Sandbox Code Playgroud)
蒂安娜的回答很好。顺便说一句,要将 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.
Run Code Online (Sandbox Code Playgroud)
def binary(x, bits):
mask = 2**torch.arange(bits).to(x.device, x.dtype)
return x.unsqueeze(-1).bitwise_and(mask).ne(0).byte()
Run Code Online (Sandbox Code Playgroud)
如果您想反转位的顺序,请改用它torch.arange(bits-1,-1,-1)
。
归档时间: |
|
查看次数: |
3402 次 |
最近记录: |