Skip to main content
 首页 » 编程设计

python之没有 View 的切片(或 : shuffling multiple arrays)

2025年04月02日17txw1958

我有两个不同的 numpy 数组,我想以异步方式打乱它们。

当前解决方案取自https://www.tensorflow.org/versions/r0.8/tutorials/mnist/pros/index.html并进行如下操作:

perm = np.arange(self.no_images_train) 
np.random.shuffle(perm) 
self.images_train = self.images_train[perm] 
self.labels_train = self.labels_train[perm] 

问题是每次我这样做都会使内存翻倍。不知何故,旧数组没有被删除,我猜可能是因为切片运算符创建了 View 。出于纯粹的绝望,我尝试了以下更改:

perm = np.arange(self.no_images_train) 
np.random.shuffle(perm) 
 
n_images_train = self.images_train[perm] 
n_labels_train = self.labels_train[perm]             
 
del self.images_train 
del self.labels_train 
gc.collect() 
 
self.images_train = n_images_train 
self.labels_train = n_labels_train 

还是一样,内存泄漏,几次操作后内存不足。

顺便说一句,这两个数组的等级分别为 100000,224,244,1 和 100000,1。

我知道这已在此处处理(Better way to shuffle two numpy arrays in unison),但答案对我没有帮助,因为提供的解决方案需要再次切片。

感谢您的帮助。

请您参考如下方法:

以同步方式就地置换两个大数组的一种方法是保存随机数生成器的状态,然后打乱第一个数组。然后恢复状态并对第二个数组进行洗牌。

例如,这是我的两个数组:

In [48]: a 
Out[48]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15]) 
 
In [49]: b 
Out[49]: array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15]) 

保存随机数生成器当前的内部状态:

In [50]: state = np.random.get_state() 

就地随机播放a:

In [51]: np.random.shuffle(a) 

恢复随机数生成器的内部状态:

In [52]: np.random.set_state(state) 

就地随机播放 b:

In [53]: np.random.shuffle(b) 

检查排列是否相同:

In [54]: a 
Out[54]: array([13, 12, 11, 15, 10,  5,  1,  6, 14,  3,  9,  7,  0,  8,  4,  2]) 
 
In [55]: b 
Out[55]: array([13, 12, 11, 15, 10,  5,  1,  6, 14,  3,  9,  7,  0,  8,  4,  2]) 

对于您的代码,这看起来像:

state = np.random.get_state() 
np.random.shuffle(self.images_train) 
np.random.set_state(state) 
np.random.shuffle(self.labels_train)