python - 查找图像 channel PyTorch 的平均值和标准差

标签 python deep-learning pytorch mean standard-deviation

假设我有一批尺寸为 (B x C x W x H) 张量形式的图像,其中 B 是批量大小,C 是图像中的 channel 数,W 和 H 是宽度和图像的高度。我希望使用 transforms.Normalize() 函数根据 C 图像 channel 中数据集的平均值和标准差对图像进行标准化,这意味着我想要一个 1 x C 形式的结果张量。有没有一种简单的方法可以做到这一点?

我尝试了 torch.view(C, -1).mean(1)torch.view(C, -1).std(1) 但我得到错误:

view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.

编辑

在研究了 view() 在 PyTorch 中的工作原理之后,我知道为什么我的方法不起作用;但是,我仍然不知道如何获得每个 channel 的平均值和标准差。

最佳答案

请注意,相加的是方差,而不是标准差。请参阅此处的详细说明:https://apcentral.collegeboard.org/courses/ap-statistics/classroom-resources/why-variances-add-and-why-it-matters

修改后的代码如下:

nimages = 0
mean = 0.0
var = 0.0
for i_batch, batch_target in enumerate(trainloader):
    batch = batch_target[0]
    # Rearrange batch to be the shape of [B, C, W * H]
    batch = batch.view(batch.size(0), batch.size(1), -1)
    # Update total number of images
    nimages += batch.size(0)
    # Compute mean and std here
    mean += batch.mean(2).sum(0) 
    var += batch.var(2).sum(0)

mean /= nimages
var /= nimages
std = torch.sqrt(var)

print(mean)
print(std)

关于python - 查找图像 channel PyTorch 的平均值和标准差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60101240/

相关文章:

python - 使用 matplotlib 或 PIL 将 3d numpy 数组绘制为 3d 图像

python - 如何解压pkl文件?

python - Pytorch 运行时错误 : expected scalar type Float but found Byte

python - Pytorch梯度还没有计算

python - 这个 .py 可以有多个短语吗?

python - sklearn FeatureHasher 并行化

python - Keras 密集层中的单位

python - 在没有安装 pytorch 的情况下使用 RNN 训练模型

c++ - PySide 中的自定义样式支持,如何将 QStyleOption 转换为它的子类?

tensorflow - 如何在使用 Keras 或 Tensorflow 训练深度神经网络期间添加更多数据