一些以前的信息
我有以下方法,它从磁盘加载两个数据集,然后将它们组合并返回组合的数据集。
def _get_data(self, data_set_name):
training_data = DataSet.from_file('path_to_data_file','path_to_label_file')
test_data = DataSet.from_file('path_to_data_file','path_to_label_file')
return training_data.concat(test_data) # doubles the memory consumption
DataSet
如下所示:
class DataSet:
def __init__(self, data, labels):
self.x = data # float64 array of shape (x,y)
self.y = labels # int array of shape (x,)
def concat(self, other_data_set):
new_x = numpy.vstack((self.x, other_data_set.x))
new_y = numpy.concatenate((self.y, other_data_set.y))
return DataSet(new_x, new_y)
我的问题
调用DataSet.concat
时,内存会加倍。这首先是预期的行为,因为 numpy 会创建两个包含组合数据的新数组。但是离开_get_data
方法后,变量training_data
和test_data
不应再引用较小的数据集。所以我预计内存消耗应该会再次减少。这不会发生。因为我想知道,我尝试手动调用垃圾回收,但没有任何成功。
data_set = _get_data('someName')
gc.collect(0)
gc.collect(1)
gc.collect(2)
# Still same memory consumption
谁能向我解释一下这里发生了什么?我做错了什么吗?
更新
我通过以下代码测量内存:
pid = os.getpid()
py = psutil.Process(pid)
memoryUse = py.memory_info()[0] / 2. ** 30 # memory use in GB
print('memory use:', memoryUse)
看起来此行为是由于调试而发生的。当我在_get_data
之前放置断点时,在走出_get_data
并继续前进后,内存没有释放。当我在调用_get_data
内存后放置第一个断点时,正确释放了内存。我不知道调试会对内存管理产生如此大的影响。