【问题标题】:Finding mean and standard deviation across image channels PyTorch跨图像通道 PyTorch 查找均值和标准差
【发布时间】:2020-05-22 20:52:12
【问题描述】:

假设我有一批尺寸为 (B x C x W x H) 的张量形式的图像,其中 B 是批量大小,C 是图像中的通道数,W 和 H 是宽度和图像的高度。我希望使用transforms.Normalize() 函数根据数据集跨C图像通道的均值和标准差对我的图像进行归一化,这意味着我想要一个形式为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 中的工作原理之后,我知道为什么我的方法不起作用了;但是,我仍然不知道如何获得每个通道的均值和标准差。

【问题讨论】:

    标签: python deep-learning pytorch mean standard-deviation


    【解决方案1】:

    请注意,添加的是方差,而不是标准差。详细解释看这里: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)
    

    【讨论】:

      【解决方案2】:

      您只需要以正确的方式重新排列批张量:从 [B, C, W, H][B, C, W * H] by:

      batch = batch.view(batch.size(0), batch.size(1), -1)
      

      这是关于随机数据的完整使用示例:

      代码:

      import torch
      from torch.utils.data import TensorDataset, DataLoader
      
      data = torch.randn(64, 3, 28, 28)
      labels = torch.zeros(64, 1)
      dataset = TensorDataset(data, labels)
      loader = DataLoader(dataset, batch_size=8)
      
      nimages = 0
      mean = 0.
      std = 0.
      for batch, _ in loader:
          # 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) 
          std += batch.std(2).sum(0)
      
      # Final step
      mean /= nimages
      std /= nimages
      
      print(mean)
      print(std)
      

      输出:

      tensor([-0.0029, -0.0022, -0.0036])
      tensor([0.9942, 0.9939, 0.9923])
      

      【讨论】:

      • 这是不正确的原因是因为您已经按图像数量平均了,实际上它应该在像素上平均。
      猜你喜欢
      • 2022-01-19
      • 2017-04-28
      • 2014-03-15
      • 1970-01-01
      • 2014-04-27
      • 2016-02-07
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      相关资源
      最近更新 更多