深度學(xué)習(xí) 分別利用PyTorch 與numpy實現(xiàn)數(shù)據(jù)增強

  1. PyTorch有自帶的數(shù)據(jù)增強包在torchvision.transforms中, 可以使用
import torchvision.transforms as transforms

my_transforms = transforms.Compose([
        transforms.RandomCrop(32),
        transforms.Grayscale(),
        transforms.RandomHorizontalFlip(),
        transforms.RandomVerticalFlip(),
        transforms.Resize(img_size),#for example img_size=(128, 128)
        transforms.ToTensor(),
        transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
    ])

實現(xiàn)張量空間的數(shù)據(jù)增強.

  1. 當(dāng)然也可以使用numpy, openCV自行實現(xiàn), 這樣更加自由, 給出我自己的實例如下, 在main中transforms.compose([Normalize()...])調(diào)用就可以了:
# normalization
class Normalize(object):
    def __init__(self, mean=0.5, std=0.5):
        self.mean = mean
        self.std = std

    def __call__(self, data):
        data["img"] = (data["img"] - self.mean) / self.std
        return data

# to PyTorch tensor
class ToTensor(object):
    def __init__(self):

    def __call__(self, data):
        data["img"] = torch.from_numpy(data["img"].transpose((2, 0, 1)).astype(np.float32))

        return data

# horizontal flip with probability p
class RandomHorizontalFlip(object):
    def __init__(self, p=0.5):
        self.p = p

    def __call__(self, data):
        if np.random.rand() < self.p:
            np.flip(data["img"], axis=1)
        else:
            data["img"] = data["img"]
        return data

# vertical flip with p
class RandomVerticalFlip(object):
    def __init__(self, p=0.5):
        self.p = p

    def __call__(self, data):
        if np.random.rand() < self.p:
            np.flip(data["img"], axis=0)
        else:
            data["img"] = data["img"]
        return data
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容