【问题标题】:operations on arrays in python from memory perspective从内存的角度对python中的数组进行操作
【发布时间】:2020-04-24 04:17:09
【问题描述】:

我正在尝试了解以下操作中的内存分配:

x_batch,images_path,ImageValidStatus = tf_resize_images(path_list, img_type=col_mode, im_size=IMAGE_SIZE)
x_batch=x_batch/255;
x_batch = 1.0-x_batch  
x_batch = x_batch.reshape(x_batch.shape[0],IMAGE_SIZE[0]*IMAGE_SIZE[1]*IMAGE_SIZE[2])

我感兴趣的是x_batch,这是一个多维numpy数组(100x64x64x3) 其中 100 是图像的数量,64x64x3 是图像的尺寸。

在某个时间点内存中图像的最大副本数是多少。 换句话说,从内存的角度来看,(x_batch/255)(1-x_batch)x_batch.reshape 的操作究竟是如何发生的。

我主要关心的是在某些情况下我试图同时处理 500K 图像,如果我将在内存中制作这些图像的多个副本,那么将很难将所有内容都放入内存中。

【问题讨论】:

  • 肯定会出现内存错误。每个= 都会产生一个临时缓冲区——除了重塑。

标签: python numpy numpy-ndarray


【解决方案1】:

我在您的代码中看到“tf”,所以我不确定您问的是张量还是数组。假设您正在询问数组。通常,数组被写入内存一次,然后被操作。例如,

import numpy as np
data = np.empty((1000,30,30,5))  #This took up 1000*30*30*5*dtype_size bytes (plus epsilon). 
data.reshape((1000,30,150))      #Does nothing but update how numpy accesses the array.
data += 1                        #Adds one to all the entries in the array. 
data = 1-data                    #Overwrites the array with the data of 1-data.
x    = data + 1                  #Re-allocates and copies the whole memory. 

只要不更改数组大小(重新分配内存),numpy 对数据的操作就会非常快速有效。不如 tensorflow,但非常非常快。就地添加,功能,操作,都在不使用更多内存的情况下完成。诸如附加到数组之类的事情可能会导致问题并使 python 在内存中重写数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    相关资源
    最近更新 更多