gpt4 book ai didi

python - NumPy:3 字节、6 字节类型(又名 uint24、uint48)

转载 作者:太空狗 更新时间:2023-10-30 00:57:03 32 4
gpt4 key购买 nike

NumPy 似乎缺乏对 3 字节和 6 字节类型的内置支持,也就是 uint24uint48。我有一个使用这些类型的大数据集,想将它提供给 numpy。我目前所做的(对于 uint24):

import numpy as np
dt = np.dtype([('head', '<u2'), ('data', '<u2', (3,))])
# I would like to be able to write
# dt = np.dtype([('head', '<u2'), ('data', '<u3', (2,))])
# dt = np.dtype([('head', '<u2'), ('data', '<u6')])
a = np.memmap("filename", mode='r', dtype=dt)
# convert 3 x 2byte data to 2 x 3byte
# w1 is LSB, w3 is MSB
w1, w2, w3 = a['data'].swapaxes(0,1)
a2 = np.ndarray((2,a.size), dtype='u4')
# 3 LSB
a2[0] = w2 % 256
a2[0] <<= 16
a2[0] += w1
# 3 MSB
a2[1] = w3
a2[1] <<=8
a2[1] += w2 >> 8
# now a2 contains "uint24" matrix

虽然它适用于 100MB 的输入,但它看起来效率很低(想想 100 GB 的数据)。有没有更有效的方法?例如,创建一种特殊类型的只读 View 来屏蔽部分数据会很有用(类似于“具有两个 MSB 且始终为零的 uint64”类型)。我只需要对数据进行只读访问。

最佳答案

我不相信有一种方法可以满足您的要求(它需要未对齐的访问,这在某些架构上效率非常低)。我的解决方案来自 Reading and storing arbitrary byte length integers from a file将数据传输到进程内数组可能会更有效:

a = np.memmap("filename", mode='r', dtype=np.dtype('>u1'))
e = np.zeros(a.size / 6, np.dtype('>u8'))
for i in range(3):
e.view(dtype='>u2')[i + 1::4] = a.view(dtype='>u2')[i::3]

您可以使用 strides 构造函数参数获得未对齐的访问:

e = np.ndarray((a.size - 2) // 6, np.dtype('<u8'), buf, strides=(6,))

然而,每个元素都将与下一个元素重叠,因此要实际使用它,您必须在访问时屏蔽掉高字节。

关于python - NumPy:3 字节、6 字节类型(又名 uint24、uint48),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11967339/

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