所以我试图在一系列大型阵列上进行以下计算,但我不断收到错误:
MemoryError
总共有9个grain_size数组2745乘2654(注意:我可以在这里使用一个浮点数而不是数组,因为它是每个单元格中相同数字的数组,这不会改变),9 g_pro数组2745乘2654和我在下面创建的9个数组。
所以我想我的问题是有办法解决这个问题吗?
# Create empty arrays to store the information
Fs1 = np.zeros_like(g_pro_1, dtype = float)
Fs2 = np.zeros_like(g_pro_1, dtype = float)
Fs3 = np.zeros_like(g_pro_1, dtype = float)
Fs4 = np.zeros_like(g_pro_1, dtype = float)
Fs5 = np.zeros_like(g_pro_1, dtype = float)
Fs6 = np.zeros_like(g_pro_1, dtype = float)
Fs7 = np.zeros_like(g_pro_1, dtype = float)
Fs8 = np.zeros_like(g_pro_1, dtype = float)
Fs9 = np.zeros_like(g_pro_1, dtype = float)
# Check where the condition is true
np.putmask(Fs1, np.logical_and(grain_size_1_array > 0.0000625, grain_size_1_array <= 0.002), g_pro_1)
np.putmask(Fs2, np.logical_and(grain_size_2_array > 0.0000625, grain_size_2_array <= 0.002), g_pro_2)
np.putmask(Fs3, np.logical_and(grain_size_3_array > 0.0000625, grain_size_3_array <= 0.002), g_pro_3)
np.putmask(Fs4, np.logical_and(grain_size_4_array > 0.0000625, grain_size_4_array <= 0.002), g_pro_4)
np.putmask(Fs5, np.logical_and(grain_size_5_array > 0.0000625, grain_size_5_array <= 0.002), g_pro_5)
np.putmask(Fs6, np.logical_and(grain_size_6_array > 0.0000625, grain_size_6_array <= 0.002), g_pro_6)
np.putmask(Fs7, np.logical_and(grain_size_7_array > 0.0000625, grain_size_7_array <= 0.002), g_pro_7)
np.putmask(Fs8, np.logical_and(grain_size_8_array > 0.0000625, grain_size_8_array <= 0.002), g_pro_8)
np.putmask(Fs9, np.logical_and(grain_size_9_array > 0.0000625, grain_size_9_array <= 0.002), g_pro_9)
Fs = Fs1 + Fs2 + Fs3 + Fs4 + Fs5 + Fs6 + Fs7 + Fs8 + Fs9
Fs[self.discharge == -9999] = -9999
现在适合我的代码是:
Fs = np.zeros_like(g_pro_1, dtype = float)
grain_array_list = [self.grain_size_1, self.grain_size_2, self.grain_size_3, self.grain_size_4, self.grain_size_5, self.grain_size_6, self.grain_size_7, self.grain_size_8, self.grain_size_9]
proportions_list = [g_pro_1, g_pro_2, g_pro_3, g_pro_4, g_pro_5, g_pro_6, g_pro_7, g_pro_8, g_pro_9]
for proportion, grain in izip(proportions_list, grain_array_list):
if grain > 0.0000625 and grain <= 0.002:
print grain
Fs = Fs + proportion
Fs[self.discharge == -9999] = -9999
答案 0 :(得分:1)
您的示例需要9*2745*2654*sizeof(float)
字节(即500 MiB)来存储grain_size
数组,并再次存储g_pro
数组。要运行logical_and
函数,必须存储带有比较结果的参数数组,再添加100个Mib。也许你最终真的会耗尽内存?
您可以尝试
Fs<n>
数组,而不是同时在内存中创建每个数组答案 1 :(得分:1)
每当您看到只有一个字符不同的代码行时,您应该使用循环。在您的情况下,您将保留未在内存中使用的数据。您的工作流程基本上是
grain_size_array
grain_size_array
Fs
)grain_size_array
就代码而言,您需要以下内容:
g_pro_1 = load() # however you get that
Fs = np.zeros_like(g_pro_1, dtype = float)
Fs_tmp = np.zeros_like(g_pro_1, dtype = float)
for i in range(10):
g_pro = load() # whatever
grain_size_array = load() # whatever
np.putmask(Fs_tmp, np.logical_and(grain_size_array > 0.0000625, grain_size_array <= 0.002), g_pro_1)
Fs += Fs_tmp