【问题标题】:Is there a way to retrieve the specific parameters used in a random torchvision transform?有没有办法检索随机 torchvision 变换中使用的特定参数?
【发布时间】:2021-04-30 12:31:20
【问题描述】:

我可以在训练期间通过应用随机变换(旋转/平移/重新缩放)来扩充我的数据,但我不知道选择的值。

我需要知道应用了哪些值。我可以手动设置这些值,但是我失去了火炬视觉变换提供的很多好处。

有没有一种简单的方法可以让这些值在训练期间以合理的方式应用?

这是一个例子。我希望能够打印出每个图像的旋转角度、平移/重新缩放:

import numpy as np
import matplotlib.pyplot as plt
from torchvision import transforms


RandAffine = transforms.RandomAffine(degrees=0, translate=(0.1, 0.1), scale=(0.8, 1.2))

rotate = transforms.RandomRotation(degrees=45)
shift = RandAffine
composed = transforms.Compose([rotate,
                               shift])

# Apply each of the above transforms on sample.
fig = plt.figure()
sample = np.zeros((28,28))
sample[5:15,7:20] = 255
sample = transforms.ToPILImage()(sample.astype(np.uint8))
title = ['None', 'Rot','Aff','Comp']
for i, tsfrm in enumerate([None,rotate, shift, composed]):
    if tsfrm:
        t_sample = tsfrm(sample)
    else:
        t_sample = sample
    ax = plt.subplot(1, 5, i + 2)
    plt.tight_layout()
    ax.set_title(title[i])
    ax.imshow(np.reshape(np.array(list(t_sample.getdata())), (-1,28)), cmap='gray')    

plt.show()

【问题讨论】:

    标签: python pytorch affinetransform data-augmentation torchvision


    【解决方案1】:

    恐怕没有简单的解决方法:Torchvision 的随机变换实用程序的构建方式是在调用时对变换参数进行采样。它们是 唯一 随机变换,因为用户无法访问 (1) 参数并且 (2) 是相同的随机变换是可重复的。

    从 Torchvision 0.8.0 开始,随机变换通常具有两个主要功能:

    • get_params:将根据变换的超参数(初始化变换运算符时提供的,即参数的取值范围)进行采样

    • forward:应用转换时执行的函数。重要的部分是它从get_params 获取其参数,然后使用相关的确定性函数将其应用于输入。对于RandomRotationF.rotate 将被调用。同样,RandomAffine 将使用F.affine

    您的问题的一个解决方案是自己从get_params 中采样参数,然后调用函数式 - 确定性 - API。因此,您不会使用RandomRotationRandomAffine 或任何其他Random* 转换。


    例如,让我们看一下T.RandomRotation(为简洁起见,我删除了 cmets)。

    class RandomRotation(torch.nn.Module):
        def __init__(
            self, degrees, interpolation=InterpolationMode.NEAREST, expand=False, 
            center=None, fill=None, resample=None):
            # ...
    
        @staticmethod
        def get_params(degrees: List[float]) -> float:
            angle = float(torch.empty(1).uniform_(float(degrees[0]), \
                float(degrees[1])).item())
            return angle
    
        def forward(self, img):
            fill = self.fill
            if isinstance(img, Tensor):
                if isinstance(fill, (int, float)):
                    fill = [float(fill)] * F._get_image_num_channels(img)
                else:
                    fill = [float(f) for f in fill]
            angle = self.get_params(self.degrees)
    
            return F.rotate(img, angle, self.resample, self.expand, self.center, fill)
    
        def __repr__(self):
            # ...
    

    考虑到这一点,这里有一个可能的覆盖来修改T.RandomRotation

    class RandomRotation(T.RandomRotation):
        def __init__(*args, **kwargs):
            super(RandomRotation, self).__init__(*args, **kwargs) # let super do all the work
    
            self.angle = self.get_params(self.degrees) # initialize your random parameters
    
        def forward(self): # override T.RandomRotation's forward
            fill = self.fill
            if isinstance(img, Tensor):
                if isinstance(fill, (int, float)):
                    fill = [float(fill)] * F._get_image_num_channels(img)
                else:
                    fill = [float(f) for f in fill]
    
            return F.rotate(img, self.angle, self.resample, self.expand, self.center, fill)
    

    我基本上复制了T.RandomRotationforward 函数,唯一的区别是参数在__init__ie 一次)中采样,而不是在forwardie 每次通话)。 Torchvision 的实现涵盖了所有情况,您通常不需要复制完整的forward。在某些情况下,您可以直接调用功能版本。例如,如果您不需要设置fill 参数,则可以丢弃该部分并仅使用:

    class RandomRotation(T.RandomRotation):
        def __init__(*args, **kwargs):
            super(RandomRotation, self).__init__(*args, **kwargs) # let super do all the work
    
            self.angle = self.get_params(self.degrees) # initialize your random parameters
    
        def forward(self): # override T.RandomRotation's forward
            return F.rotate(img, self.angle, self.resample, self.expand, self.center)
    

    如果您想覆盖其他随机变换,您可以查看the source code。该 API 相当不言自明,为每个转换实现覆盖应该不会有太多问题。

    【讨论】:

    • 感谢您提供的详细信息。我担心这就是答案,但我感谢你的解释并写下来。
    猜你喜欢
    • 2015-10-06
    • 2019-05-06
    • 2017-12-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-18
    • 2020-09-29
    • 2016-09-29
    • 1970-01-01
    相关资源
    最近更新 更多