将整数转换为二进制位的pytorch张量

将整数转换为二进制位的pytorch张量,pytorch,Pytorch,给定一个数字和一个编码长度,如何将该数字转换为其作为张量的二进制表示形式 例如,给定数字6和宽度8,如何获得张量: (0, 0, 0, 0, 0, 1, 1, 0) 示例: >>> 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)) tens

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

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

(0, 0, 0, 0, 0, 1, 1, 0)
示例:

>>> 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)
示例:

>>> 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)

如果输入为无符号字节,输出宽度为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)

请注意,仅当输入为无符号字节且输出宽度为8位时,才使用np.uint8。

>>> 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)
请注意,仅使用np.uint8进行操作

def二进制文件,位: 掩码=2**torch.arangebits.tox.device,x.dtype 返回x.unsqueze-1.bit_和mask.ne0.byte 如果你想颠倒比特的顺序,就用火炬来代替,用arangebits-1,-1,-1

def二进制文件,位: 掩码=2**torch.arangebits.tox.device,x.dtype 返回x.unsqueze-1.bit_和mask.ne0.byte 如果你想颠倒位的顺序,就把它和torch一起使用。arangebits-1,-1,-1是个不错的选择。顺便说一句,要将Tiana的2个基数结果转换回10个基数,可以这样做:

进口火炬 将numpy作为np导入 def dec2binx,位: 掩码=2**torch.arangebits.tox.device,x.dtype 掩码=2**torch.arangebits-1,-1,-1.tox.device,x.dtype 返回x.unsqueze-1.bit_和mask.ne0.float def bin2decb,位: 掩码=2**torch.arangebits-1,-1,-1.tob.device,b.dtype 返回火炬。总任务*b,-1 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': NUM_位=7 d=火炬。随机数0,16,3,6 b=dec2bind,NUM_位 打印 版图 打印B.形状 总位的printnum:{}.formatnp.prodb.shape d_rec=bin2decb,NUM_位 打印记录 printabsd-d_rec.max应为0。 这是个好主意。顺便说一句,要将Tiana的2个基数结果转换回10个基数,可以这样做:

进口火炬 将numpy作为np导入 def dec2binx,位: 掩码=2**torch.arangebits.tox.device,x.dtype 掩码=2**torch.arangebits-1,-1,-1.tox.device,x.dtype 返回x.unsqueze-1.bit_和mask.ne0.float def bin2decb,位: 掩码=2**torch.arangebits-1,-1,-1.tob.device,b.dtype 返回火炬。总任务*b,-1 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': NUM_位=7 d=火炬。随机数0,16,3,6 b=dec2bind,NUM_位 打印 版图 打印B.形状 总位的printnum:{}.formatnp.prodb.shape d_rec=bin2decb,NUM_位 打印记录 printabsd-d_rec.max应为0。
相关的:相关的:这是如此优雅这是如此优雅为什么。浮动和否。字节根据参考答案?是的,在一般情况下,你可以在这里使用。字节。我使用了.float,因为我需要将结果传递给第三方评估程序,该程序需要浮点格式的位。不管怎样,所有的数字仍然是0或1。为什么是.float而不是.byte,根据参考答案?是的,在一般情况下,您可以在这里使用.byte。我使用了.float,因为我需要将结果传递给第三方评估程序,该程序需要浮点格式的位。无论如何,所有的数字仍然是0或1。