如何使用单独的 numpy 数组将 numpy int 转换为 float ?

Arl*_*len 5 python arrays numpy out-of-memory

我有大量的 numpy 内存错误问题数据,我尝试使用切片来处理它,如下所示 如果切片不能解决内存错误,如何合并两个大型 numpy 数组?

切片适用于 numpy.multiply,但似乎无法通过切片将 numpy int 转换为 float。以下是示例:

images = numpy.array([1,2,3,4,5,6,7,8,9,10])
images[0:5] = images[0:5].astype(numpy.float32)
print type(images[0])
images = images.astype(numpy.float32)
print type(images[0])

<type 'numpy.int32'>
<type 'numpy.float32'>
Run Code Online (Sandbox Code Playgroud)

一旦我使用 images.astype(numpy.float32),我就会出现内存错误(dtype 相同)。目标内存太小,我可能很难使用稀疏矩阵。

感谢您的任何建议...!

Jul*_*ien 13

您不能dtype仅修改切片的 。当你这样做时

images[0:5] = images[0:5].astype(numpy.float32)
Run Code Online (Sandbox Code Playgroud)

images[0:5].astype(numpy.float32)创建float切片的副本,但结果会转换回int分配回images切片时的状态,因为imagesis of dtype int

您可以做的是创建切片的临时副本并将其转换为浮点数:

copied_slice = images[0:5].astype(numpy.float32)
Run Code Online (Sandbox Code Playgroud)

对数据的这一较小部分进行所需的所有计算,保存所需的任何结果,然后继续到下一个(复制和转换的)切片。