Skip to main content
 首页 » 编程设计

python之计算批处理的均值和标准差 [Python/Numpy]

2025年05月04日22txw1958

希望高效地计算批处理中每个 channel 的平均值和标准差。


详细信息:

  • 批量大小:128
  • 图片:32x32
  • 3 channel (RGB)

因此每个批处理的大小为 [128, 32, 32, 3]。

有很多批处理(天真的方法在所有批处理上需要大约 4 分钟)。

我想输出 2 个数组:(meanR, meanG, meanB) 和 (stdR, stdG, stdB)


(此外,如果有一种有效的方法可以在计算后对批处理执行算术运算,那将会很有帮助。例如,从每个图像中减去整个数据集的平均值)

请您参考如下方法:

如果我没有理解错,并且您想计算所有 图像的均值和标准值:

演示:(2,2,3) 形状的 2 个图像(为简单起见):

In [189]: a 
Out[189]: 
array([[[[ 1,  2,  3], 
         [ 4,  5,  6]], 
 
        [[ 7,  8,  9], 
         [10, 11, 12]]], 
 
 
       [[[13, 14, 15], 
         [16, 17, 18]], 
 
        [[19, 20, 21], 
         [22, 23, 24]]]]) 
 
In [190]: a.shape 
Out[190]: (2, 2, 2, 3) 
 
In [191]: np.mean(a, axis=(0,1,2)) 
Out[191]: array([ 11.5,  12.5,  13.5]) 
 
In [192]: np.einsum('ijkl->l', a)/float(np.prod(a.shape[:3])) 
Out[192]: array([ 11.5,  12.5,  13.5]) 

速度测量:

In [202]: a = np.random.randint(255, size=(128,32,32,3)) 
 
In [203]: %timeit np.mean(a, axis=(0,1,2)) 
9.48 ms ± 822 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) 
 
In [204]: %timeit np.einsum('ijkl->l', a)/float(np.prod(a.shape[:3])) 
1.82 ms ± 22.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)