【问题标题】:How to convert numpy int to float with separate numpy array?如何使用单独的 numpy 数组将 numpy int 转换为浮点数?
【发布时间】:2017-10-26 07:04:19
【问题描述】:

我有大量的 numpy 内存错误问题, 我尝试使用切片来处理它,如下所示 How to merge two large numpy arrays if slicing doesn't resolve memory error?

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

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

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

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

【问题讨论】:

  • numpy 声明numpy.array 的每个元素都属于同一类型,因此您不能仅更改数组一部分的类型。你可以创建另一个数组images_5_float = images[0:5].astype(numpy.float32)
  • 好的...知道了...我猜已经...,只是希望找到另一种方法,谢谢您的回复!
  • 但如果您可以逐个部分、逐个切片地执行下一个操作,则可以使用这个新的部分数组

标签: python arrays numpy out-of-memory


【解决方案1】:

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

images[0:5] = images[0:5].astype(numpy.float32)

images[0:5].astype(numpy.float32) 创建切片的float 副本,但当分配回images 切片时,结果将转换回int,因为images 属于dtype int

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

copied_slice = images[0:5].astype(numpy.float32)

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

【讨论】:

  • 为什么它把这个AttributeError: 'int' object has no attribute 'astype'@Julien扔给我?
  • @andreagalle 也许你切片太多了,正在拉出一个 int 而不是一个 numpy 数组
猜你喜欢
  • 2021-11-13
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多