|
| 1 | +''' |
| 2 | +Code borrowed from https://github.com/lukasruff/Deep-SVDD-PyTorch |
| 3 | +''' |
| 4 | +from PIL import Image |
| 5 | +import numpy as np |
| 6 | +from random import sample |
| 7 | +from abc import ABC, abstractmethod |
| 8 | +import torch |
| 9 | +from torch.utils.data import Subset |
| 10 | +from torchvision.datasets import MNIST |
| 11 | +import torchvision.transforms as transforms |
| 12 | +from torch.utils.data import DataLoader |
| 13 | + |
| 14 | +class BaseADDataset(ABC): |
| 15 | + """Anomaly detection dataset base class.""" |
| 16 | + |
| 17 | + def __init__(self, root: str): |
| 18 | + super().__init__() |
| 19 | + self.root = root # root path to data |
| 20 | + |
| 21 | + self.n_classes = 2 # 0: normal, 1: outlier |
| 22 | + self.normal_classes = None # tuple with original class labels that define the normal class |
| 23 | + self.outlier_classes = None # tuple with original class labels that define the outlier class |
| 24 | + |
| 25 | + self.train_set = None # must be of type torch.utils.data.Dataset |
| 26 | + self.test_set = None # must be of type torch.utils.data.Dataset |
| 27 | + |
| 28 | + @abstractmethod |
| 29 | + def loaders(self, batch_size: int, shuffle_train=True, shuffle_test=False, num_workers: int = 0) -> ( |
| 30 | + DataLoader, DataLoader): |
| 31 | + """Implement data loaders of type torch.utils.data.DataLoader for train_set and test_set.""" |
| 32 | + pass |
| 33 | + |
| 34 | + def __repr__(self): |
| 35 | + return self.__class__.__name__ |
| 36 | + |
| 37 | +class TorchvisionDataset(BaseADDataset): |
| 38 | + """TorchvisionDataset class for datasets already implemented in torchvision.datasets.""" |
| 39 | + |
| 40 | + def __init__(self, root: str): |
| 41 | + super().__init__(root) |
| 42 | + |
| 43 | + def loaders(self, batch_size: int, shuffle_train=True, shuffle_test=False, num_workers: int = 0) -> ( |
| 44 | + DataLoader, DataLoader): |
| 45 | + train_loader = DataLoader(dataset=self.train_set, batch_size=batch_size, shuffle=shuffle_train, |
| 46 | + num_workers=num_workers) |
| 47 | + test_loader = DataLoader(dataset=self.test_set, batch_size=batch_size, shuffle=shuffle_test, |
| 48 | + num_workers=num_workers) |
| 49 | + return train_loader, test_loader |
| 50 | + |
| 51 | +class MNIST_Dataset(TorchvisionDataset): |
| 52 | + |
| 53 | + def __init__(self, root: str, normal_class=0): |
| 54 | + super().__init__(root) |
| 55 | + #Loads only the digit 0 and digit 1 data |
| 56 | + # for both train and test |
| 57 | + self.n_classes = 2 # 0: normal, 1: outlier |
| 58 | + self.normal_classes = tuple([0]) |
| 59 | + self.train_classes = tuple([0,1]) |
| 60 | + self.test_class = tuple([0,1]) |
| 61 | + |
| 62 | + transform = transforms.Compose([transforms.ToTensor(), |
| 63 | + transforms.Normalize(mean=[0.1307], |
| 64 | + std=[0.3081])]) |
| 65 | + |
| 66 | + target_transform = transforms.Lambda(lambda x: int(x in self.normal_classes)) |
| 67 | + |
| 68 | + train_set = MyMNIST(root=self.root, train=True, download=True, |
| 69 | + transform=transform, target_transform=target_transform) |
| 70 | + # Subset train_set to normal class |
| 71 | + train_idx_normal = get_target_label_idx(train_set.targets, self.train_classes) |
| 72 | + self.train_set = Subset(train_set, train_idx_normal) |
| 73 | + |
| 74 | + test_set = MyMNIST(root=self.root, train=False, download=True, |
| 75 | + transform=transform, target_transform=target_transform) |
| 76 | + test_idx_normal = get_target_label_idx(test_set.targets, self.test_class) |
| 77 | + self.test_set = Subset(test_set, test_idx_normal) |
| 78 | + |
| 79 | +class MyMNIST(MNIST): |
| 80 | + """Torchvision MNIST class with patch of __getitem__ method to also return the index of a data sample.""" |
| 81 | + |
| 82 | + def __init__(self, *args, **kwargs): |
| 83 | + super(MyMNIST, self).__init__(*args, **kwargs) |
| 84 | + |
| 85 | + def __getitem__(self, index): |
| 86 | + """Override the original method of the MNIST class. |
| 87 | + Args: |
| 88 | + index (int): Index |
| 89 | + Returns: |
| 90 | + triple: (image, target, index) where target is index of the target class. |
| 91 | + """ |
| 92 | + img, target = self.data[index], self.targets[index] |
| 93 | + |
| 94 | + # doing this so that it is consistent with all other datasets |
| 95 | + # to return a PIL Image |
| 96 | + img = Image.fromarray(img.numpy(), mode='L') |
| 97 | + |
| 98 | + if self.transform is not None: |
| 99 | + img = self.transform(img) |
| 100 | + |
| 101 | + if self.target_transform is not None: |
| 102 | + target = self.target_transform(target) |
| 103 | + |
| 104 | + return img, target, index # only line changed |
| 105 | + |
| 106 | + |
| 107 | +def get_target_label_idx(labels, targets): |
| 108 | + """ |
| 109 | + Get the indices of labels that are included in targets. |
| 110 | + :param labels: array of labels |
| 111 | + :param targets: list/tuple of target labels |
| 112 | + :return: list with indices of target labels |
| 113 | + """ |
| 114 | + return np.argwhere(np.isin(labels, targets)).flatten().tolist() |
| 115 | + |
| 116 | + |
| 117 | +def global_contrast_normalization(x: torch.tensor, scale='l2'): |
| 118 | + """ |
| 119 | + Apply global contrast normalization to tensor, i.e. subtract mean across features (pixels) and normalize by scale, |
| 120 | + which is either the standard deviation, L1- or L2-norm across features (pixels). |
| 121 | + Note this is a *per sample* normalization globally across features (and not across the dataset). |
| 122 | + """ |
| 123 | + |
| 124 | + assert scale in ('l1', 'l2') |
| 125 | + |
| 126 | + n_features = int(np.prod(x.shape)) |
| 127 | + |
| 128 | + mean = torch.mean(x) # mean over all features (pixels) per sample |
| 129 | + x -= mean |
| 130 | + |
| 131 | + if scale == 'l1': |
| 132 | + x_scale = torch.mean(torch.abs(x)) |
| 133 | + |
| 134 | + if scale == 'l2': |
| 135 | + x_scale = torch.sqrt(torch.sum(x ** 2)) / n_features |
| 136 | + |
| 137 | + x /= x_scale |
| 138 | + |
| 139 | + return x |
0 commit comments