【问题标题】:How to reshape a big array (Memory Error)如何重塑一个大数组(内存错误)
【发布时间】:2017-02-26 04:52:11
【问题描述】:

我有一个非常大的 6D 数组 (225, 97, 225, 32, 32, 32)。我想将它重塑为像(225*97*225, 32, 32, 32) 这样的 4D 数组。我尝试在 ubuntu 14.04 中使用 python 2.7 和下面的代码,但我得到了内存错误。我该如何解决?谢谢

import numpy as np

#input_6D shape (225, 97, 225, 32, 32, 32)
input_4D= input_6D.reshape(input_6D.shape[0]*input_6D.shape[1]*input_6D.shape[2], input_6D[0],input_6D[1],input_6D[2])

错误是

input_4D= input_6D.reshape(input_6D.shape[0]*input_6D.shape[1]*input_6D.shape[2], input_6D[0],input_6D[1],input_6D[2]) 内存错误

这是我做的步骤。首先,我加载一个形状为256x128x256 的3D 输入。然后我使用下面的代码得到6D数组(225, 97, 225, 32, 32, 32),其中补丁形状为32, 32, 32

def patch_extract_3D(input,patch_shape):
    patches_6D = np.lib.stride_tricks.as_strided(input, ((input.shape[0] - patch_shape[0] + 1) // xstep, (input.shape[1] - patch_shape[1] + 1) // ystep,
                                                  (input.shape[2] - patch_shape[2] + 1) // zstep, patch_shape[0], patch_shape[1], patch_shape[2]),
                                                  (input.strides[0] * xstep, input.strides[1] * ystep,input.strides[2] * zstep, input.strides[0], input.strides[1],input.strides[2]))

【问题讨论】:

  • 拥有如此庞大的数据量,您可能必须先将其转储到磁盘(文件或数据库),然后再读取。
  • 你们有没有通过代码提供解决方案?抱歉,我没有完整了解您的解决方案
  • 您确定您正在运行问题中显示的相同命令吗?因为在我看来,使用该命令似乎不会达到 MemoryError 的程度。你应该得到类似“只有长度为 1 的数组可以转换为 Python 标量”之类的东西,因为你提供了作为参数来重塑像 input_6D[0] 这样的东西,它们不是数字,而是巨大的数组本身。
  • @user3051460:我的评论只是,嗯,评论,而不是答案。
  • as_strided 创建一个视图。但几乎任何对它的操作,包括这种重塑,都会复制。

标签: python python-2.7 numpy


【解决方案1】:

跨步表达式适用于xstep,ystep,zstep=1,1,1

如果输入是np.zeros((256,128,256),np.int8),步幅为(32768, 256, 1),则输出将具有给定的形状和步幅(32768, 256, 1, 32768, 256, 1)

我计算出重构数组的步幅必须是(1426325504, 58982400, 262144, 1024, 32, 1)

没有副本就无法获得它。 as_strided 生成原始视图。但是重塑会使副本大 200 倍。

更多关于在reshaping a view of a n-dimensional array without using reshapeas_strided 创建副本

这种跨步视图可能适用于缩减操作,例如在最后 3 个维度上取平均值或求和。先这样做,然后尝试重塑。 as_strided 很棘手,在 3 维上完成时更是如此。

How to recover 3D image from its patches in Python? - 你之前的问题涉及这个跨步代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多