gpt4 book ai didi

python - numpy 二进制符号快速生成

转载 作者:太空狗 更新时间:2023-10-30 02:56:43 25 4
gpt4 key购买 nike

假设,我有一个包含 n 元素的 numpy 向量,所以我想将此向量中的数字编码为二进制符号,因此生成的形状将是 (n,m) 其中 mlog2(maxnumber) 例如:

x = numpy.array([32,5,67])

因为我拥有的最大数量是 67,所以我需要 numpy.ceil(numpy.log2(67)) == 7 位来编码这个向量,所以形状结果将是 (3,7)

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

问题出现是因为我没有快速的方法从
移动二进制符号函数 numpy.binary_repr 到 numpy 数组。现在我必须遍历结果,并分别放置每一位:

brepr = numpy.binary_repr(x[i],width=7)
j = 0
for bin in brepr:
X[i][j] = bin
j += 1

这种方式非常耗时且愚蠢,如何使其高效?

最佳答案

这是使用 np.unpackbits 和广播的一种方式:

>>> max_size = np.ceil(np.log2(x.max())).astype(int)
>>> np.unpackbits(x[:,None].astype(np.uint8), axis=1)[:,-max_size:]
array([[0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 1],
[1, 0, 0, 0, 0, 1, 1]], dtype=uint8)

关于python - numpy 二进制符号快速生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39580110/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com