├── data ├── __init__.py ├── datasets.py ├── utils.py └── cifar.py ├── out └── placeholder.txt ├── rec_global └── placeholder.txt ├── clip ├── __init__.py ├── bpe_simple_vocab_16e6.txt.gz ├── simple_tokenizer.py ├── clip.py └── model.py ├── requirements.txt ├── global_var.py ├── exceptions └── exceptions.py ├── test_c10_instance.sh ├── test_c100_instance.sh ├── README.md ├── models ├── model.py └── resnet.py ├── resnet_cifar.py ├── resnet.py ├── resnet_image.py ├── utils.py ├── LICENSE.md ├── main_fast.py └── hoc.py /data/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /out/placeholder.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /rec_global/placeholder.txt: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /clip/__init__.py: -------------------------------------------------------------------------------- 1 | from .clip import * 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | torch==1.7.1 3 | Pillow~=8.2.0 4 | torchvision 5 | tqdm 6 | ftfy 7 | regex 8 | pyyaml 9 | -------------------------------------------------------------------------------- /clip/bpe_simple_vocab_16e6.txt.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/UCSC-REAL/SimiFeat/HEAD/clip/bpe_simple_vocab_16e6.txt.gz -------------------------------------------------------------------------------- /global_var.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | def _init(): 3 | global _global_dict 4 | _global_dict = {} 5 | 6 | 7 | def set_value(key, value): 8 | _global_dict[key] = value 9 | 10 | 11 | def get_value(key): 12 | try: 13 | return _global_dict[key] 14 | except: 15 | print('read' + key + 'failed\r\n') 16 | -------------------------------------------------------------------------------- /exceptions/exceptions.py: -------------------------------------------------------------------------------- 1 | class BaseSimCLRException(Exception): 2 | """Base exception""" 3 | 4 | 5 | class InvalidBackboneError(BaseSimCLRException): 6 | """Raised when the choice of backbone Convnet is invalid.""" 7 | 8 | 9 | class InvalidDatasetSelection(BaseSimCLRException): 10 | """Raised when the choice of dataset is invalid.""" 11 | -------------------------------------------------------------------------------- /test_c10_instance.sh: -------------------------------------------------------------------------------- 1 | noise_type="instance" # pairflip symmetric instance manual 2 | methods="mv rank1" # mv rank1 both 3 | pre_type="image18 CLIP" # image18 image34 image50 ssl_c10 ssl_c100 CLIP clean_label_10 4 | # pre_type="clean_label_100" # image18 image34 image50 ssl_c10 ssl_c100 CLIP clean_label_10 5 | for PRE in $pre_type; 6 | do 7 | for NOISE in $noise_type; 8 | do 9 | for METHOD in $methods; 10 | do 11 | echo "Running model $PRE, noise $NOISE, method $METHOD" 12 | CUDA_VISIBLE_DEVICES=0 python3 main_fast.py --dataset cifar10 --noise_type $NOISE --k 10 --pre_type $PRE --noise_rate 0.4 --num_epoch 21 --Tii_offset 1.0 --method $METHOD > ./results/cifar10/c10_$METHOD\_$PRE\_$NOISE.log 13 | done 14 | done 15 | done 16 | -------------------------------------------------------------------------------- /test_c100_instance.sh: -------------------------------------------------------------------------------- 1 | 2 | noise_type="instance" # pairflip symmetric instance manual 3 | methods="mv rank1" # mv rank1 both 4 | # methods="rank1" # mv rank1 both 5 | pre_type="image18 CLIP" # image18 image34 image50 ssl_c10 ssl_c100 CLIP clean_label_10 6 | # pre_type="clean_label_100" # image18 image34 image50 ssl_c10 ssl_c100 CLIP clean_label_10 7 | for PRE in $pre_type; 8 | do 9 | for NOISE in $noise_type; 10 | do 11 | for METHOD in $methods; 12 | do 13 | echo "Running model $PRE, noise $NOISE, method $METHOD" 14 | CUDA_VISIBLE_DEVICES=0 python3 main_fast.py --dataset cifar100 --noise_type $NOISE --k 10 --pre_type $PRE --noise_rate 0.4 --num_epoch 21 --Tii_offset 1.0 --method $METHOD > ./results/cifar100/c100_$METHOD\_$PRE\_$NOISE.log 15 | done 16 | done 17 | done 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Detecting Corrupted Labels Without Training a Model to Predict 2 | 3 | **[Update 5/17/2023]** SimiFeat is a module of [Docta](https://github.com/Docta-ai/docta) now! 4 | - A doctor for your data 5 | - An advanced data-centric AI platform that offers a comprehensive range of services aimed at detecting and rectifying issues in your data. 6 | 7 | This code is a PyTorch implementation of the [paper](https://arxiv.org/abs/2110.06283): Detecting Corrupted Labels Without Training a Model to Predict 8 | 9 | 10 | ## Prerequisites 11 | 12 | Python 3.6.9 13 | 14 | PyTorch 1.7.1 15 | 16 | Torchvision 0.8.2 17 | 18 | Full list in ./requirements.txt 19 | 20 | Datasets will be downloaded to ./data/. 21 | 22 | ## Run HOC + Vote Based and Rank Based method 23 | 24 | On CIFAR-10 . 25 | 26 | ``` 27 | sh ./test_c10_instance.sh 28 | ``` 29 | 30 | On CIFAR-100 31 | 32 | ``` 33 | sh ./test_c100_instance.sh 34 | ``` 35 | -------------------------------------------------------------------------------- /models/model.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.nn.functional as F 4 | from torchvision.models.resnet import resnet34 5 | 6 | 7 | class Model(nn.Module): 8 | def __init__(self, feature_dim=128): 9 | super(Model, self).__init__() 10 | 11 | self.f = [] 12 | for name, module in resnet34().named_children(): 13 | if name == 'conv1': 14 | module = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) 15 | if not isinstance(module, nn.Linear) and not isinstance(module, nn.MaxPool2d): 16 | self.f.append(module) 17 | # encoder 18 | self.f = nn.Sequential(*self.f) 19 | # projection head 20 | self.g = nn.Sequential(nn.Linear(512, 512, bias=False), nn.BatchNorm1d(512), 21 | nn.ReLU(inplace=True), nn.Linear(512, feature_dim, bias=True)) 22 | 23 | def forward(self, x): 24 | x = self.f(x) 25 | feature = torch.flatten(x, start_dim=1) 26 | out = self.g(feature) 27 | return F.normalize(feature, dim=-1), F.normalize(out, dim=-1) 28 | -------------------------------------------------------------------------------- /models/resnet.py: -------------------------------------------------------------------------------- 1 | '''ResNet in PyTorch. 2 | 3 | For Pre-activation ResNet, see 'preact_resnet.py'. 4 | 5 | Reference: 6 | [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun 7 | Deep Residual Learning for Image Recognition. arXiv:1512.03385 8 | ''' 9 | import torch 10 | import torch.nn as nn 11 | import torch.nn.functional as F 12 | 13 | 14 | class BasicBlock(nn.Module): 15 | expansion = 1 16 | 17 | def __init__(self, in_planes, planes, stride=1): 18 | super(BasicBlock, self).__init__() 19 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 20 | self.bn1 = nn.BatchNorm2d(planes) 21 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) 22 | self.bn2 = nn.BatchNorm2d(planes) 23 | 24 | self.shortcut = nn.Sequential() 25 | if stride != 1 or in_planes != self.expansion * planes: 26 | self.shortcut = nn.Sequential( 27 | nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), 28 | nn.BatchNorm2d(self.expansion * planes) 29 | ) 30 | 31 | def forward(self, x): 32 | out = F.relu(self.bn1(self.conv1(x))) 33 | out = self.bn2(self.conv2(out)) 34 | out += self.shortcut(x) 35 | out = F.relu(out) 36 | return out 37 | 38 | 39 | class Bottleneck(nn.Module): 40 | expansion = 4 41 | 42 | def __init__(self, in_planes, planes, stride=1): 43 | super(Bottleneck, self).__init__() 44 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) 45 | self.bn1 = nn.BatchNorm2d(planes) 46 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 47 | self.bn2 = nn.BatchNorm2d(planes) 48 | self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False) 49 | self.bn3 = nn.BatchNorm2d(self.expansion * planes) 50 | 51 | self.shortcut = nn.Sequential() 52 | if stride != 1 or in_planes != self.expansion * planes: 53 | self.shortcut = nn.Sequential( 54 | nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), 55 | nn.BatchNorm2d(self.expansion * planes) 56 | ) 57 | 58 | def forward(self, x): 59 | out = F.relu(self.bn1(self.conv1(x))) 60 | out = F.relu(self.bn2(self.conv2(out))) 61 | out = self.bn3(self.conv3(out)) 62 | out += self.shortcut(x) 63 | out = F.relu(out) 64 | return out 65 | 66 | 67 | class ResNet(nn.Module): 68 | def __init__(self, block, num_blocks, num_classes=10): 69 | super(ResNet, self).__init__() 70 | self.in_planes = 64 71 | 72 | self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) 73 | self.bn1 = nn.BatchNorm2d(64) 74 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) 75 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) 76 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) 77 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) 78 | self.linear = nn.Linear(512 * block.expansion, num_classes) 79 | 80 | def _make_layer(self, block, planes, num_blocks, stride): 81 | strides = [stride] + [1] * (num_blocks - 1) 82 | layers = [] 83 | for stride in strides: 84 | layers.append(block(self.in_planes, planes, stride)) 85 | self.in_planes = planes * block.expansion 86 | return nn.Sequential(*layers) 87 | 88 | def forward(self, x): 89 | out = F.relu(self.bn1(self.conv1(x))) 90 | out = self.layer1(out) 91 | out = self.layer2(out) 92 | out = self.layer3(out) 93 | out = self.layer4(out) 94 | out = F.avg_pool2d(out, 4) 95 | out = out.view(out.size(0), -1) 96 | # out = self.linear(out) 97 | return out, self.linear(out) 98 | 99 | 100 | def ResNet18(num_classes): 101 | return ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes) 102 | 103 | 104 | def ResNet34(num_classes): 105 | return ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes) 106 | 107 | 108 | def ResNet50(num_classes): 109 | return ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes) 110 | 111 | 112 | def ResNet101(num_classes): 113 | return ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) 114 | 115 | 116 | def ResNet152(num_classes): 117 | return ResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) 118 | 119 | 120 | def test(): 121 | net = ResNet18() 122 | y = net(torch.randn(1, 3, 32, 32)) 123 | print(y.size()) 124 | 125 | # test() 126 | -------------------------------------------------------------------------------- /resnet_cifar.py: -------------------------------------------------------------------------------- 1 | '''ResNet in PyTorch. 2 | 3 | For Pre-activation ResNet, see 'preact_resnet.py'. 4 | 5 | Reference: 6 | [1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun 7 | Deep Residual Learning for Image Recognition. arXiv:1512.03385 8 | ''' 9 | import torch 10 | import torch.nn as nn 11 | import torch.nn.functional as F 12 | 13 | 14 | class BasicBlock(nn.Module): 15 | expansion = 1 16 | 17 | def __init__(self, in_planes, planes, stride=1): 18 | super(BasicBlock, self).__init__() 19 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 20 | self.bn1 = nn.BatchNorm2d(planes) 21 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) 22 | self.bn2 = nn.BatchNorm2d(planes) 23 | 24 | self.shortcut = nn.Sequential() 25 | if stride != 1 or in_planes != self.expansion * planes: 26 | self.shortcut = nn.Sequential( 27 | nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), 28 | nn.BatchNorm2d(self.expansion * planes) 29 | ) 30 | 31 | def forward(self, x): 32 | out = F.relu(self.bn1(self.conv1(x))) 33 | out = self.bn2(self.conv2(out)) 34 | out += self.shortcut(x) 35 | out = F.relu(out) 36 | return out 37 | 38 | 39 | class Bottleneck(nn.Module): 40 | expansion = 4 41 | 42 | def __init__(self, in_planes, planes, stride=1): 43 | super(Bottleneck, self).__init__() 44 | self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False) 45 | self.bn1 = nn.BatchNorm2d(planes) 46 | self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) 47 | self.bn2 = nn.BatchNorm2d(planes) 48 | self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=1, bias=False) 49 | self.bn3 = nn.BatchNorm2d(self.expansion * planes) 50 | 51 | self.shortcut = nn.Sequential() 52 | if stride != 1 or in_planes != self.expansion * planes: 53 | self.shortcut = nn.Sequential( 54 | nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), 55 | nn.BatchNorm2d(self.expansion * planes) 56 | ) 57 | 58 | def forward(self, x): 59 | out = F.relu(self.bn1(self.conv1(x))) 60 | out = F.relu(self.bn2(self.conv2(out))) 61 | out = self.bn3(self.conv3(out)) 62 | out += self.shortcut(x) 63 | out = F.relu(out) 64 | return out 65 | 66 | 67 | class ResNet(nn.Module): 68 | def __init__(self, block, num_blocks, num_classes=10): 69 | super(ResNet, self).__init__() 70 | self.in_planes = 64 71 | 72 | self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) 73 | self.bn1 = nn.BatchNorm2d(64) 74 | self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) 75 | self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) 76 | self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) 77 | self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) 78 | self.linear = nn.Linear(512 * block.expansion, num_classes) 79 | 80 | def _make_layer(self, block, planes, num_blocks, stride): 81 | strides = [stride] + [1] * (num_blocks - 1) 82 | layers = [] 83 | for stride in strides: 84 | layers.append(block(self.in_planes, planes, stride)) 85 | self.in_planes = planes * block.expansion 86 | return nn.Sequential(*layers) 87 | 88 | def forward(self, x): 89 | out = F.relu(self.bn1(self.conv1(x))) 90 | out = self.layer1(out) 91 | out = self.layer2(out) 92 | out = self.layer3(out) 93 | out = self.layer4(out) 94 | out = F.avg_pool2d(out, 4) 95 | out = out.view(out.size(0), -1) 96 | # out = self.linear(out) 97 | return out, self.linear(out) 98 | 99 | 100 | def ResNet18(num_classes): 101 | return ResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes) 102 | 103 | 104 | def ResNet34(num_classes): 105 | return ResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes) 106 | 107 | 108 | def ResNet50(num_classes): 109 | return ResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes) 110 | 111 | 112 | def ResNet101(num_classes): 113 | return ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) 114 | 115 | 116 | def ResNet152(num_classes): 117 | return ResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) 118 | 119 | 120 | def test(): 121 | net = ResNet18() 122 | y = net(torch.randn(1, 3, 32, 32)) 123 | print(y.size()) 124 | 125 | # test() 126 | -------------------------------------------------------------------------------- /clip/simple_tokenizer.py: -------------------------------------------------------------------------------- 1 | import gzip 2 | import html 3 | import os 4 | from functools import lru_cache 5 | 6 | import ftfy 7 | import regex as re 8 | 9 | 10 | @lru_cache() 11 | def default_bpe(): 12 | return os.path.join(os.path.dirname(os.path.abspath(__file__)), "bpe_simple_vocab_16e6.txt.gz") 13 | 14 | 15 | @lru_cache() 16 | def bytes_to_unicode(): 17 | """ 18 | Returns list of utf-8 byte and a corresponding list of unicode strings. 19 | The reversible bpe codes work on unicode strings. 20 | This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. 21 | When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. 22 | This is a signficant percentage of your normal, say, 32K bpe vocab. 23 | To avoid that, we want lookup tables between utf-8 bytes and unicode strings. 24 | And avoids mapping to whitespace/control characters the bpe code barfs on. 25 | """ 26 | bs = list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1)) 27 | cs = bs[:] 28 | n = 0 29 | for b in range(2 ** 8): 30 | if b not in bs: 31 | bs.append(b) 32 | cs.append(2 ** 8 + n) 33 | n += 1 34 | cs = [chr(n) for n in cs] 35 | return dict(zip(bs, cs)) 36 | 37 | 38 | def get_pairs(word): 39 | """Return set of symbol pairs in a word. 40 | Word is represented as tuple of symbols (symbols being variable-length strings). 41 | """ 42 | pairs = set() 43 | prev_char = word[0] 44 | for char in word[1:]: 45 | pairs.add((prev_char, char)) 46 | prev_char = char 47 | return pairs 48 | 49 | 50 | def basic_clean(text): 51 | text = ftfy.fix_text(text) 52 | text = html.unescape(html.unescape(text)) 53 | return text.strip() 54 | 55 | 56 | def whitespace_clean(text): 57 | text = re.sub(r'\s+', ' ', text) 58 | text = text.strip() 59 | return text 60 | 61 | 62 | class SimpleTokenizer(object): 63 | def __init__(self, bpe_path: str = default_bpe()): 64 | self.byte_encoder = bytes_to_unicode() 65 | self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} 66 | merges = gzip.open(bpe_path).read().decode("utf-8").split('\n') 67 | merges = merges[1:49152 - 256 - 2 + 1] 68 | merges = [tuple(merge.split()) for merge in merges] 69 | vocab = list(bytes_to_unicode().values()) 70 | vocab = vocab + [v + '' for v in vocab] 71 | for merge in merges: 72 | vocab.append(''.join(merge)) 73 | vocab.extend(['<|startoftext|>', '<|endoftext|>']) 74 | self.encoder = dict(zip(vocab, range(len(vocab)))) 75 | self.decoder = {v: k for k, v in self.encoder.items()} 76 | self.bpe_ranks = dict(zip(merges, range(len(merges)))) 77 | self.cache = {'<|startoftext|>': '<|startoftext|>', '<|endoftext|>': '<|endoftext|>'} 78 | self.pat = re.compile( 79 | r"""<\|startoftext\|>|<\|endoftext\|>|'s|'t|'re|'ve|'m|'ll|'d|[\p{L}]+|[\p{N}]|[^\s\p{L}\p{N}]+""", 80 | re.IGNORECASE) 81 | 82 | def bpe(self, token): 83 | if token in self.cache: 84 | return self.cache[token] 85 | word = tuple(token[:-1]) + (token[-1] + '',) 86 | pairs = get_pairs(word) 87 | 88 | if not pairs: 89 | return token + '' 90 | 91 | while True: 92 | bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf'))) 93 | if bigram not in self.bpe_ranks: 94 | break 95 | first, second = bigram 96 | new_word = [] 97 | i = 0 98 | while i < len(word): 99 | try: 100 | j = word.index(first, i) 101 | new_word.extend(word[i:j]) 102 | i = j 103 | except: 104 | new_word.extend(word[i:]) 105 | break 106 | 107 | if word[i] == first and i < len(word) - 1 and word[i + 1] == second: 108 | new_word.append(first + second) 109 | i += 2 110 | else: 111 | new_word.append(word[i]) 112 | i += 1 113 | new_word = tuple(new_word) 114 | word = new_word 115 | if len(word) == 1: 116 | break 117 | else: 118 | pairs = get_pairs(word) 119 | word = ' '.join(word) 120 | self.cache[token] = word 121 | return word 122 | 123 | def encode(self, text): 124 | bpe_tokens = [] 125 | text = whitespace_clean(basic_clean(text)).lower() 126 | for token in re.findall(self.pat, text): 127 | token = ''.join(self.byte_encoder[b] for b in token.encode('utf-8')) 128 | bpe_tokens.extend(self.encoder[bpe_token] for bpe_token in self.bpe(token).split(' ')) 129 | return bpe_tokens 130 | 131 | def decode(self, tokens): 132 | text = ''.join([self.decoder[token] for token in tokens]) 133 | text = bytearray([self.byte_decoder[c] for c in text]).decode('utf-8', errors="replace").replace('', ' ') 134 | return text 135 | -------------------------------------------------------------------------------- /data/datasets.py: -------------------------------------------------------------------------------- 1 | import torchvision.transforms as transforms 2 | from .cifar import CIFAR10, CIFAR100 3 | 4 | train_cifar10_transform = transforms.Compose([ 5 | transforms.RandomCrop(32, padding=4), 6 | transforms.RandomHorizontalFlip(), 7 | transforms.ToTensor(), 8 | transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), 9 | ]) 10 | 11 | test_cifar10_transform = transforms.Compose([ 12 | transforms.ToTensor(), 13 | transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)), 14 | ]) 15 | train_cifar100_transform = transforms.Compose([ 16 | transforms.RandomCrop(32, padding=4), 17 | transforms.RandomHorizontalFlip(), 18 | transforms.ToTensor(), 19 | transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)), 20 | ]) 21 | 22 | test_cifar100_transform = transforms.Compose([ 23 | transforms.ToTensor(), 24 | transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761)), 25 | ]) 26 | 27 | 28 | def input_dataset(dataset, noise_type, noise_ratio, transform=True, noise_file=None): 29 | if dataset == 'cifar10': 30 | train_dataset = CIFAR10(root='./data/', 31 | download=True, 32 | train=True, 33 | transform=train_cifar10_transform if transform else test_cifar10_transform, 34 | noise_type=noise_type, 35 | noise_rate=noise_ratio, 36 | noise_file=noise_file, 37 | ) 38 | test_dataset = CIFAR10(root='./data/', 39 | download=True, 40 | train=False, 41 | transform=test_cifar10_transform, 42 | noise_type=noise_type, 43 | noise_rate=noise_ratio 44 | ) 45 | num_classes = 10 46 | num_training_samples = 50000 47 | num_testing_samples = 10000 48 | 49 | elif dataset == 'cifar100': 50 | train_dataset = CIFAR100(root='./data/', 51 | download=True, 52 | train=True, 53 | transform=train_cifar100_transform if transform else test_cifar100_transform, 54 | noise_type=noise_type, 55 | noise_rate=noise_ratio, 56 | noise_file=noise_file 57 | ) 58 | test_dataset = CIFAR100(root='./data/', 59 | download=True, 60 | train=False, 61 | transform=test_cifar100_transform, 62 | noise_type=noise_type, 63 | noise_rate=noise_ratio 64 | ) 65 | num_classes = 100 66 | num_training_samples = 50000 67 | num_testing_samples = 10000 68 | 69 | return train_dataset, test_dataset, num_classes, num_training_samples, num_testing_samples 70 | 71 | 72 | def input_dataset_clip(dataset, noise_type, noise_ratio, transform=None, noise_file=None): 73 | print(dataset) 74 | if dataset == 'cifar10': 75 | train_dataset = CIFAR10(root='~/data/', 76 | download=True, 77 | train=True, 78 | transform=transform, 79 | noise_type=noise_type, 80 | noise_rate=noise_ratio, 81 | noise_file=noise_file, 82 | ) 83 | test_dataset = CIFAR10(root='~/data/', 84 | download=True, 85 | train=False, 86 | transform=transform, 87 | noise_type=noise_type, 88 | noise_rate=noise_ratio 89 | ) 90 | num_classes = 10 91 | num_training_samples = len(train_dataset.train_labels) 92 | num_testing_samples = 10000 93 | 94 | elif dataset == 'cifar100': 95 | train_dataset = CIFAR100(root='~/data/', 96 | download=True, 97 | train=True, 98 | transform=transform, 99 | noise_type=noise_type, 100 | noise_rate=noise_ratio, 101 | noise_file=noise_file 102 | ) 103 | test_dataset = CIFAR100(root='~/data/', 104 | download=True, 105 | train=False, 106 | transform=transform, 107 | noise_type=noise_type, 108 | noise_rate=noise_ratio 109 | ) 110 | num_classes = 100 111 | num_training_samples = len(train_dataset.train_noisy_labels) 112 | num_testing_samples = 10000 113 | 114 | return train_dataset, test_dataset, num_classes, num_training_samples, num_testing_samples 115 | -------------------------------------------------------------------------------- /data/utils.py: -------------------------------------------------------------------------------- 1 | import errno 2 | import hashlib 3 | import os 4 | import os.path 5 | 6 | import numpy as np 7 | import torch 8 | import torch.nn.functional as F 9 | from numpy.testing import assert_array_almost_equal 10 | 11 | 12 | def check_integrity(fpath, md5): 13 | if not os.path.isfile(fpath): 14 | return False 15 | md5o = hashlib.md5() 16 | with open(fpath, 'rb') as f: 17 | # read in 1MB chunks 18 | for chunk in iter(lambda: f.read(1024 * 1024), b''): 19 | md5o.update(chunk) 20 | md5c = md5o.hexdigest() 21 | if md5c != md5: 22 | return False 23 | return True 24 | 25 | 26 | def download_url(url, root, filename, md5): 27 | from six.moves import urllib 28 | 29 | root = os.path.expanduser(root) 30 | fpath = os.path.join(root, filename) 31 | 32 | try: 33 | os.makedirs(root) 34 | except OSError as e: 35 | if e.errno == errno.EEXIST: 36 | pass 37 | else: 38 | raise 39 | 40 | # downloads file 41 | if os.path.isfile(fpath) and check_integrity(fpath, md5): 42 | print('Using downloaded and verified file: ' + fpath) 43 | else: 44 | try: 45 | print('Downloading ' + url + ' to ' + fpath) 46 | urllib.request.urlretrieve(url, fpath) 47 | except: 48 | if url[:5] == 'https': 49 | url = url.replace('https:', 'http:') 50 | print('Failed download. Trying https -> http instead.' 51 | ' Downloading ' + url + ' to ' + fpath) 52 | urllib.request.urlretrieve(url, fpath) 53 | 54 | 55 | def list_dir(root, prefix=False): 56 | """List all directories at a given root 57 | 58 | Args: 59 | root (str): Path to directory whose folders need to be listed 60 | prefix (bool, optional): If true, prepends the path to each result, otherwise 61 | only returns the name of the directories found 62 | """ 63 | root = os.path.expanduser(root) 64 | directories = list( 65 | filter( 66 | lambda p: os.path.isdir(os.path.join(root, p)), 67 | os.listdir(root) 68 | ) 69 | ) 70 | 71 | if prefix is True: 72 | directories = [os.path.join(root, d) for d in directories] 73 | 74 | return directories 75 | 76 | 77 | def list_files(root, suffix, prefix=False): 78 | """List all files ending with a suffix at a given root 79 | 80 | Args: 81 | root (str): Path to directory whose folders need to be listed 82 | suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png'). 83 | It uses the Python "str.endswith" method and is passed directly 84 | prefix (bool, optional): If true, prepends the path to each result, otherwise 85 | only returns the name of the files found 86 | """ 87 | root = os.path.expanduser(root) 88 | files = list( 89 | filter( 90 | lambda p: os.path.isfile(os.path.join(root, p)) and p.endswith(suffix), 91 | os.listdir(root) 92 | ) 93 | ) 94 | 95 | if prefix is True: 96 | files = [os.path.join(root, d) for d in files] 97 | 98 | return files 99 | 100 | 101 | # basic function# 102 | def multiclass_noisify(y, P, random_state=0): 103 | """ Flip classes according to transition probability matrix T. 104 | It expects a number between 0 and the number of classes - 1. 105 | """ 106 | # print np.max(y), P.shape[0] 107 | assert P.shape[0] == P.shape[1] 108 | assert np.max(y) < P.shape[0] 109 | 110 | # row stochastic matrix 111 | assert_array_almost_equal(P.sum(axis=1), np.ones(P.shape[1])) 112 | assert (P >= 0.0).all() 113 | 114 | m = y.shape[0] 115 | # print m 116 | new_y = y.copy() 117 | flipper = np.random.RandomState(random_state) 118 | 119 | for idx in np.arange(m): 120 | i = y[idx] 121 | # draw a vector with only an 1 122 | flipped = flipper.multinomial(1, P[i, :][0], 1)[0] 123 | new_y[idx] = np.where(flipped == 1)[0] 124 | 125 | return new_y 126 | 127 | 128 | # noisify_pairflip call the function "multiclass_noisify" 129 | def noisify_pairflip(y_train, noise, random_state=None, nb_classes=10): 130 | """mistakes: 131 | flip in the pair 132 | """ 133 | P = np.eye(nb_classes) 134 | n = noise 135 | 136 | if n > 0.0: 137 | # 0 -> 1 138 | P[0, 0], P[0, 1] = 1. - n, n 139 | for i in range(1, nb_classes - 1): 140 | P[i, i], P[i, i + 1] = 1. - n, n 141 | P[nb_classes - 1, nb_classes - 1], P[nb_classes - 1, 0] = 1. - n, n 142 | 143 | y_train_noisy = multiclass_noisify(y_train, P=P, 144 | random_state=random_state) 145 | actual_noise = (y_train_noisy != y_train).mean() 146 | assert actual_noise > 0.0 147 | print('Actual noise %.2f' % actual_noise) 148 | y_train = y_train_noisy 149 | # print P 150 | 151 | return y_train, actual_noise 152 | 153 | 154 | def noisify_multiclass_symmetric(y_train, noise, random_state=None, nb_classes=10): 155 | """mistakes: 156 | flip in the symmetric way 157 | """ 158 | P = np.ones((nb_classes, nb_classes)) 159 | n = noise 160 | P = (n / (nb_classes - 1)) * P 161 | 162 | if n > 0.0: 163 | # 0 -> 1 164 | P[0, 0] = 1. - n 165 | for i in range(1, nb_classes - 1): 166 | P[i, i] = 1. - n 167 | P[nb_classes - 1, nb_classes - 1] = 1. - n 168 | 169 | y_train_noisy = multiclass_noisify(y_train, P=P, 170 | random_state=random_state) 171 | actual_noise = (y_train_noisy != y_train).mean() 172 | assert actual_noise > 0.0 173 | print('Actual noise %.2f' % actual_noise) 174 | y_train = y_train_noisy 175 | # print P 176 | 177 | return y_train, actual_noise 178 | 179 | 180 | def noisify(dataset='mnist', nb_classes=10, train_labels=None, noise_type=None, noise_rate=0, random_state=0): 181 | if noise_type == 'pairflip': 182 | train_noisy_labels, actual_noise_rate = noisify_pairflip(train_labels, noise_rate, random_state=0, 183 | nb_classes=nb_classes) 184 | elif noise_type == 'symmetric': 185 | train_noisy_labels, actual_noise_rate = noisify_multiclass_symmetric(train_labels, noise_rate, random_state=0, 186 | nb_classes=nb_classes) 187 | else: 188 | print(f'Current input is {noise_type}') 189 | return train_noisy_labels, actual_noise_rate 190 | 191 | 192 | def noisify_instance(train_data,train_labels,noise_rate): 193 | if max(train_labels)>10: 194 | num_class = 100 195 | else: 196 | num_class = 10 197 | np.random.seed(0) 198 | 199 | q_ = np.random.normal(loc=noise_rate,scale=0.1,size=1000000) 200 | q = [] 201 | for pro in q_: 202 | if 0 < pro < 1: 203 | q.append(pro) 204 | if len(q)==50000: 205 | break 206 | 207 | w = [] 208 | for i in range(num_class): 209 | w.append(np.random.normal(loc=0,scale=1,size=(32*32*3,num_class))) 210 | 211 | noisy_labels = [] 212 | T = np.zeros((num_class,num_class)) 213 | for i, sample in enumerate(train_data): 214 | sample = sample.flatten() 215 | p_all = np.matmul(sample,w[train_labels[i]]) 216 | p_all[train_labels[i]] = -1000000 217 | p_all = q[i]* F.softmax(torch.tensor(p_all),dim=0).numpy() 218 | p_all[train_labels[i]] = 1 - q[i] 219 | noisy_labels.append(np.random.choice(np.arange(num_class),p=p_all/sum(p_all))) 220 | T[train_labels[i]][noisy_labels[i]] += 1 221 | over_all_noise_rate = 1 - float(torch.tensor(train_labels).eq(torch.tensor(noisy_labels)).sum())/50000 222 | T = T/np.sum(T,axis=1) 223 | print(np.round(T*100,1)) 224 | return noisy_labels, over_all_noise_rate 225 | -------------------------------------------------------------------------------- /clip/clip.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import os 3 | import urllib 4 | import warnings 5 | from typing import Union, List 6 | 7 | import torch 8 | from PIL import Image 9 | from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize, Lambda 10 | from tqdm import tqdm 11 | 12 | from .model import build_model 13 | from .simple_tokenizer import SimpleTokenizer as _Tokenizer 14 | 15 | __all__ = ["available_models", "load", "tokenize"] 16 | _tokenizer = _Tokenizer() 17 | 18 | _MODELS = { 19 | "RN50": "https://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.pt", 20 | "RN101": "https://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.pt", 21 | "RN50x4": "https://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.pt", 22 | "ViT-B/32": "https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.pt", 23 | } 24 | 25 | 26 | def _download(url: str, root: str = os.path.expanduser("~/.cache/clip")): 27 | os.makedirs(root, exist_ok=True) 28 | filename = os.path.basename(url) 29 | 30 | expected_sha256 = url.split("/")[-2] 31 | download_target = os.path.join(root, filename) 32 | 33 | if os.path.exists(download_target) and not os.path.isfile(download_target): 34 | raise RuntimeError(f"{download_target} exists and is not a regular file") 35 | 36 | if os.path.isfile(download_target): 37 | if hashlib.sha256(open(download_target, "rb").read()).hexdigest() == expected_sha256: 38 | return download_target 39 | else: 40 | warnings.warn(f"{download_target} exists, but the SHA256 checksum does not match; re-downloading the file") 41 | 42 | with urllib.request.urlopen(url) as source, open(download_target, "wb") as output: 43 | with tqdm(total=int(source.info().get("Content-Length")), ncols=80, unit='iB', unit_scale=True) as loop: 44 | while True: 45 | buffer = source.read(8192) 46 | if not buffer: 47 | break 48 | 49 | output.write(buffer) 50 | loop.update(len(buffer)) 51 | 52 | if hashlib.sha256(open(download_target, "rb").read()).hexdigest() != expected_sha256: 53 | raise RuntimeError(f"Model has been downloaded but the SHA256 checksum does not not match") 54 | 55 | return download_target 56 | 57 | 58 | def _convert_RGB(image): 59 | return image.convert("RGB") 60 | 61 | 62 | def _transform(n_px): 63 | return Compose([ 64 | Resize(n_px, interpolation=Image.BICUBIC), 65 | CenterCrop(n_px), 66 | # lambda image: image.convert("RGB"), 67 | Lambda(_convert_RGB), 68 | ToTensor(), 69 | Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)), 70 | ]) 71 | 72 | 73 | def available_models() -> List[str]: 74 | """Returns the names of available CLIP models""" 75 | return list(_MODELS.keys()) 76 | 77 | 78 | def load(name: str, device: Union[str, torch.device] = "cuda" if torch.cuda.is_available() else "cpu", jit=True): 79 | """Load a CLIP model 80 | 81 | Parameters 82 | ---------- 83 | name : str 84 | A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict 85 | 86 | device : Union[str, torch.device] 87 | The device to put the loaded model 88 | 89 | jit : bool 90 | Whether to load the optimized JIT model (default) or more hackable non-JIT model. 91 | 92 | Returns 93 | ------- 94 | model : torch.nn.Module 95 | The CLIP model 96 | 97 | preprocess : Callable[[PIL.Image], torch.Tensor] 98 | A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input 99 | """ 100 | if name in _MODELS: 101 | model_path = _download(_MODELS[name]) 102 | elif os.path.isfile(name): 103 | model_path = name 104 | else: 105 | raise RuntimeError(f"Model {name} not found; available models = {available_models()}") 106 | 107 | try: 108 | # loading JIT archive 109 | model = torch.jit.load(model_path, map_location=device if jit else "cpu").eval() 110 | state_dict = None 111 | except RuntimeError: 112 | # loading saved state dict 113 | if jit: 114 | warnings.warn(f"File {model_path} is not a JIT archive. Loading as a state dict instead") 115 | jit = False 116 | state_dict = torch.load(model_path, map_location="cpu") 117 | 118 | if not jit: 119 | model = build_model(state_dict or model.state_dict()).to(device) 120 | if str(device) == "cpu": 121 | model.float() 122 | return model, _transform(model.visual.input_resolution) 123 | 124 | # patch the device names 125 | device_holder = torch.jit.trace(lambda: torch.ones([]).to(torch.device(device)), example_inputs=[]) 126 | device_node = [n for n in device_holder.graph.findAllNodes("prim::Constant") if "Device" in repr(n)][-1] 127 | 128 | def patch_device(module): 129 | graphs = [module.graph] if hasattr(module, "graph") else [] 130 | if hasattr(module, "forward1"): 131 | graphs.append(module.forward1.graph) 132 | 133 | for graph in graphs: 134 | for node in graph.findAllNodes("prim::Constant"): 135 | if "value" in node.attributeNames() and str(node["value"]).startswith("cuda"): 136 | node.copyAttributes(device_node) 137 | 138 | model.apply(patch_device) 139 | patch_device(model.encode_image) 140 | patch_device(model.encode_text) 141 | 142 | # patch dtype to float32 on CPU 143 | if str(device) == "cpu": 144 | float_holder = torch.jit.trace(lambda: torch.ones([]).float(), example_inputs=[]) 145 | float_input = list(float_holder.graph.findNode("aten::to").inputs())[1] 146 | float_node = float_input.node() 147 | 148 | def patch_float(module): 149 | graphs = [module.graph] if hasattr(module, "graph") else [] 150 | if hasattr(module, "forward1"): 151 | graphs.append(module.forward1.graph) 152 | 153 | for graph in graphs: 154 | for node in graph.findAllNodes("aten::to"): 155 | inputs = list(node.inputs()) 156 | for i in [1, 2]: # dtype can be the second or third argument to aten::to() 157 | if inputs[i].node()["value"] == 5: 158 | inputs[i].node().copyAttributes(float_node) 159 | 160 | model.apply(patch_float) 161 | patch_float(model.encode_image) 162 | patch_float(model.encode_text) 163 | 164 | model.float() 165 | 166 | return model, _transform(model.input_resolution.item()) 167 | 168 | 169 | def tokenize(texts: Union[str, List[str]], context_length: int = 77) -> torch.LongTensor: 170 | """ 171 | Returns the tokenized representation of given input string(s) 172 | 173 | Parameters 174 | ---------- 175 | texts : Union[str, List[str]] 176 | An input string or a list of input strings to tokenize 177 | 178 | context_length : int 179 | The context length to use; all CLIP models use 77 as the context length 180 | 181 | Returns 182 | ------- 183 | A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length] 184 | """ 185 | if isinstance(texts, str): 186 | texts = [texts] 187 | 188 | sot_token = _tokenizer.encoder["<|startoftext|>"] 189 | eot_token = _tokenizer.encoder["<|endoftext|>"] 190 | all_tokens = [[sot_token] + _tokenizer.encode(text) + [eot_token] for text in texts] 191 | result = torch.zeros(len(all_tokens), context_length, dtype=torch.long) 192 | 193 | for i, tokens in enumerate(all_tokens): 194 | if len(tokens) > context_length: 195 | raise RuntimeError(f"Input {texts[i]} is too long for context length {context_length}") 196 | result[i, :len(tokens)] = torch.tensor(tokens) 197 | 198 | return result 199 | -------------------------------------------------------------------------------- /resnet.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import torch 4 | import torch.nn as nn 5 | 6 | __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 7 | 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d'] 8 | 9 | 10 | def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): 11 | """3x3 convolution with padding""" 12 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 13 | padding=dilation, groups=groups, bias=False, dilation=dilation) 14 | 15 | 16 | def conv1x1(in_planes, out_planes, stride=1): 17 | """1x1 convolution""" 18 | return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) 19 | 20 | 21 | class BasicBlock(nn.Module): 22 | expansion = 1 23 | 24 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 25 | base_width=64, dilation=1, norm_layer=None): 26 | super(BasicBlock, self).__init__() 27 | if norm_layer is None: 28 | norm_layer = nn.BatchNorm2d 29 | if groups != 1 or base_width != 64: 30 | raise ValueError('BasicBlock only supports groups=1 and base_width=64') 31 | if dilation > 1: 32 | raise NotImplementedError("Dilation > 1 not supported in BasicBlock") 33 | # Both self.conv1 and self.downsample layers downsample the input when stride != 1 34 | self.conv1 = conv3x3(inplanes, planes, stride) 35 | self.bn1 = norm_layer(planes) 36 | self.relu = nn.ReLU(inplace=True) 37 | self.conv2 = conv3x3(planes, planes) 38 | self.bn2 = norm_layer(planes) 39 | self.downsample = downsample 40 | self.stride = stride 41 | 42 | def forward(self, x): 43 | identity = x 44 | 45 | out = self.conv1(x) 46 | out = self.bn1(out) 47 | out = self.relu(out) 48 | 49 | out = self.conv2(out) 50 | out = self.bn2(out) 51 | 52 | if self.downsample is not None: 53 | identity = self.downsample(x) 54 | 55 | out += identity 56 | out = self.relu(out) 57 | 58 | return out 59 | 60 | 61 | class Bottleneck(nn.Module): 62 | expansion = 4 63 | 64 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 65 | base_width=64, dilation=1, norm_layer=None): 66 | super(Bottleneck, self).__init__() 67 | if norm_layer is None: 68 | norm_layer = nn.BatchNorm2d 69 | width = int(planes * (base_width / 64.)) * groups 70 | # Both self.conv2 and self.downsample layers downsample the input when stride != 1 71 | self.conv1 = conv1x1(inplanes, width) 72 | self.bn1 = norm_layer(width) 73 | self.conv2 = conv3x3(width, width, stride, groups, dilation) 74 | self.bn2 = norm_layer(width) 75 | self.conv3 = conv1x1(width, planes * self.expansion) 76 | self.bn3 = norm_layer(planes * self.expansion) 77 | self.relu = nn.ReLU(inplace=True) 78 | self.downsample = downsample 79 | self.stride = stride 80 | 81 | def forward(self, x): 82 | identity = x 83 | 84 | out = self.conv1(x) 85 | out = self.bn1(out) 86 | out = self.relu(out) 87 | 88 | out = self.conv2(out) 89 | out = self.bn2(out) 90 | out = self.relu(out) 91 | 92 | out = self.conv3(out) 93 | out = self.bn3(out) 94 | 95 | if self.downsample is not None: 96 | identity = self.downsample(x) 97 | 98 | out += identity 99 | out = self.relu(out) 100 | 101 | return out 102 | 103 | 104 | class ResNet(nn.Module): 105 | 106 | def __init__(self, block, layers, num_classes=10, zero_init_residual=False, 107 | groups=1, width_per_group=64, replace_stride_with_dilation=None, 108 | norm_layer=None): 109 | super(ResNet, self).__init__() 110 | if norm_layer is None: 111 | norm_layer = nn.BatchNorm2d 112 | self._norm_layer = norm_layer 113 | 114 | self.inplanes = 64 115 | self.dilation = 1 116 | if replace_stride_with_dilation is None: 117 | # each element in the tuple indicates if we should replace 118 | # the 2x2 stride with a dilated convolution instead 119 | replace_stride_with_dilation = [False, False, False] 120 | if len(replace_stride_with_dilation) != 3: 121 | raise ValueError("replace_stride_with_dilation should be None " 122 | "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) 123 | self.groups = groups 124 | self.base_width = width_per_group 125 | 126 | ## CIFAR10: kernel_size 7 -> 3, stride 2 -> 1, padding 3->1 127 | self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=3, stride=1, padding=1, bias=False) 128 | ## END 129 | 130 | self.bn1 = norm_layer(self.inplanes) 131 | self.relu = nn.ReLU(inplace=True) 132 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 133 | self.layer1 = self._make_layer(block, 64, layers[0]) 134 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2, 135 | dilate=replace_stride_with_dilation[0]) 136 | self.layer3 = self._make_layer(block, 256, layers[2], stride=2, 137 | dilate=replace_stride_with_dilation[1]) 138 | self.layer4 = self._make_layer(block, 512, layers[3], stride=2, 139 | dilate=replace_stride_with_dilation[2]) 140 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) 141 | self.fc = nn.Linear(512 * block.expansion, num_classes) 142 | 143 | for m in self.modules(): 144 | if isinstance(m, nn.Conv2d): 145 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 146 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 147 | nn.init.constant_(m.weight, 1) 148 | nn.init.constant_(m.bias, 0) 149 | 150 | # Zero-initialize the last BN in each residual branch, 151 | # so that the residual branch starts with zeros, and each residual block behaves like an identity. 152 | # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 153 | if zero_init_residual: 154 | for m in self.modules(): 155 | if isinstance(m, Bottleneck): 156 | nn.init.constant_(m.bn3.weight, 0) 157 | elif isinstance(m, BasicBlock): 158 | nn.init.constant_(m.bn2.weight, 0) 159 | 160 | def _make_layer(self, block, planes, blocks, stride=1, dilate=False): 161 | norm_layer = self._norm_layer 162 | downsample = None 163 | previous_dilation = self.dilation 164 | if dilate: 165 | self.dilation *= stride 166 | stride = 1 167 | if stride != 1 or self.inplanes != planes * block.expansion: 168 | downsample = nn.Sequential( 169 | conv1x1(self.inplanes, planes * block.expansion, stride), 170 | norm_layer(planes * block.expansion), 171 | ) 172 | 173 | layers = [] 174 | layers.append(block(self.inplanes, planes, stride, downsample, self.groups, 175 | self.base_width, previous_dilation, norm_layer)) 176 | self.inplanes = planes * block.expansion 177 | for _ in range(1, blocks): 178 | layers.append(block(self.inplanes, planes, groups=self.groups, 179 | base_width=self.base_width, dilation=self.dilation, 180 | norm_layer=norm_layer)) 181 | 182 | return nn.Sequential(*layers) 183 | 184 | def forward(self, x): 185 | x = self.conv1(x) 186 | x = self.bn1(x) 187 | x = self.relu(x) 188 | x = self.maxpool(x) 189 | 190 | x = self.layer1(x) 191 | x = self.layer2(x) 192 | x = self.layer3(x) 193 | x = self.layer4(x) 194 | 195 | x = self.avgpool(x) 196 | x = x.reshape(x.size(0), -1) 197 | # x = self.fc(x) 198 | 199 | return x, self.fc(x) 200 | 201 | 202 | def _resnet(arch, block, layers, pretrained, progress, device, **kwargs): 203 | model = ResNet(block, layers, **kwargs) 204 | if pretrained: 205 | script_dir = os.path.dirname(__file__) 206 | state_dict = torch.load(script_dir + '/state_dicts/' + arch + '.pt', map_location=device) 207 | model.load_state_dict(state_dict) 208 | return model 209 | 210 | 211 | def resnet18(pretrained=False, progress=True, device='cpu', **kwargs): 212 | """Constructs a ResNet-18 model. 213 | 214 | Args: 215 | pretrained (bool): If True, returns a model pre-trained on ImageNet 216 | progress (bool): If True, displays a progress bar of the download to stderr 217 | """ 218 | return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, device, 219 | **kwargs) 220 | 221 | 222 | def resnet34(pretrained=False, progress=True, device='cpu', **kwargs): 223 | """Constructs a ResNet-34 model. 224 | 225 | Args: 226 | pretrained (bool): If True, returns a model pre-trained on ImageNet 227 | progress (bool): If True, displays a progress bar of the download to stderr 228 | """ 229 | return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, device, 230 | **kwargs) 231 | 232 | 233 | def resnet50(pretrained=False, progress=True, device='cpu', **kwargs): 234 | """Constructs a ResNet-50 model. 235 | 236 | Args: 237 | pretrained (bool): If True, returns a model pre-trained on ImageNet 238 | progress (bool): If True, displays a progress bar of the download to stderr 239 | """ 240 | return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, device, 241 | **kwargs) 242 | 243 | 244 | def resnet101(pretrained=False, progress=True, device='cpu', **kwargs): 245 | """Constructs a ResNet-101 model. 246 | 247 | Args: 248 | pretrained (bool): If True, returns a model pre-trained on ImageNet 249 | progress (bool): If True, displays a progress bar of the download to stderr 250 | """ 251 | return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, device, 252 | **kwargs) 253 | 254 | 255 | def resnet152(pretrained=False, progress=True, device='cpu', **kwargs): 256 | """Constructs a ResNet-152 model. 257 | 258 | Args: 259 | pretrained (bool): If True, returns a model pre-trained on ImageNet 260 | progress (bool): If True, displays a progress bar of the download to stderr 261 | """ 262 | return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress, device, 263 | **kwargs) 264 | 265 | 266 | def resnext50_32x4d(pretrained=False, progress=True, device='cpu', **kwargs): 267 | """Constructs a ResNeXt-50 32x4d model. 268 | 269 | Args: 270 | pretrained (bool): If True, returns a model pre-trained on ImageNet 271 | progress (bool): If True, displays a progress bar of the download to stderr 272 | """ 273 | kwargs['groups'] = 32 274 | kwargs['width_per_group'] = 4 275 | return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], 276 | pretrained, progress, device, **kwargs) 277 | 278 | 279 | def resnext101_32x8d(pretrained=False, progress=True, device='cpu', **kwargs): 280 | """Constructs a ResNeXt-101 32x8d model. 281 | 282 | Args: 283 | pretrained (bool): If True, returns a model pre-trained on ImageNet 284 | progress (bool): If True, displays a progress bar of the download to stderr 285 | """ 286 | kwargs['groups'] = 32 287 | kwargs['width_per_group'] = 8 288 | return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], 289 | pretrained, progress, device, **kwargs) 290 | -------------------------------------------------------------------------------- /resnet_image.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | from torch.hub import load_state_dict_from_url 4 | 5 | __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 6 | 'resnet152', 'resnext50_32x4d', 'resnext101_32x8d', 7 | 'wide_resnet50_2', 'wide_resnet101_2'] 8 | 9 | model_urls = { 10 | 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth', 11 | 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth', 12 | 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth', 13 | 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth', 14 | 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth', 15 | 'resnext50_32x4d': 'https://download.pytorch.org/models/resnext50_32x4d-7cdf4587.pth', 16 | 'resnext101_32x8d': 'https://download.pytorch.org/models/resnext101_32x8d-8ba56ff5.pth', 17 | 'wide_resnet50_2': 'https://download.pytorch.org/models/wide_resnet50_2-95faca4d.pth', 18 | 'wide_resnet101_2': 'https://download.pytorch.org/models/wide_resnet101_2-32ee1156.pth', 19 | } 20 | 21 | 22 | def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): 23 | """3x3 convolution with padding""" 24 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 25 | padding=dilation, groups=groups, bias=False, dilation=dilation) 26 | 27 | 28 | def conv1x1(in_planes, out_planes, stride=1): 29 | """1x1 convolution""" 30 | return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) 31 | 32 | 33 | class BasicBlock(nn.Module): 34 | expansion = 1 35 | __constants__ = ['downsample'] 36 | 37 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 38 | base_width=64, dilation=1, norm_layer=None): 39 | super(BasicBlock, self).__init__() 40 | if norm_layer is None: 41 | norm_layer = nn.BatchNorm2d 42 | if groups != 1 or base_width != 64: 43 | raise ValueError('BasicBlock only supports groups=1 and base_width=64') 44 | if dilation > 1: 45 | raise NotImplementedError("Dilation > 1 not supported in BasicBlock") 46 | # Both self.conv1 and self.downsample layers downsample the input when stride != 1 47 | self.conv1 = conv3x3(inplanes, planes, stride) 48 | self.bn1 = norm_layer(planes) 49 | self.relu = nn.ReLU(inplace=True) 50 | self.conv2 = conv3x3(planes, planes) 51 | self.bn2 = norm_layer(planes) 52 | self.downsample = downsample 53 | self.stride = stride 54 | 55 | def forward(self, x): 56 | identity = x 57 | 58 | out = self.conv1(x) 59 | out = self.bn1(out) 60 | out = self.relu(out) 61 | 62 | out = self.conv2(out) 63 | out = self.bn2(out) 64 | 65 | if self.downsample is not None: 66 | identity = self.downsample(x) 67 | 68 | out += identity 69 | out = self.relu(out) 70 | 71 | return out 72 | 73 | 74 | class Bottleneck(nn.Module): 75 | expansion = 4 76 | __constants__ = ['downsample'] 77 | 78 | def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1, 79 | base_width=64, dilation=1, norm_layer=None): 80 | super(Bottleneck, self).__init__() 81 | if norm_layer is None: 82 | norm_layer = nn.BatchNorm2d 83 | width = int(planes * (base_width / 64.)) * groups 84 | # Both self.conv2 and self.downsample layers downsample the input when stride != 1 85 | self.conv1 = conv1x1(inplanes, width) 86 | self.bn1 = norm_layer(width) 87 | self.conv2 = conv3x3(width, width, stride, groups, dilation) 88 | self.bn2 = norm_layer(width) 89 | self.conv3 = conv1x1(width, planes * self.expansion) 90 | self.bn3 = norm_layer(planes * self.expansion) 91 | self.relu = nn.ReLU(inplace=True) 92 | self.downsample = downsample 93 | self.stride = stride 94 | 95 | def forward(self, x): 96 | identity = x 97 | 98 | out = self.conv1(x) 99 | out = self.bn1(out) 100 | out = self.relu(out) 101 | 102 | out = self.conv2(out) 103 | out = self.bn2(out) 104 | out = self.relu(out) 105 | 106 | out = self.conv3(out) 107 | out = self.bn3(out) 108 | 109 | if self.downsample is not None: 110 | identity = self.downsample(x) 111 | 112 | out += identity 113 | out = self.relu(out) 114 | 115 | return out 116 | 117 | 118 | class ResNet(nn.Module): 119 | 120 | def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, 121 | groups=1, width_per_group=64, replace_stride_with_dilation=None, 122 | norm_layer=None): 123 | super(ResNet, self).__init__() 124 | if norm_layer is None: 125 | norm_layer = nn.BatchNorm2d 126 | self._norm_layer = norm_layer 127 | 128 | self.inplanes = 64 129 | self.dilation = 1 130 | if replace_stride_with_dilation is None: 131 | # each element in the tuple indicates if we should replace 132 | # the 2x2 stride with a dilated convolution instead 133 | replace_stride_with_dilation = [False, False, False] 134 | if len(replace_stride_with_dilation) != 3: 135 | raise ValueError("replace_stride_with_dilation should be None " 136 | "or a 3-element tuple, got {}".format(replace_stride_with_dilation)) 137 | self.groups = groups 138 | self.base_width = width_per_group 139 | self.conv1 = nn.Conv2d(3, self.inplanes, kernel_size=7, stride=2, padding=3, 140 | bias=False) 141 | self.bn1 = norm_layer(self.inplanes) 142 | self.relu = nn.ReLU(inplace=True) 143 | self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) 144 | self.layer1 = self._make_layer(block, 64, layers[0]) 145 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2, 146 | dilate=replace_stride_with_dilation[0]) 147 | self.layer3 = self._make_layer(block, 256, layers[2], stride=2, 148 | dilate=replace_stride_with_dilation[1]) 149 | self.layer4 = self._make_layer(block, 512, layers[3], stride=2, 150 | dilate=replace_stride_with_dilation[2]) 151 | self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) 152 | self.fc = nn.Linear(512 * block.expansion, num_classes) 153 | 154 | for m in self.modules(): 155 | if isinstance(m, nn.Conv2d): 156 | nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') 157 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 158 | nn.init.constant_(m.weight, 1) 159 | nn.init.constant_(m.bias, 0) 160 | 161 | # Zero-initialize the last BN in each residual branch, 162 | # so that the residual branch starts with zeros, and each residual block behaves like an identity. 163 | # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 164 | if zero_init_residual: 165 | for m in self.modules(): 166 | if isinstance(m, Bottleneck): 167 | nn.init.constant_(m.bn3.weight, 0) 168 | elif isinstance(m, BasicBlock): 169 | nn.init.constant_(m.bn2.weight, 0) 170 | 171 | def _make_layer(self, block, planes, blocks, stride=1, dilate=False): 172 | norm_layer = self._norm_layer 173 | downsample = None 174 | previous_dilation = self.dilation 175 | if dilate: 176 | self.dilation *= stride 177 | stride = 1 178 | if stride != 1 or self.inplanes != planes * block.expansion: 179 | downsample = nn.Sequential( 180 | conv1x1(self.inplanes, planes * block.expansion, stride), 181 | norm_layer(planes * block.expansion), 182 | ) 183 | 184 | layers = [] 185 | layers.append(block(self.inplanes, planes, stride, downsample, self.groups, 186 | self.base_width, previous_dilation, norm_layer)) 187 | self.inplanes = planes * block.expansion 188 | for _ in range(1, blocks): 189 | layers.append(block(self.inplanes, planes, groups=self.groups, 190 | base_width=self.base_width, dilation=self.dilation, 191 | norm_layer=norm_layer)) 192 | 193 | return nn.Sequential(*layers) 194 | 195 | def _forward_impl(self, x): 196 | # See note [TorchScript super()] 197 | x = self.conv1(x) 198 | x = self.bn1(x) 199 | x = self.relu(x) 200 | x = self.maxpool(x) 201 | 202 | x = self.layer1(x) 203 | x = self.layer2(x) 204 | x = self.layer3(x) 205 | x = self.layer4(x) 206 | 207 | x = self.avgpool(x) 208 | x = torch.flatten(x, 1) 209 | # x = self.fc(x) 210 | 211 | return x, self.fc(x) 212 | 213 | def forward(self, x): 214 | return self._forward_impl(x) 215 | 216 | 217 | def _resnet(arch, block, layers, pretrained, progress, **kwargs): 218 | model = ResNet(block, layers, **kwargs) 219 | if pretrained: 220 | state_dict = load_state_dict_from_url(model_urls[arch], 221 | progress=progress) 222 | model.load_state_dict(state_dict) 223 | return model 224 | 225 | 226 | def resnet18(pretrained=False, progress=True, **kwargs): 227 | r"""ResNet-18 model from 228 | `"Deep Residual Learning for Image Recognition" `_ 229 | 230 | Args: 231 | pretrained (bool): If True, returns a model pre-trained on ImageNet 232 | progress (bool): If True, displays a progress bar of the download to stderr 233 | """ 234 | return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], pretrained, progress, 235 | **kwargs) 236 | 237 | 238 | def resnet34(pretrained=False, progress=True, **kwargs): 239 | r"""ResNet-34 model from 240 | `"Deep Residual Learning for Image Recognition" `_ 241 | 242 | Args: 243 | pretrained (bool): If True, returns a model pre-trained on ImageNet 244 | progress (bool): If True, displays a progress bar of the download to stderr 245 | """ 246 | return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], pretrained, progress, 247 | **kwargs) 248 | 249 | 250 | def resnet50(pretrained=False, progress=True, **kwargs): 251 | r"""ResNet-50 model from 252 | `"Deep Residual Learning for Image Recognition" `_ 253 | 254 | Args: 255 | pretrained (bool): If True, returns a model pre-trained on ImageNet 256 | progress (bool): If True, displays a progress bar of the download to stderr 257 | """ 258 | return _resnet('resnet50', Bottleneck, [3, 4, 6, 3], pretrained, progress, 259 | **kwargs) 260 | 261 | 262 | def resnet101(pretrained=False, progress=True, **kwargs): 263 | r"""ResNet-101 model from 264 | `"Deep Residual Learning for Image Recognition" `_ 265 | 266 | Args: 267 | pretrained (bool): If True, returns a model pre-trained on ImageNet 268 | progress (bool): If True, displays a progress bar of the download to stderr 269 | """ 270 | return _resnet('resnet101', Bottleneck, [3, 4, 23, 3], pretrained, progress, 271 | **kwargs) 272 | 273 | 274 | def resnet152(pretrained=False, progress=True, **kwargs): 275 | r"""ResNet-152 model from 276 | `"Deep Residual Learning for Image Recognition" `_ 277 | 278 | Args: 279 | pretrained (bool): If True, returns a model pre-trained on ImageNet 280 | progress (bool): If True, displays a progress bar of the download to stderr 281 | """ 282 | return _resnet('resnet152', Bottleneck, [3, 8, 36, 3], pretrained, progress, 283 | **kwargs) 284 | 285 | 286 | def resnext50_32x4d(pretrained=False, progress=True, **kwargs): 287 | r"""ResNeXt-50 32x4d model from 288 | `"Aggregated Residual Transformation for Deep Neural Networks" `_ 289 | 290 | Args: 291 | pretrained (bool): If True, returns a model pre-trained on ImageNet 292 | progress (bool): If True, displays a progress bar of the download to stderr 293 | """ 294 | kwargs['groups'] = 32 295 | kwargs['width_per_group'] = 4 296 | return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], 297 | pretrained, progress, **kwargs) 298 | 299 | 300 | def resnext101_32x8d(pretrained=False, progress=True, **kwargs): 301 | r"""ResNeXt-101 32x8d model from 302 | `"Aggregated Residual Transformation for Deep Neural Networks" `_ 303 | 304 | Args: 305 | pretrained (bool): If True, returns a model pre-trained on ImageNet 306 | progress (bool): If True, displays a progress bar of the download to stderr 307 | """ 308 | kwargs['groups'] = 32 309 | kwargs['width_per_group'] = 8 310 | return _resnet('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], 311 | pretrained, progress, **kwargs) 312 | 313 | 314 | def wide_resnet50_2(pretrained=False, progress=True, **kwargs): 315 | r"""Wide ResNet-50-2 model from 316 | `"Wide Residual Networks" `_ 317 | 318 | The model is the same as ResNet except for the bottleneck number of channels 319 | which is twice larger in every block. The number of channels in outer 1x1 320 | convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 321 | channels, and in Wide ResNet-50-2 has 2048-1024-2048. 322 | 323 | Args: 324 | pretrained (bool): If True, returns a model pre-trained on ImageNet 325 | progress (bool): If True, displays a progress bar of the download to stderr 326 | """ 327 | kwargs['width_per_group'] = 64 * 2 328 | return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3], 329 | pretrained, progress, **kwargs) 330 | 331 | 332 | def wide_resnet101_2(pretrained=False, progress=True, **kwargs): 333 | r"""Wide ResNet-101-2 model from 334 | `"Wide Residual Networks" `_ 335 | 336 | The model is the same as ResNet except for the bottleneck number of channels 337 | which is twice larger in every block. The number of channels in outer 1x1 338 | convolutions is the same, e.g. last block in ResNet-50 has 2048-512-2048 339 | channels, and in Wide ResNet-50-2 has 2048-1024-2048. 340 | 341 | Args: 342 | pretrained (bool): If True, returns a model pre-trained on ImageNet 343 | progress (bool): If True, displays a progress bar of the download to stderr 344 | """ 345 | kwargs['width_per_group'] = 64 * 2 346 | return _resnet('wide_resnet101_2', Bottleneck, [3, 4, 23, 3], 347 | pretrained, progress, **kwargs) 348 | -------------------------------------------------------------------------------- /utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch.nn.functional as F 3 | import time 4 | import resnet_image as res_image 5 | import resnet as res_cifar 6 | import resnet_cifar as res_cifar_new 7 | import torch 8 | import random 9 | import math 10 | import torch.nn as nn 11 | import torchvision 12 | import os 13 | import shutil 14 | import global_var 15 | import torch 16 | import yaml 17 | from numpy.testing import assert_array_almost_equal 18 | 19 | smp = torch.nn.Softmax(dim=0) 20 | smt = torch.nn.Softmax(dim=1) 21 | 22 | # basic function# 23 | def multiclass_noisify(y, P, random_state=0): 24 | """ Flip classes according to transition probability matrix T. 25 | It expects a number between 0 and the number of classes - 1. 26 | """ 27 | #print np.max(y), P.shape[0] 28 | assert P.shape[0] == P.shape[1] 29 | assert np.max(y) < P.shape[0] 30 | 31 | # row stochastic matrix 32 | assert_array_almost_equal(P.sum(axis=1), np.ones(P.shape[1])) 33 | assert (P >= 0.0).all() 34 | 35 | m = y.shape[0] 36 | #print m 37 | new_y = y.copy() 38 | flipper = np.random.RandomState(random_state) 39 | 40 | for idx in np.arange(m): 41 | i = y[idx] 42 | # draw a vector with only an 1 43 | flipped = flipper.multinomial(1, P[i, :][0], 1)[0] 44 | new_y[idx] = np.where(flipped == 1)[0] 45 | 46 | return new_y 47 | 48 | 49 | def distCosine(x, y): 50 | """ 51 | :param x: m x k array 52 | :param y: n x k array 53 | :return: m x n array 54 | """ 55 | xx = np.sum(x ** 2, axis=1) ** 0.5 56 | x = x / xx[:, np.newaxis] 57 | yy = np.sum(y ** 2, axis=1) ** 0.5 58 | y = y / yy[:, np.newaxis] 59 | dist = 1 - np.dot(x, y.transpose()) # 1 - cosine distance 60 | return dist 61 | 62 | def cosDistance(features): 63 | # features: N*M matrix. N features, each features is M-dimension. 64 | features = F.normalize(features, dim=1) # each feature's l2-norm should be 1 65 | similarity_matrix = torch.matmul(features, features.T) 66 | distance_matrix = 1.0 - similarity_matrix 67 | return distance_matrix 68 | 69 | def distEuclidean(x, y, squared=True): 70 | """Compute pairwise (squared) Euclidean distances. 71 | """ 72 | assert isinstance(x, np.ndarray) and x.ndim == 2 73 | assert isinstance(y, np.ndarray) and y.ndim == 2 74 | assert x.shape[1] == y.shape[1] 75 | 76 | # x_square = np.sum(x*x, axis=1, keepdims=True) 77 | x_square = np.expand_dims(np.einsum('ij,ij->i', x, x), axis=1) 78 | if x is y: 79 | y_square = x_square.T 80 | else: 81 | # y_square = np.sum(y*y, axis=1, keepdims=True).T 82 | y_square = np.expand_dims(np.einsum('ij,ij->i', y, y), axis=0) 83 | distances = np.dot(x, y.T) 84 | # use inplace operation to accelerate 85 | distances *= -2 86 | distances += x_square 87 | distances += y_square 88 | # result maybe less than 0 due to floating point rounding errors. 89 | np.maximum(distances, 0, distances) 90 | if x is y: 91 | # Ensure that distances between vectors and themselves are set to 0.0. 92 | # This may not be the case due to floating point rounding errors. 93 | distances.flat[::distances.shape[0] + 1] = 0.0 94 | if not squared: 95 | np.sqrt(distances, distances) 96 | return distances 97 | 98 | def check_T_torch(KINDS, clean_label, noisy_label): 99 | T_real = np.zeros((KINDS,KINDS)) 100 | for i in range(clean_label.shape[0]): 101 | T_real[clean_label[i]][noisy_label[i]] += 1 102 | P_real = [sum(T_real[i])*1.0 for i in range(KINDS)] # random selection 103 | for i in range(KINDS): 104 | if P_real[i]>0: 105 | T_real[i] /= P_real[i] 106 | P_real = np.array(P_real)/sum(P_real) 107 | print(f'Check: P = {P_real},\n T = \n{np.round(T_real,3)}') 108 | return T_real, P_real 109 | 110 | 111 | 112 | 113 | 114 | 115 | # def extract_sub_dataset_local_c100(origin_trans, center_idx = None, numLocal = 10000): 116 | # feat_cord0 = origin_trans[center_idx] 117 | # dist_all = torch.norm(feat_cord0.view(1,-1) - origin_trans, dim=1) 118 | # dist_s, idx = torch.sort(dist_all) 119 | # idx_sel = idx[:numLocal].detach().cpu().tolist() 120 | 121 | # return idx_sel 122 | 123 | def extract_sub_dataset_local(origin_trans, center_idx = None, numLocal = 250): 124 | feat_cord0 = origin_trans[center_idx] 125 | dist_all = torch.norm(feat_cord0.view(1,-1) - origin_trans, dim=1) 126 | dist_s, idx = torch.sort(dist_all) 127 | idx_sel = idx[:numLocal].detach().cpu().tolist() 128 | 129 | return idx_sel 130 | 131 | 132 | def extract_sub_dataset(sub_cluster_each, origin, sub_clean_dataset_name, sub_noisy_dataset_name = None): 133 | for i in range(len(sub_cluster_each)): #KINDS 134 | random.shuffle(origin[i]) 135 | origin[i] = origin[i][:sub_cluster_each[i]] 136 | 137 | for ori in origin[i]: 138 | ori['label'] = i 139 | 140 | total_len = sum([len(a) for a in origin]) 141 | 142 | origin_trans = torch.zeros(total_len,origin[0][0]['feature'].shape[0]) 143 | origin_label = torch.zeros(total_len).long() 144 | origin_index = torch.zeros(total_len).long() 145 | cnt = 0 146 | for item in origin: 147 | for i in item: 148 | origin_trans[cnt] = i['feature'] 149 | origin_label[cnt] = i['label'] 150 | origin_index[cnt] = i['index'] 151 | cnt += 1 152 | torch.save({'feature': origin_trans, 'clean_label': origin_label, 'index': origin_index},f'{sub_clean_dataset_name}') 153 | origin_dataset = torch.load(f'{sub_clean_dataset_name}') 154 | origin_dataset['noisy_label'] = origin_dataset['clean_label'].clone() 155 | torch.save(origin_dataset, f'{sub_noisy_dataset_name}') 156 | 157 | 158 | def add_noise_dataset(KINDS, sub_clean_dataset_name, sub_noisy_dataset_name, cluster_cnt, sub_cluster_each, label_list, T): 159 | origin_dataset = torch.load(f'{sub_noisy_dataset_name}') 160 | 161 | T_real = np.zeros((KINDS,KINDS)) 162 | for i in range(sum(sub_cluster_each)): 163 | origin_dataset['noisy_label'][i] = torch.tensor(np.random.choice(label_list,1,p=T[origin_dataset['clean_label'][i]])).long() 164 | T_real[origin_dataset['clean_label'][i]][origin_dataset['noisy_label'][i]] += 1 165 | P_real = [sum(T_real[i])*1.0 for i in range(KINDS)] # random selection 166 | for i in range(KINDS): 167 | if P_real[i]>0: 168 | T_real[i] /= P_real[i] 169 | P_real = np.array(P_real)/sum(P_real) 170 | torch.save(origin_dataset, f'{sub_noisy_dataset_name}') 171 | 172 | 173 | def add_noise_dataset_local(KINDS, sub_noisy_dataset_name, cluster_cnt, sub_cluster_each, label_list, T, idx_sel): 174 | origin_dataset = torch.load(f'{sub_noisy_dataset_name}') 175 | 176 | T_real = np.zeros((KINDS,KINDS)) 177 | for i in range(len(idx_sel)): 178 | origin_dataset['noisy_label'][idx_sel[i]] = torch.tensor(np.random.choice(label_list,1,p=T[origin_dataset['clean_label'][idx_sel[i]]])).long() 179 | T_real[origin_dataset['clean_label'][idx_sel[i]]][origin_dataset['noisy_label'][idx_sel[i]]] += 1 180 | P_real = [sum(T_real[i])*1.0 for i in range(KINDS)] # random selection 181 | for i in range(KINDS): 182 | if P_real[i]>0: 183 | T_real[i] /= P_real[i] 184 | P_real = np.array(P_real)/sum(P_real) 185 | torch.save(origin_dataset, f'{sub_noisy_dataset_name}') 186 | return P_real, T_real 187 | 188 | 189 | def get_feat_clusters(origin, sample): 190 | final_feat = origin['feature'][sample] 191 | noisy_label = origin['noisy_label'][sample] 192 | return final_feat, noisy_label 193 | 194 | 195 | def get_feat_clusters_local(subdataset_name, sample): 196 | origin = torch.load(f'{subdataset_name}', map_location=torch.device('cpu')) 197 | final_feat = origin['feature'][sample] 198 | noisy_label = origin['noisy_label'][sample] 199 | 200 | return 0, final_feat, noisy_label 201 | 202 | 203 | 204 | def count_real(KINDS, T, P, mode, _device = 'cpu'): 205 | # time1 = time.time() 206 | P = P.reshape((KINDS, 1)) 207 | p_real = [[] for _ in range(3)] 208 | 209 | p_real[0] = torch.mm(T.transpose(0, 1), P).transpose(0, 1) 210 | # p_real[2] = torch.zeros((KINDS, KINDS, KINDS)).to(_device) 211 | p_real[2] = torch.zeros((KINDS, KINDS, KINDS)) 212 | 213 | temp33 = torch.tensor([]) 214 | for i in range(KINDS): 215 | Ti = torch.cat((T[:, i:], T[:, :i]), 1) 216 | temp2 = torch.mm((T * Ti).transpose(0, 1), P) 217 | p_real[1] = torch.cat([p_real[1], temp2], 1) if i != 0 else temp2 218 | 219 | for j in range(KINDS): 220 | Tj = torch.cat((T[:, j:], T[:, :j]), 1) 221 | temp3 = torch.mm((T * Ti * Tj).transpose(0, 1), P) 222 | temp33 = torch.cat([temp33, temp3], 1) if j != 0 else temp3 223 | # adjust the order of the output (N*N*N), keeping consistent with p_estimate 224 | t3 = [] 225 | for p3 in range(KINDS): 226 | t3 = torch.cat((temp33[p3, KINDS - p3:], temp33[p3, :KINDS - p3])) 227 | temp33[p3] = t3 228 | if mode == -1: 229 | for r in range(KINDS): 230 | p_real[2][r][(i+r+KINDS)%KINDS] = temp33[r] 231 | else: 232 | p_real[2][mode][(i + mode + KINDS) % KINDS] = temp33[mode] 233 | 234 | 235 | temp = [] # adjust the order of the output (N*N), keeping consistent with p_estimate 236 | for p1 in range(KINDS): 237 | temp = torch.cat((p_real[1][p1, KINDS-p1:], p_real[1][p1, :KINDS-p1])) 238 | p_real[1][p1] = temp 239 | return p_real 240 | 241 | 242 | def build_T(cluster): 243 | T = [[0 for _ in range(cluster)] for _ in range(cluster)] 244 | for i in range(cluster): 245 | rand_sum = 0 246 | for j in range(cluster): 247 | if i != j: 248 | rand = round(random.uniform(0.01, 0.07), 3) 249 | rand_sum += rand 250 | T[i][j] = rand 251 | T[i][i] = 1 - rand_sum 252 | return T 253 | 254 | 255 | 256 | def build_T_local(cluster, center_class): 257 | T = [[0 for _ in range(cluster)] for _ in range(cluster)] 258 | zero_class = np.random.choice(range(cluster),int(np.sqrt(cluster)), replace = False) 259 | for i in range(cluster): 260 | rand_sum = 0 261 | for j in range(cluster): 262 | if i != j: 263 | rand = round(random.uniform(0.15, 0.25), 3) * (j in zero_class) if i == center_class else round(random.uniform(0.01, 0.07), 3) 264 | rand_sum += rand 265 | T[i][j] = rand 266 | T[i][i] = 1 - rand_sum 267 | # print(torch.tensor(T)) 268 | # exit() 269 | return T 270 | 271 | 272 | 273 | def check_T(KINDS, noisy_label, point_each_cluster): 274 | temp_error_matrix = [[0 for _ in range(KINDS)] for _ in range(KINDS)] 275 | cnt_point = 0 276 | for cnt in range(len(point_each_cluster)): 277 | for label in noisy_label[cnt_point : point_each_cluster[cnt]+cnt_point]: 278 | temp_error_matrix[cnt][label] = temp_error_matrix[cnt][label] + 1 279 | cnt_point += point_each_cluster[cnt] 280 | for i in range(KINDS): 281 | temp_sum = sum(temp_error_matrix[i]) 282 | for j in range(KINDS): 283 | temp_error_matrix[i][j] = round(temp_error_matrix[i][j]/temp_sum, 3) 284 | print(f'Check_Error_Rate = \n{np.array(temp_error_matrix)}') 285 | 286 | 287 | 288 | 289 | 290 | def select_next_idx(selected_idx, idx_sel): 291 | # selected_idx[idx_sel[:int(numLocal*0.7)]] = -1 292 | selected_idx[idx_sel] = -1 293 | if selected_idx[selected_idx > -1].size(0) > 0: 294 | next_select_idx = random.choice(selected_idx[selected_idx > 0]) # select one from the remaining part 295 | return next_select_idx, selected_idx 296 | else: 297 | return random.randint(0, 49999), selected_idx 298 | 299 | 300 | def adjust_learning_rate(optimizer, epoch,alpha_plan): 301 | for param_group in optimizer.param_groups: 302 | param_group['lr']=alpha_plan[epoch] 303 | 304 | # def accuracy(logit, target, topk=(1,)): 305 | # """Computes the precision@k for the specified values of k""" 306 | # output = F.softmax(logit, dim=1) 307 | # maxk = max(topk) 308 | # batch_size = target.size(0) 309 | 310 | # _, pred = output.topk(maxk, 1, True, True) 311 | # pred = pred.t() 312 | # correct = pred.eq(target.view(1, -1).expand_as(pred)) 313 | 314 | # res = [] 315 | # for k in topk: 316 | # correct_k = correct[:k].view(-1).float().sum(0, keepdim=True) 317 | # res.append(correct_k.mul_(100.0 / batch_size)) 318 | # return res 319 | 320 | 321 | def accuracy(output, target, topk=(1,)): 322 | """Computes the accuracy over the k top predictions for the specified values of k""" 323 | with torch.no_grad(): 324 | maxk = max(topk) 325 | batch_size = target.size(0) 326 | 327 | _, pred = output.topk(maxk, 1, True, True) 328 | pred = pred.t() 329 | correct = pred.eq(target.view(1, -1).expand_as(pred)) 330 | 331 | res = [] 332 | for k in topk: 333 | correct_k = correct[:k].reshape(-1).float().sum(0, keepdim=True) 334 | res.append(correct_k.mul_(100.0 / batch_size)) 335 | return res 336 | 337 | 338 | def save_checkpoint(state, is_best, filename='checkpoint.pth.tar'): 339 | torch.save(state, filename) 340 | if is_best: 341 | shutil.copyfile(filename, 'model_best.pth.tar') 342 | 343 | 344 | def save_config_file(model_checkpoints_folder, args): 345 | if not os.path.exists(model_checkpoints_folder): 346 | os.makedirs(model_checkpoints_folder) 347 | with open(os.path.join(model_checkpoints_folder, 'config.yml'), 'w') as outfile: 348 | yaml.dump(args, outfile, default_flow_style=False) 349 | 350 | 351 | 352 | 353 | def set_device(): 354 | if torch.cuda.is_available(): 355 | _device = torch.device("cuda") 356 | else: 357 | _device = torch.device("cpu") 358 | print(f'Current device is {_device}', flush=True) 359 | return _device 360 | 361 | def set_model_pre(config): 362 | # use resnet50 for ImageNet pretrain (PyTorch official pre-trained model) 363 | if config.pre_type == 'image': 364 | model = res_image.resnet50(pretrained=True) 365 | else: 366 | RuntimeError('Undefined pretrained model.') 367 | for param in model.parameters(): 368 | param.requires_grad = False 369 | num_ftrs = model.fc.in_features 370 | model.fc = nn.Linear(num_ftrs, config.num_classes) 371 | model.to(config.device) 372 | return model 373 | 374 | 375 | 376 | 377 | def set_model_train(config): 378 | model = res_cifar_new.ResNet34(num_classes = config.num_classes) 379 | model.to(config.device) 380 | optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=0.0005) 381 | return model, optimizer 382 | 383 | 384 | 385 | def init_feature_set(config, model_pre, train_dataloader, rnd): 386 | c1m_cluster_each = [0 for _ in range(config.num_classes)] 387 | # save the 512-dim feature as a dataset 388 | model_pre.eval() 389 | record = [[] for _ in range(config.num_classes)] 390 | 391 | for i_batch, (feature, label, index) in enumerate(train_dataloader): 392 | feature = feature.to(config.device) 393 | label = label.to(config.device) 394 | extracted_feature, _ = model_pre(feature) 395 | for i in range(extracted_feature.shape[0]): 396 | record[label[i]].append({'feature': extracted_feature[i].detach().cpu(), 'index': index[i]}) 397 | 398 | path = f'./data/{config.pre_type}_{config.dataset}_{config.label_file_path[7:-3]}.pt' 399 | return path, record, c1m_cluster_each 400 | 401 | 402 | def build_dataset_informal(config, record, c1m_cluster_each): 403 | # estimate T 404 | original_clean_dataset_name = config.path 405 | sub_clean_dataset_name = f'{config.path[:-3]}_clean.pt' 406 | sub_noisy_dataset_name = f'{config.path[:-3]}_noisy.pt' 407 | # if ~config.build_feat: 408 | # return sub_clean_dataset_name, sub_noisy_dataset_name 409 | # Build Dataset ----------------------------------------------- 410 | label_list = [i for i in range(config.num_classes)] # label-type: 0, 1, 2 ... 9 411 | P = config.P 412 | 413 | sub_cluster_each = [int(50000/config.num_classes)] * config.num_classes 414 | extract_sub_dataset(sub_cluster_each, record, sub_clean_dataset_name, 415 | sub_noisy_dataset_name) 416 | 417 | if config.label_file_path is 'NA': 418 | RuntimeError('Cannot load noisy labels.') 419 | else: 420 | # load noise file. re-format 421 | origin_dataset = torch.load(f'{sub_noisy_dataset_name}') 422 | noise_label = torch.load(config.label_file_path) 423 | 424 | T_real = np.zeros((config.num_classes,config.num_classes)) 425 | for i in range(sum(sub_cluster_each)): 426 | idx = origin_dataset['index'][i] 427 | assert origin_dataset['clean_label'][i] == noise_label['clean_label_train'][idx] 428 | origin_dataset['noisy_label'][i] = noise_label['noise_label_train'][idx].long() 429 | T_real[origin_dataset['clean_label'][i]][origin_dataset['noisy_label'][i]] += 1 430 | P_real = [sum(T_real[i])*1.0 for i in range(config.num_classes)] # random selection 431 | for i in range(config.num_classes): 432 | if P_real[i]>0: 433 | T_real[i] /= P_real[i] 434 | P_real = np.array(P_real)/sum(P_real) 435 | config.T = T_real 436 | torch.save(origin_dataset, f'{sub_noisy_dataset_name}') 437 | 438 | 439 | return sub_clean_dataset_name, sub_noisy_dataset_name -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # Creative Commons Attribution-NonCommercial 4.0 International 2 | 3 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 4 | 5 | **Using Creative Commons Public Licenses** 6 | 7 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 8 | 9 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 10 | 11 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 12 | 13 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 14 | 15 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 16 | 17 | ### Section 1 – Definitions. 18 | 19 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 20 | 21 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 22 | 23 | c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 24 | 25 | d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 26 | 27 | e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 28 | 29 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 30 | 31 | g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 32 | 33 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 34 | 35 | i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 36 | 37 | j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 38 | 39 | k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 40 | 41 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. __Your__ has a corresponding meaning. 42 | 43 | ### Section 2 – Scope. 44 | 45 | a. ___License grant.___ 46 | 47 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 48 | 49 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 50 | 51 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 52 | 53 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 54 | 55 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 56 | 57 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 58 | 59 | 5. __Downstream recipients.__ 60 | 61 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 62 | 63 | B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 64 | 65 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 66 | 67 | b. ___Other rights.___ 68 | 69 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 70 | 71 | 2. Patent and trademark rights are not licensed under this Public License. 72 | 73 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 74 | 75 | ### Section 3 – License Conditions. 76 | 77 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 78 | 79 | a. ___Attribution.___ 80 | 81 | 1. If You Share the Licensed Material (including in modified form), You must: 82 | 83 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 84 | 85 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 86 | 87 | ii. a copyright notice; 88 | 89 | iii. a notice that refers to this Public License; 90 | 91 | iv. a notice that refers to the disclaimer of warranties; 92 | 93 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 94 | 95 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 96 | 97 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 98 | 99 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 100 | 101 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 102 | 103 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 104 | 105 | ### Section 4 – Sui Generis Database Rights. 106 | 107 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 108 | 109 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 110 | 111 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 112 | 113 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 114 | 115 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 116 | 117 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 118 | 119 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 120 | 121 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 122 | 123 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 124 | 125 | ### Section 6 – Term and Termination. 126 | 127 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 128 | 129 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 130 | 131 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 132 | 133 | 2. upon express reinstatement by the Licensor. 134 | 135 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 136 | 137 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 138 | 139 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 140 | 141 | ### Section 7 – Other Terms and Conditions. 142 | 143 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 144 | 145 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 146 | 147 | ### Section 8 – Interpretation. 148 | 149 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 150 | 151 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 152 | 153 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 154 | 155 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 156 | 157 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 158 | > 159 | > Creative Commons may be contacted at creativecommons.org 160 | -------------------------------------------------------------------------------- /main_fast.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import random 3 | import time 4 | 5 | import numpy as np 6 | import torchvision.transforms as transforms 7 | 8 | 9 | import clip 10 | from data.datasets import input_dataset_clip 11 | from hoc import * 12 | import global_var 13 | 14 | # Options ---------------------------------------------------------------------- 15 | parser = argparse.ArgumentParser() 16 | parser.add_argument("--pre_type", type=str, default='CLIP') # image, cifar 17 | parser.add_argument('--noise_rate', type=float, help='corruption rate, should be less than 1', default=0.6) 18 | parser.add_argument('--noise_type', type=str, default='manual') # manual 19 | parser.add_argument('--dataset', type=str, help='cifar10, cifar100', default='cifar10') 20 | parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') 21 | parser.add_argument('--G', type=int, default=10, help='num of rounds (parameter G in Algorithm 1)') 22 | parser.add_argument('--k', type=int, default=10, help='knn') 23 | parser.add_argument('--cnt', type=int, default=15000, help='num of examples in each round') 24 | parser.add_argument('--max_iter', type=int, default=400, help='num of iterations to get a T') 25 | parser.add_argument("--local", default=False, action='store_true') 26 | parser.add_argument('--loss', type=str, help='ce, fw', default='fw') 27 | parser.add_argument('--label_file_path', type=str, help='the path of noisy labels', 28 | default='./data/noise_label_human.pt') 29 | parser.add_argument('--num_epoch', type=int, default=1, help='num of epochs') 30 | parser.add_argument('--min_similarity', type=float, help='min_similarity', default=0.0) 31 | parser.add_argument('--Tii_offset', type=float, help='Tii_offset', default=1.0) 32 | parser.add_argument('--num_classes', type=int, default=10, help='num of classes') 33 | parser.add_argument('--method', type=str, help='mv or rank1', default='rank1') 34 | 35 | 36 | def set_model_min(config): 37 | # use resnet18 (pretrained with CIFAR-10). Only for the minimum implementation of HOC 38 | print(f'Use model {config.pre_type}') 39 | if config.pre_type == 'CLIP': 40 | device = "cuda" if torch.cuda.is_available() else "cpu" 41 | model, preprocess = clip.load('ViT-B/32', device, jit=False) # RN50, RN101, RN50x4, ViT-B/32 42 | return model, preprocess 43 | 44 | else: 45 | 46 | if config.pre_type == 'image18': 47 | model = res_image.resnet18(pretrained=True) 48 | elif config.pre_type == 'image34': 49 | model = res_image.resnet34(pretrained=True) 50 | elif config.pre_type == 'image50': 51 | model = res_image.resnet50(pretrained=True) 52 | else: 53 | RuntimeError('Undefined pretrained model.') 54 | for param in model.parameters(): 55 | param.requires_grad = False 56 | if 'image' in config.pre_type: 57 | num_ftrs = model.fc.in_features 58 | model.fc = nn.Linear(num_ftrs, config.num_classes) 59 | model.to(config.device) 60 | return model, None 61 | 62 | 63 | def data_transform(record, noise_or_not, sel_noisy): 64 | # assert noise_or_not is not None 65 | total_len = sum([len(a) for a in record]) 66 | origin_trans = torch.zeros(total_len, record[0][0]['feature'].shape[0]) 67 | origin_label = torch.zeros(total_len).long() 68 | noise_or_not_reorder = np.empty(total_len, dtype=bool) 69 | index_rec = np.zeros(total_len, dtype=int) 70 | cnt, lb = 0, 0 71 | sel_noisy = np.array(sel_noisy) 72 | noisy_prior = np.zeros(len(record)) 73 | 74 | for item in record: 75 | for i in item: 76 | # if i['index'] not in sel_noisy: 77 | origin_trans[cnt] = i['feature'] 78 | origin_label[cnt] = lb 79 | noise_or_not_reorder[cnt] = noise_or_not[i['index']] if noise_or_not is not None else False 80 | index_rec[cnt] = i['index'] 81 | cnt += 1 - np.sum(sel_noisy == i['index'].item()) 82 | # print(cnt) 83 | noisy_prior[lb] = cnt - np.sum(noisy_prior) 84 | lb += 1 85 | data_set = {'feature': origin_trans[:cnt], 'noisy_label': origin_label[:cnt], 86 | 'noise_or_not': noise_or_not_reorder[:cnt], 'index': index_rec[:cnt]} 87 | return data_set, noisy_prior / cnt 88 | 89 | 90 | def get_knn_acc_all_class(args, data_set, k=10, noise_prior=None, sel_noisy=None, thre_noise_rate=0.5, thre_true=None): 91 | # Build Feature Clusters -------------------------------------- 92 | KINDS = args.num_classes 93 | 94 | all_point_cnt = data_set['feature'].shape[0] 95 | # global 96 | sample = np.random.choice(np.arange(data_set['feature'].shape[0]), all_point_cnt, replace=False) 97 | # final_feat, noisy_label = get_feat_clusters(data_set, sample) 98 | final_feat = data_set['feature'][sample] 99 | noisy_label = data_set['noisy_label'][sample] 100 | noise_or_not_sample = data_set['noise_or_not'][sample] 101 | sel_idx = data_set['index'][sample] 102 | knn_labels_cnt = count_knn_distribution(args, final_feat, noisy_label, all_point_cnt, k=k, norm='l2') 103 | 104 | 105 | method = 'ce' 106 | # time_score = time.time() 107 | score = get_score(knn_labels_cnt, noisy_label, k=k, method=method, prior=noise_prior) # method = ['cores', 'peer'] 108 | # print(f'time for get_score is {time.time()-time_score}') 109 | score_np = score.cpu().numpy() 110 | 111 | if args.method == 'mv': 112 | # test majority voting 113 | print(f'Use MV') 114 | label_pred = np.argmax(knn_labels_cnt, axis=1).reshape(-1) 115 | sel_noisy += (sel_idx[label_pred != noisy_label]).tolist() 116 | elif args.method == 'rank1': 117 | print(f'Use rank1') 118 | print(f'Tii offset is {args.Tii_offset}') 119 | # fig=plt.figure(figsize=(15,4)) 120 | for sel_class in range(KINDS): 121 | thre_noise_rate_per_class = 1 - min(args.Tii_offset * thre_noise_rate[sel_class][sel_class], 1.0) 122 | if thre_noise_rate_per_class >= 1.0: 123 | thre_noise_rate_per_class = 0.95 124 | elif thre_noise_rate_per_class <= 0.0: 125 | thre_noise_rate_per_class = 0.05 126 | sel_labels = (noisy_label.cpu().numpy() == sel_class) 127 | thre = np.percentile(score_np[sel_labels], 100 * (1 - thre_noise_rate_per_class)) 128 | 129 | indicator_all_tail = (score_np >= thre) * (sel_labels) 130 | sel_noisy += sel_idx[indicator_all_tail].tolist() 131 | else: 132 | raise NameError('Undefined method') 133 | 134 | return sel_noisy 135 | 136 | # plot_score(score, name = f'{args.noise_type}_{args.noise_rate}_{k}_{method}', noise_or_not_sample = noise_or_not_sample, thre_noise_rate = thre_noise_rate, sel_class = sel_class) 137 | 138 | # method = 'avg' 139 | # score = get_score(knn_labels_cnt, noisy_label, k = k, method = method, prior = noise_prior) # method = ['cores', 'peer'] 140 | # plot_score(score, name = f'{args.noise_type}_{args.noise_rate}_{k}_{method}', noise_or_not_sample = noise_or_not_sample) 141 | # method = 'new' 142 | # score = get_score(knn_labels_cnt, noisy_label, k = k, method = method, prior = noise_prior) # method = ['cores', 'peer'] 143 | # plot_score(score, name = f'{args.noise_type}_{args.noise_rate}_{k}_{method}', noise_or_not_sample = noise_or_not_sample) 144 | # exit() 145 | 146 | 147 | def get_T_global_min_new(args, data_set, max_step=501, T0=None, p0=None, lr=0.1, NumTest=50, all_point_cnt=15000): 148 | 149 | 150 | # Build Feature Clusters -------------------------------------- 151 | KINDS = args.num_classes 152 | # NumTest = 50 153 | all_point_cnt = args.cnt 154 | print(f'Use {all_point_cnt} in each round. Total rounds {NumTest}.') 155 | 156 | p_estimate = [[] for _ in range(3)] 157 | p_estimate[0] = torch.zeros(KINDS) 158 | p_estimate[1] = torch.zeros(KINDS, KINDS) 159 | p_estimate[2] = torch.zeros(KINDS, KINDS, KINDS) 160 | # p_estimate_rec = torch.zeros(NumTest, 3) 161 | for idx in range(NumTest): 162 | # print(idx, flush=True) 163 | # global 164 | sample = np.random.choice(range(data_set['feature'].shape[0]), all_point_cnt, replace=False) 165 | # final_feat, noisy_label = get_feat_clusters(data_set, sample) 166 | final_feat = data_set['feature'][sample] 167 | noisy_label = data_set['noisy_label'][sample] 168 | cnt_y_3 = count_y(KINDS, final_feat, noisy_label, all_point_cnt) 169 | for i in range(3): 170 | cnt_y_3[i] /= all_point_cnt 171 | p_estimate[i] = p_estimate[i] + cnt_y_3[i] if idx != 0 else cnt_y_3[i] 172 | 173 | for j in range(3): 174 | p_estimate[j] = p_estimate[j] / NumTest 175 | 176 | args.device = set_device() 177 | loss_min, E_calc, P_calc, _ = calc_func(KINDS, p_estimate, False, args.device, max_step, T0, p0, lr=lr) 178 | E_calc = E_calc.cpu().numpy() 179 | P_calc = P_calc.cpu().numpy() 180 | return E_calc, P_calc 181 | 182 | 183 | # def error(T, T_true): 184 | # error = np.sum(np.abs(T - T_true)) / np.sum(np.abs(T_true)) 185 | # return error 186 | 187 | 188 | def noniterate_detection(config, record, train_dataset, sel_noisy=[]): 189 | 190 | T_given_noisy_true = None 191 | T_given_noisy = None 192 | 193 | 194 | # non-iterate 195 | # sel_noisy = [] 196 | data_set, noisy_prior = data_transform(record, train_dataset.noise_or_not, sel_noisy) 197 | # print(data_set['noisy_label']) 198 | if config.method == 'rank1': 199 | T_init = global_var.get_value('T_init') 200 | p_init = global_var.get_value('p_init') 201 | 202 | # print(f'T_init is {T_init}') 203 | T, p = get_T_global_min_new(config, data_set=data_set, max_step=config.max_iter if T_init is None else 20, 204 | lr=0.1 if T_init is None else 0.01, NumTest=config.G, T0=T_init, p0=p_init) 205 | 206 | 207 | T_given_noisy = T * p / noisy_prior 208 | print("T given noisy:") 209 | print(np.round(T_given_noisy, 2)) 210 | # add randomness 211 | for i in range(T.shape[0]): 212 | T_given_noisy[i][i] += np.random.uniform(low=-0.05, high=0.05) 213 | 214 | 215 | sel_noisy = get_knn_acc_all_class(config, data_set, k=config.k, noise_prior=noisy_prior, sel_noisy=sel_noisy, 216 | thre_noise_rate=T_given_noisy, thre_true=T_given_noisy_true) 217 | 218 | sel_noisy = np.array(sel_noisy) 219 | sel_clean = np.array(list(set(data_set['index'].tolist()) ^ set(sel_noisy))) 220 | 221 | noisy_in_sel_noisy = np.sum(train_dataset.noise_or_not[sel_noisy]) / sel_noisy.shape[0] 222 | precision_noisy = noisy_in_sel_noisy 223 | recall_noisy = np.sum(train_dataset.noise_or_not[sel_noisy]) / np.sum(train_dataset.noise_or_not) 224 | 225 | 226 | print(f'[noisy] precision: {precision_noisy}') 227 | print(f'[noisy] recall: {recall_noisy}') 228 | print(f'[noisy] F1-score: {2.0 * precision_noisy * recall_noisy / (precision_noisy + recall_noisy)}') 229 | 230 | return sel_noisy, sel_clean, data_set['index'] 231 | 232 | 233 | if __name__ == "__main__": 234 | 235 | # Setup ------------------------------------------------------------------------ 236 | torch.multiprocessing.set_sharing_strategy('file_system') 237 | config = parser.parse_args() 238 | config.device = set_device() 239 | torch.manual_seed(config.seed) 240 | np.random.seed(config.seed) 241 | random.seed(config.seed) 242 | model_pre, preprocess = set_model_min(config) 243 | if config.noise_type in ['clean', 'worst', 'aggre', 'rand1', 'rand2', 'rand3', 'clean100', 'noisy100']: 244 | noise_type_map = {'clean': 'clean_label', 'worst': 'worse_label', 'aggre': 'aggre_label', 245 | 'rand1': 'random_label1', 'rand2': 'random_label2', 'rand3': 'random_label3', 246 | 'clean100': 'clean_label', 'noisy100': 'noisy_label'} 247 | config.noise_type = noise_type_map[config.noise_type] 248 | 249 | # set transforms 250 | if config.dataset in ['cifar10', 'cifar100']: 251 | crop = transforms.RandomCrop(32, padding=4) 252 | normalize = transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)) 253 | elif config.dataset in ['stl10']: 254 | crop = transforms.RandomCrop(96, padding=12) 255 | normalize = transforms.Normalize((0.44671097, 0.4398105, 0.4066468), (0.2603405, 0.25657743, 0.27126738)) 256 | else: 257 | raise NameError('Undefined dataset') 258 | 259 | if config.pre_type == "CLIP": 260 | preprocess_rand = transforms.Compose([crop, 261 | transforms.RandomHorizontalFlip(), 262 | preprocess]) 263 | elif 'image' in config.pre_type: 264 | preprocess_rand = transforms.Compose([crop, 265 | transforms.RandomHorizontalFlip(), 266 | transforms.Resize(224), 267 | transforms.ToTensor(), 268 | normalize]) 269 | else: # cifar pretrain 270 | preprocess_rand = transforms.Compose([crop, 271 | transforms.Resize(32), 272 | transforms.RandomHorizontalFlip(), 273 | transforms.ToTensor(), 274 | normalize]) 275 | 276 | # load dataset 277 | train_dataset, _, num_classes, num_training_samples, _ = input_dataset_clip(config.dataset, config.noise_type, 278 | config.noise_rate, 279 | transform=preprocess_rand, 280 | noise_file=config.label_file_path) 281 | config.num_classes = num_classes 282 | config.num_training_samples = num_training_samples 283 | print(f'num_training_samples is {num_training_samples}') 284 | 285 | sel_noisy_rec = [] 286 | # for config.cnt in [5000, 15000, 50000]: 287 | for loop_i in range(1): 288 | train_dataloader_EF = torch.utils.data.DataLoader(train_dataset, 289 | batch_size=256, 290 | shuffle=True, 291 | num_workers=4, 292 | drop_last=False) 293 | model_pre.eval() 294 | 295 | sel_clean_rec = np.zeros((config.num_epoch, num_training_samples)) 296 | sel_times_rec = np.zeros(num_training_samples) 297 | global_var._init() 298 | global_var.set_value('T_init', None) 299 | global_var.set_value('p_init', None) 300 | for epoch in range(config.num_epoch): 301 | print(f'Epoch {epoch}') 302 | 303 | record = [[] for _ in range(config.num_classes)] 304 | 305 | for i_batch, (feature, label, index) in enumerate(train_dataloader_EF): 306 | feature = feature.to(config.device) 307 | label = label.to(config.device) 308 | with torch.no_grad(): 309 | if config.pre_type == "CLIP": 310 | extracted_feature = model_pre.encode_image(feature) 311 | elif 'ssl' in config.pre_type: 312 | extracted_feature, _ = model_pre(feature) 313 | else: 314 | extracted_feature, _ = model_pre(feature) 315 | for i in range(extracted_feature.shape[0]): 316 | record[label[i]].append({'feature': extracted_feature[i].detach().cpu(), 'index': index[i]}) 317 | if i_batch > 200: 318 | break 319 | 320 | time1 = time.time() 321 | 322 | if config.method == 'both': 323 | # rank1 + mv 324 | config.method = 'rank1' 325 | sel_noisy, sel_clean, sel_idx = noniterate_detection(config, record, train_dataset, 326 | sel_noisy=sel_noisy_rec.copy()) 327 | sel_clean_rec[epoch][np.array(sel_clean)] += 0.5 328 | sel_times_rec[np.array(sel_idx)] += 0.5 329 | config.method = 'mv' 330 | sel_noisy, sel_clean, sel_idx = noniterate_detection(config, record, train_dataset, 331 | sel_noisy=sel_noisy_rec.copy()) 332 | sel_clean_rec[epoch][np.array(sel_clean)] += 0.5 333 | config.method = 'both' 334 | sel_times_rec[np.array(sel_idx)] += 0.5 335 | else: 336 | # use one method 337 | sel_noisy, sel_clean, sel_idx = noniterate_detection(config, record, train_dataset, 338 | sel_noisy=sel_noisy_rec.copy()) 339 | if config.num_epoch > 1: 340 | sel_clean_rec[epoch][np.array(sel_clean)] = 1 341 | sel_times_rec[np.array(sel_idx)] += 1 342 | 343 | 344 | print(f'Time for one detection is {time.time() - time1}') 345 | 346 | # config.method = 'rank1' 347 | if epoch % 1 == 0: 348 | # config.method = 'mv' 349 | aa = np.sum(sel_clean_rec[:epoch + 1], 0) / sel_times_rec 350 | nan_flag = np.isnan(aa) 351 | aa[nan_flag] = 0 352 | # aa += 0.1 353 | 354 | sel_clean_summary = np.round(aa).astype(bool) 355 | sel_noisy_summary = np.round(1.0 - aa).astype(bool) 356 | sel_noisy_summary[nan_flag] = False 357 | print( 358 | f'We find {sel_clean_summary.shape[0] - np.sum(sel_clean_summary) - np.sum(nan_flag * 1)} corrupted instances from {sel_clean_summary.shape[0] - np.sum(nan_flag * 1)} instances') 359 | 360 | # noisy 361 | noisy_in_sel_noisy = np.sum(train_dataset.noise_or_not[sel_noisy_summary]) / np.sum(sel_noisy_summary) 362 | precision_noisy = noisy_in_sel_noisy 363 | recall_noisy = np.sum(train_dataset.noise_or_not[sel_noisy_summary]) / np.sum( 364 | train_dataset.noise_or_not[(1 - nan_flag).astype(bool)]) 365 | 366 | print(f'[Epoch {epoch + 1}] precision noisy: {precision_noisy}') 367 | print(f'[Epoch {epoch + 1}] recall noisy: {recall_noisy}') 368 | print( 369 | f'[Epoch {epoch + 1}] F1-score noisy: {2.0 * precision_noisy * recall_noisy / (precision_noisy + recall_noisy)}') 370 | torch.save(sel_clean_rec, 371 | f'result_{config.pre_type}_{config.method}_{config.dataset}_{config.noise_type}_e{config.num_epoch}_k{config.k}.pt') 372 | -------------------------------------------------------------------------------- /clip/model.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | from typing import Tuple, Union 3 | 4 | import numpy as np 5 | import torch 6 | import torch.nn.functional as F 7 | from torch import nn 8 | 9 | 10 | class Bottleneck(nn.Module): 11 | expansion = 4 12 | 13 | def __init__(self, inplanes, planes, stride=1): 14 | super().__init__() 15 | 16 | # all conv layers have stride 1. an avgpool is performed after the second convolution when stride > 1 17 | self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False) 18 | self.bn1 = nn.BatchNorm2d(planes) 19 | 20 | self.conv2 = nn.Conv2d(planes, planes, 3, padding=1, bias=False) 21 | self.bn2 = nn.BatchNorm2d(planes) 22 | 23 | self.avgpool = nn.AvgPool2d(stride) if stride > 1 else nn.Identity() 24 | 25 | self.conv3 = nn.Conv2d(planes, planes * self.expansion, 1, bias=False) 26 | self.bn3 = nn.BatchNorm2d(planes * self.expansion) 27 | 28 | self.relu = nn.ReLU(inplace=True) 29 | self.downsample = None 30 | self.stride = stride 31 | 32 | if stride > 1 or inplanes != planes * Bottleneck.expansion: 33 | # downsampling layer is prepended with an avgpool, and the subsequent convolution has stride 1 34 | self.downsample = nn.Sequential(OrderedDict([ 35 | ("-1", nn.AvgPool2d(stride)), 36 | ("0", nn.Conv2d(inplanes, planes * self.expansion, 1, stride=1, bias=False)), 37 | ("1", nn.BatchNorm2d(planes * self.expansion)) 38 | ])) 39 | 40 | def forward(self, x: torch.Tensor): 41 | identity = x 42 | 43 | out = self.relu(self.bn1(self.conv1(x))) 44 | out = self.relu(self.bn2(self.conv2(out))) 45 | out = self.avgpool(out) 46 | out = self.bn3(self.conv3(out)) 47 | 48 | if self.downsample is not None: 49 | identity = self.downsample(x) 50 | 51 | out += identity 52 | out = self.relu(out) 53 | return out 54 | 55 | 56 | class AttentionPool2d(nn.Module): 57 | def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None): 58 | super().__init__() 59 | self.positional_embedding = nn.Parameter(torch.randn(spacial_dim ** 2 + 1, embed_dim) / embed_dim ** 0.5) 60 | self.k_proj = nn.Linear(embed_dim, embed_dim) 61 | self.q_proj = nn.Linear(embed_dim, embed_dim) 62 | self.v_proj = nn.Linear(embed_dim, embed_dim) 63 | self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim) 64 | self.num_heads = num_heads 65 | 66 | def forward(self, x): 67 | x = x.reshape(x.shape[0], x.shape[1], x.shape[2] * x.shape[3]).permute(2, 0, 1) # NCHW -> (HW)NC 68 | x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (HW+1)NC 69 | x = x + self.positional_embedding[:, None, :].to(x.dtype) # (HW+1)NC 70 | x, _ = F.multi_head_attention_forward( 71 | query=x, key=x, value=x, 72 | embed_dim_to_check=x.shape[-1], 73 | num_heads=self.num_heads, 74 | q_proj_weight=self.q_proj.weight, 75 | k_proj_weight=self.k_proj.weight, 76 | v_proj_weight=self.v_proj.weight, 77 | in_proj_weight=None, 78 | in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]), 79 | bias_k=None, 80 | bias_v=None, 81 | add_zero_attn=False, 82 | dropout_p=0, 83 | out_proj_weight=self.c_proj.weight, 84 | out_proj_bias=self.c_proj.bias, 85 | use_separate_proj_weight=True, 86 | training=self.training, 87 | need_weights=False 88 | ) 89 | 90 | return x[0] 91 | 92 | 93 | class ModifiedResNet(nn.Module): 94 | """ 95 | A ResNet class that is similar to torchvision's but contains the following changes: 96 | - There are now 3 "stem" convolutions as opposed to 1, with an average pool instead of a max pool. 97 | - Performs anti-aliasing strided convolutions, where an avgpool is prepended to convolutions with stride > 1 98 | - The final pooling layer is a QKV attention instead of an average pool 99 | """ 100 | 101 | def __init__(self, layers, output_dim, heads, input_resolution=224, width=64): 102 | super().__init__() 103 | self.output_dim = output_dim 104 | self.input_resolution = input_resolution 105 | 106 | # the 3-layer stem 107 | self.conv1 = nn.Conv2d(3, width // 2, kernel_size=3, stride=2, padding=1, bias=False) 108 | self.bn1 = nn.BatchNorm2d(width // 2) 109 | self.conv2 = nn.Conv2d(width // 2, width // 2, kernel_size=3, padding=1, bias=False) 110 | self.bn2 = nn.BatchNorm2d(width // 2) 111 | self.conv3 = nn.Conv2d(width // 2, width, kernel_size=3, padding=1, bias=False) 112 | self.bn3 = nn.BatchNorm2d(width) 113 | self.avgpool = nn.AvgPool2d(2) 114 | self.relu = nn.ReLU(inplace=True) 115 | 116 | # residual layers 117 | self._inplanes = width # this is a *mutable* variable used during construction 118 | self.layer1 = self._make_layer(width, layers[0]) 119 | self.layer2 = self._make_layer(width * 2, layers[1], stride=2) 120 | self.layer3 = self._make_layer(width * 4, layers[2], stride=2) 121 | self.layer4 = self._make_layer(width * 8, layers[3], stride=2) 122 | 123 | embed_dim = width * 32 # the ResNet feature dimension 124 | self.attnpool = AttentionPool2d(input_resolution // 32, embed_dim, heads, output_dim) 125 | 126 | def _make_layer(self, planes, blocks, stride=1): 127 | layers = [Bottleneck(self._inplanes, planes, stride)] 128 | 129 | self._inplanes = planes * Bottleneck.expansion 130 | for _ in range(1, blocks): 131 | layers.append(Bottleneck(self._inplanes, planes)) 132 | 133 | return nn.Sequential(*layers) 134 | 135 | def forward(self, x): 136 | def stem(x): 137 | for conv, bn in [(self.conv1, self.bn1), (self.conv2, self.bn2), (self.conv3, self.bn3)]: 138 | x = self.relu(bn(conv(x))) 139 | x = self.avgpool(x) 140 | return x 141 | 142 | x = x.type(self.conv1.weight.dtype) 143 | x = stem(x) 144 | x = self.layer1(x) 145 | x = self.layer2(x) 146 | x = self.layer3(x) 147 | x = self.layer4(x) 148 | x = self.attnpool(x) 149 | 150 | return x 151 | 152 | 153 | class LayerNorm(nn.LayerNorm): 154 | """Subclass torch's LayerNorm to handle fp16.""" 155 | 156 | def forward(self, x: torch.Tensor): 157 | orig_type = x.dtype 158 | ret = super().forward(x.type(torch.float32)) 159 | return ret.type(orig_type) 160 | 161 | 162 | class QuickGELU(nn.Module): 163 | def forward(self, x: torch.Tensor): 164 | return x * torch.sigmoid(1.702 * x) 165 | 166 | 167 | class ResidualAttentionBlock(nn.Module): 168 | def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None): 169 | super().__init__() 170 | 171 | self.attn = nn.MultiheadAttention(d_model, n_head) 172 | self.ln_1 = LayerNorm(d_model) 173 | self.mlp = nn.Sequential(OrderedDict([ 174 | ("c_fc", nn.Linear(d_model, d_model * 4)), 175 | ("gelu", QuickGELU()), 176 | ("c_proj", nn.Linear(d_model * 4, d_model)) 177 | ])) 178 | self.ln_2 = LayerNorm(d_model) 179 | self.attn_mask = attn_mask 180 | 181 | def attention(self, x: torch.Tensor): 182 | self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None 183 | return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0] 184 | 185 | def forward(self, x: torch.Tensor): 186 | x = x + self.attention(self.ln_1(x)) 187 | x = x + self.mlp(self.ln_2(x)) 188 | return x 189 | 190 | 191 | class Transformer(nn.Module): 192 | def __init__(self, width: int, layers: int, heads: int, attn_mask: torch.Tensor = None): 193 | super().__init__() 194 | self.width = width 195 | self.layers = layers 196 | self.resblocks = nn.Sequential(*[ResidualAttentionBlock(width, heads, attn_mask) for _ in range(layers)]) 197 | 198 | def forward(self, x: torch.Tensor): 199 | return self.resblocks(x) 200 | 201 | 202 | class VisualTransformer(nn.Module): 203 | def __init__(self, input_resolution: int, patch_size: int, width: int, layers: int, heads: int, output_dim: int): 204 | super().__init__() 205 | self.input_resolution = input_resolution 206 | self.output_dim = output_dim 207 | self.conv1 = nn.Conv2d(in_channels=3, out_channels=width, kernel_size=patch_size, stride=patch_size, bias=False) 208 | 209 | scale = width ** -0.5 210 | self.class_embedding = nn.Parameter(scale * torch.randn(width)) 211 | self.positional_embedding = nn.Parameter(scale * torch.randn((input_resolution // patch_size) ** 2 + 1, width)) 212 | self.ln_pre = LayerNorm(width) 213 | 214 | self.transformer = Transformer(width, layers, heads) 215 | 216 | self.ln_post = LayerNorm(width) 217 | self.proj = nn.Parameter(scale * torch.randn(width, output_dim)) 218 | 219 | def forward(self, x: torch.Tensor): 220 | x = self.conv1(x) # shape = [*, width, grid, grid] 221 | x = x.reshape(x.shape[0], x.shape[1], -1) # shape = [*, width, grid ** 2] 222 | x = x.permute(0, 2, 1) # shape = [*, grid ** 2, width] 223 | x = torch.cat( 224 | [self.class_embedding.to(x.dtype) + torch.zeros(x.shape[0], 1, x.shape[-1], dtype=x.dtype, device=x.device), 225 | x], dim=1) # shape = [*, grid ** 2 + 1, width] 226 | x = x + self.positional_embedding.to(x.dtype) 227 | x = self.ln_pre(x) 228 | 229 | x = x.permute(1, 0, 2) # NLD -> LND 230 | x = self.transformer(x) 231 | x = x.permute(1, 0, 2) # LND -> NLD 232 | 233 | x = self.ln_post(x[:, 0, :]) 234 | 235 | if self.proj is not None: 236 | x = x @ self.proj 237 | 238 | return x 239 | 240 | 241 | class CLIP(nn.Module): 242 | def __init__(self, 243 | embed_dim: int, 244 | # vision 245 | image_resolution: int, 246 | vision_layers: Union[Tuple[int, int, int, int], int], 247 | vision_width: int, 248 | vision_patch_size: int, 249 | # text 250 | context_length: int, 251 | vocab_size: int, 252 | transformer_width: int, 253 | transformer_heads: int, 254 | transformer_layers: int 255 | ): 256 | super().__init__() 257 | 258 | self.context_length = context_length 259 | 260 | if isinstance(vision_layers, (tuple, list)): 261 | vision_heads = vision_width * 32 // 64 262 | self.visual = ModifiedResNet( 263 | layers=vision_layers, 264 | output_dim=embed_dim, 265 | heads=vision_heads, 266 | input_resolution=image_resolution, 267 | width=vision_width 268 | ) 269 | else: 270 | vision_heads = vision_width // 64 271 | self.visual = VisualTransformer( 272 | input_resolution=image_resolution, 273 | patch_size=vision_patch_size, 274 | width=vision_width, 275 | layers=vision_layers, 276 | heads=vision_heads, 277 | output_dim=embed_dim 278 | ) 279 | 280 | self.transformer = Transformer( 281 | width=transformer_width, 282 | layers=transformer_layers, 283 | heads=transformer_heads, 284 | attn_mask=self.build_attention_mask() 285 | ) 286 | 287 | self.vocab_size = vocab_size 288 | self.token_embedding = nn.Embedding(vocab_size, transformer_width) 289 | self.positional_embedding = nn.Parameter(torch.empty(self.context_length, transformer_width)) 290 | self.ln_final = LayerNorm(transformer_width) 291 | 292 | self.text_projection = nn.Parameter(torch.empty(transformer_width, embed_dim)) 293 | self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07)) 294 | 295 | self.initialize_parameters() 296 | 297 | def initialize_parameters(self): 298 | nn.init.normal_(self.token_embedding.weight, std=0.02) 299 | nn.init.normal_(self.positional_embedding, std=0.01) 300 | 301 | if isinstance(self.visual, ModifiedResNet): 302 | if self.visual.attnpool is not None: 303 | std = self.visual.attnpool.c_proj.in_features ** -0.5 304 | nn.init.normal_(self.visual.attnpool.q_proj.weight, std=std) 305 | nn.init.normal_(self.visual.attnpool.k_proj.weight, std=std) 306 | nn.init.normal_(self.visual.attnpool.v_proj.weight, std=std) 307 | nn.init.normal_(self.visual.attnpool.c_proj.weight, std=std) 308 | 309 | for resnet_block in [self.visual.layer1, self.visual.layer2, self.visual.layer3, self.visual.layer4]: 310 | for name, param in resnet_block.named_parameters(): 311 | if name.endswith("bn3.weight"): 312 | nn.init.zeros_(param) 313 | 314 | proj_std = (self.transformer.width ** -0.5) * ((2 * self.transformer.layers) ** -0.5) 315 | attn_std = self.transformer.width ** -0.5 316 | fc_std = (2 * self.transformer.width) ** -0.5 317 | for block in self.transformer.resblocks: 318 | nn.init.normal_(block.attn.in_proj_weight, std=attn_std) 319 | nn.init.normal_(block.attn.out_proj.weight, std=proj_std) 320 | nn.init.normal_(block.mlp.c_fc.weight, std=fc_std) 321 | nn.init.normal_(block.mlp.c_proj.weight, std=proj_std) 322 | 323 | if self.text_projection is not None: 324 | nn.init.normal_(self.text_projection, std=self.transformer.width ** -0.5) 325 | 326 | def build_attention_mask(self): 327 | # lazily create causal attention mask, with full attention between the vision tokens 328 | # pytorch uses additive attention mask; fill with -inf 329 | mask = torch.empty(self.context_length, self.context_length) 330 | mask.fill_(float("-inf")) 331 | mask.triu_(1) # zero out the lower diagonal 332 | return mask 333 | 334 | @property 335 | def dtype(self): 336 | return self.visual.conv1.weight.dtype 337 | 338 | def encode_image(self, image): 339 | return self.visual(image.type(self.dtype)) 340 | 341 | def encode_text(self, text): 342 | x = self.token_embedding(text).type(self.dtype) # [batch_size, n_ctx, d_model] 343 | 344 | x = x + self.positional_embedding.type(self.dtype) 345 | x = x.permute(1, 0, 2) # NLD -> LND 346 | x = self.transformer(x) 347 | x = x.permute(1, 0, 2) # LND -> NLD 348 | x = self.ln_final(x).type(self.dtype) 349 | 350 | # x.shape = [batch_size, n_ctx, transformer.width] 351 | # take features from the eot embedding (eot_token is the highest number in each sequence) 352 | x = x[torch.arange(x.shape[0]), text.argmax(dim=-1)] @ self.text_projection 353 | 354 | return x 355 | 356 | def forward(self, image, text): 357 | image_features = self.encode_image(image) 358 | text_features = self.encode_text(text) 359 | 360 | # normalized features 361 | image_features = image_features / image_features.norm(dim=-1, keepdim=True) 362 | text_features = text_features / text_features.norm(dim=-1, keepdim=True) 363 | 364 | # cosine similarity as logits 365 | logit_scale = self.logit_scale.exp() 366 | logits_per_image = logit_scale * image_features @ text_features.t() 367 | logits_per_text = logit_scale * text_features @ image_features.t() 368 | 369 | # shape = [global_batch_size, global_batch_size] 370 | return logits_per_image, logits_per_text 371 | 372 | 373 | def convert_weights(model: nn.Module): 374 | """Convert applicable model parameters to fp16""" 375 | 376 | def _convert_weights_to_fp16(l): 377 | if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Linear)): 378 | l.weight.data = l.weight.data.half() 379 | if l.bias is not None: 380 | l.bias.data = l.bias.data.half() 381 | 382 | if isinstance(l, nn.MultiheadAttention): 383 | for attr in [*[f"{s}_proj_weight" for s in ["in", "q", "k", "v"]], "in_proj_bias", "bias_k", "bias_v"]: 384 | tensor = getattr(l, attr) 385 | if tensor is not None: 386 | tensor.data = tensor.data.half() 387 | 388 | for name in ["text_projection", "proj"]: 389 | if hasattr(l, name): 390 | attr = getattr(l, name) 391 | if attr is not None: 392 | attr.data = attr.data.half() 393 | 394 | model.apply(_convert_weights_to_fp16) 395 | 396 | 397 | def build_model(state_dict: dict): 398 | vit = "visual.proj" in state_dict 399 | 400 | if vit: 401 | vision_width = state_dict["visual.conv1.weight"].shape[0] 402 | vision_layers = len( 403 | [k for k in state_dict.keys() if k.startswith("visual.") and k.endswith(".attn.in_proj_weight")]) 404 | vision_patch_size = state_dict["visual.conv1.weight"].shape[-1] 405 | grid_size = round((state_dict["visual.positional_embedding"].shape[0] - 1) ** 0.5) 406 | image_resolution = vision_patch_size * grid_size 407 | else: 408 | counts: list = [len(set(k.split(".")[2] for k in state_dict if k.startswith(f"visual.layer{b}"))) for b in 409 | [1, 2, 3, 4]] 410 | vision_layers = tuple(counts) 411 | vision_width = state_dict["visual.layer1.0.conv1.weight"].shape[0] 412 | output_width = round((state_dict["visual.attnpool.positional_embedding"].shape[0] - 1) ** 0.5) 413 | vision_patch_size = None 414 | assert output_width ** 2 + 1 == state_dict["visual.attnpool.positional_embedding"].shape[0] 415 | image_resolution = output_width * 32 416 | 417 | embed_dim = state_dict["text_projection"].shape[1] 418 | context_length = state_dict["positional_embedding"].shape[0] 419 | vocab_size = state_dict["token_embedding.weight"].shape[0] 420 | transformer_width = state_dict["ln_final.weight"].shape[0] 421 | transformer_heads = transformer_width // 64 422 | transformer_layers = len(set(k.split(".")[2] for k in state_dict if k.startswith(f"transformer.resblocks"))) 423 | 424 | model = CLIP( 425 | embed_dim, 426 | image_resolution, vision_layers, vision_width, vision_patch_size, 427 | context_length, vocab_size, transformer_width, transformer_heads, transformer_layers 428 | ) 429 | 430 | for key in ["input_resolution", "context_length", "vocab_size"]: 431 | if key in state_dict: 432 | del state_dict[key] 433 | 434 | convert_weights(model) 435 | model.load_state_dict(state_dict) 436 | return model.eval() 437 | -------------------------------------------------------------------------------- /hoc.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn.functional as F 3 | 4 | from utils import * 5 | 6 | 7 | def get_T_HOC(config, model, train_dataloader_EF, rnd, test_flag=False, max_step=501, T0=None, p0=None, lr=0.1): 8 | config.path, record, c1m_cluster_each = init_feature_set(config, model, train_dataloader_EF, rnd) 9 | sub_clean_dataset_name, sub_noisy_dataset_name = build_dataset_informal(config, record, c1m_cluster_each) 10 | 11 | if test_flag: 12 | return 0, 0, 0 13 | 14 | if config.loss == 'fw': # forward loss correction 15 | # return one matrix if global 16 | # return a set of matrices + a map between index and matrix 17 | T_est, P_est, T_init, T_err = get_T_P_global(config, sub_noisy_dataset_name, max_step, T0, p0, lr=lr) 18 | # T_est = config.T 19 | if config.local: 20 | T_local, map_index_T, T_err = get_T_P_local(config, sub_noisy_dataset_name, T_est) 21 | return T_local, map_index_T, T_err 22 | else: 23 | return T_est, T_init, T_err 24 | else: 25 | return 0, 0, 0 26 | 27 | 28 | def get_T_P_global(config, sub_noisy_dataset_name, max_step=501, T0=None, p0=None, lr=0.1): 29 | global GLOBAL_T_REAL 30 | # all_point_cnt = 10000 31 | all_point_cnt = 15000 32 | # all_point_cnt = 2000 33 | NumTest = int(50) 34 | # NumTest = int(20) 35 | # TODO: make the above parameters configurable 36 | 37 | print(f'Estimating global T. Sampling {all_point_cnt} examples each time') 38 | 39 | KINDS = config.num_classes 40 | data_set = torch.load(f'{sub_noisy_dataset_name}', map_location=torch.device('cpu')) 41 | T_real, P_real = check_T_torch(KINDS, data_set['clean_label'], data_set['noisy_label']) 42 | GLOBAL_T_REAL = T_real 43 | p_real = count_real(KINDS, torch.tensor(T_real), torch.tensor(P_real), -1) 44 | 45 | # Build Feature Clusters -------------------------------------- 46 | p_estimate = [[] for _ in range(3)] 47 | p_estimate[0] = torch.zeros(KINDS) 48 | p_estimate[1] = torch.zeros(KINDS, KINDS) 49 | p_estimate[2] = torch.zeros(KINDS, KINDS, KINDS) 50 | p_estimate_rec = torch.zeros(NumTest, 3) 51 | for idx in range(NumTest): 52 | print(idx, flush=True) 53 | 54 | # global 55 | sample = np.random.choice(range(data_set['feature'].shape[0]), all_point_cnt, replace=False) 56 | final_feat = data_set['feature'][sample] 57 | noisy_label = data_set['noisy_label'][sample] 58 | cnt_y_3 = count_y(KINDS, final_feat, noisy_label, all_point_cnt) 59 | for i in range(3): 60 | cnt_y_3[i] /= all_point_cnt 61 | p_estimate[i] = p_estimate[i] + cnt_y_3[i] if idx != 0 else cnt_y_3[i] 62 | ss = torch.abs(p_estimate[i] / (idx + 1) - p_real[i]) 63 | p_estimate_rec[idx, i] = torch.mean(torch.abs(p_estimate[i] / (idx + 1) - p_real[i])) * 100.0 / ( 64 | torch.mean(p_real[i])) # Assess the gap between estimation value and real value 65 | print(p_estimate_rec[idx], flush=True) 66 | 67 | for j in range(3): 68 | p_estimate[j] = p_estimate[j] / NumTest 69 | 70 | loss_min, E_calc, P_calc, T_init = calc_func(KINDS, p_estimate, False, config.device, max_step, T0, p0, lr=lr) 71 | P_calc = P_calc.view(-1).cpu().numpy() 72 | E_calc = E_calc.cpu().numpy() 73 | T_init = T_init.cpu().numpy() 74 | # print("----Real value----------") 75 | # print(f'Real: P = {P_real},\n T = \n{np.round(np.array(T_real),3)}') 76 | # print(f'Sum P = {sum(P_real)},\n sum T = \n{np.sum(np.array(T_real), 1)}') 77 | # print("\n----Calc result----") 78 | # print(f"loss = {loss_min}, \np = {P_calc}, \nT_est = \n{np.round(E_calc, 3)}") 79 | # print(f"sum p = {np.sum(P_calc)}, \nsum T_est = \n{np.sum(E_calc, 1)}") 80 | # print("\n---Error of the estimated T (sum|T_est - T|/N * 100)----", flush=True) 81 | print(f"L11 Error (Global): {np.sum(np.abs(E_calc - np.array(T_real))) * 1.0 / KINDS * 100}") 82 | T_err = np.sum(np.abs(E_calc - np.array(T_real))) * 1.0 / KINDS * 100 83 | rec_global = [[] for _ in range(3)] 84 | rec_global[0], rec_global[1], rec_global[2] = loss_min, T_real, E_calc 85 | path = "./rec_global/" + config.dataset + "_" + config.label_file_path[11:14] + "_" + config.pre_type + ".pt" 86 | torch.save(rec_global, path) 87 | return E_calc, P_calc, T_init, T_err 88 | 89 | 90 | def get_T_P_local(config, sub_noisy_dataset_name, T_avg=None): 91 | global GLOBAL_T_REAL 92 | rounds = 300 93 | all_point_cnt = 100 # 500 for global 100 for local 94 | NumTest = int(30) 95 | # TODO: make the above parameters configurable 96 | 97 | print(f'Estimating local T. Sampling {all_point_cnt} examples each time') 98 | KINDS = config.num_classes 99 | data_set = torch.load(f'{sub_noisy_dataset_name}', map_location=torch.device('cpu')) 100 | 101 | next_select_idx = np.random.choice(range(data_set['index'].shape[0]), 1, replace=False) 102 | selected_idx = torch.tensor(range(data_set['index'].shape[0])) 103 | T_rec = [] 104 | T_true_rec = [] 105 | map_index_T = np.zeros((data_set['index'].shape[0]), dtype='int') - 1 106 | 107 | round = 0 108 | T_err_list = [] 109 | while (1): 110 | # for round in range(rounds): 111 | 112 | if config.local: # Select a picture & nearest 250 pictures: count t_ Real and P_ real 113 | 114 | # Start a cycle here and run about 300 * numtest times to the end 115 | # One center is extracted each time, and numLocal adjacent points are taken as cluster, which are recorded as selected_ idx 116 | idx_sel = torch.tensor( 117 | extract_sub_dataset_local(data_set['feature'], next_select_idx, numLocal=config.numLocal)) 118 | # assign round value to the locations with value -1 119 | map_index_T[idx_sel[map_index_T[idx_sel] == -1]] = round 120 | next_select_idx, selected_idx = select_next_idx(selected_idx, idx_sel) 121 | T_real, P_real = check_T_torch(KINDS, data_set['clean_label'][idx_sel], 122 | data_set['noisy_label'][idx_sel]) # focus on 250 samples 123 | # T and P of local cluster 124 | p_real = count_real(KINDS, torch.tensor(T_real), torch.tensor(P_real), -1) if config.local else count_real( 125 | KINDS, torch.tensor(config.T), torch.tensor(config.P), -1) 126 | 127 | # Build Feature Clusters -------------------------------------- 128 | p_estimate = [[] for _ in range(3)] 129 | p_estimate[0] = torch.zeros(KINDS) 130 | p_estimate[1] = torch.zeros(KINDS, KINDS) 131 | p_estimate[2] = torch.zeros(KINDS, KINDS, KINDS) 132 | p_estimate_rec = torch.zeros(NumTest, 3) 133 | for idx in range(NumTest): 134 | 135 | # local 136 | sample = np.random.choice(idx_sel, all_point_cnt, 137 | replace=False) # test: extract 100 samples from local cluster 138 | final_feat = data_set['feature'][sample] 139 | noisy_label = data_set['noisy_label'][sample] 140 | # 141 | cnt_y_3 = count_y(KINDS, final_feat, noisy_label, all_point_cnt) 142 | for i in range(3): 143 | cnt_y_3[i] /= all_point_cnt 144 | p_estimate[i] = p_estimate[i] + cnt_y_3[i] if idx != 0 else cnt_y_3[i] 145 | p_estimate_rec[idx, i] = torch.mean(torch.abs(p_estimate[i] / (idx + 1) - p_real[i])) * 100.0 / ( 146 | torch.mean(p_real[i])) 147 | 148 | # Calculate T & P ------------------------------------------------------------- 149 | for j in range(3): 150 | p_estimate[j] = p_estimate[j] / NumTest 151 | 152 | loss_min, E_calc, P_calc, _ = calc_func(KINDS, p_estimate, True, 153 | config.device) # E_calc, P_calc = calc_func(p_real) 154 | P_calc = P_calc.view(-1).cpu().numpy() 155 | E_calc = E_calc.cpu().numpy() 156 | 157 | center_label = np.argmax(P_real) 158 | T_rec += [P_calc.reshape(-1, 1) * E_calc + (1 - P_calc).reshape(-1, 1) * T_avg] # estimated local T 159 | T_true_rec += [P_real.reshape(-1, 1) * T_real + (1 - P_real).reshape(-1, 1) * GLOBAL_T_REAL] 160 | 161 | # print("\n---Error of the estimated T (sum|T_est - T|/N * 100)----", flush=True) 162 | # print("----T_rec[round]", np.array(T_rec[round])) 163 | # print("----T_true_rec[round]", np.array(T_true_rec[round])) 164 | T_err = np.sum(np.abs(np.array(T_rec[round]) - np.array(T_true_rec[round]))) * 1.0 / KINDS * 100 165 | print(f"L11 Error (Local): {T_err}") 166 | T_err_list.append(T_err) 167 | 168 | print(f'round {round}, remaining {np.sum(map_index_T == -1)}') 169 | round += 1 170 | if round == rounds: 171 | print( 172 | f'Only get local transition matrices for the first {np.sum(map_index_T != -1)} examples in {rounds} rounds', 173 | flush=True) 174 | T_rec += [T_avg] 175 | map_index_T[map_index_T == -1] = round # use T_avg for the remaining matrices 176 | return T_rec, map_index_T, T_err_list 177 | if selected_idx[selected_idx > -1].size(0) == 0: 178 | return T_rec, map_index_T, T_err_list 179 | # did not use P currently 180 | 181 | 182 | def func(KINDS, p_estimate, T_out, P_out, N, step, LOCAL, _device): 183 | eps = 1e-2 184 | eps2 = 1e-8 185 | eps3 = 1e-5 186 | loss = torch.tensor(0.0).to(_device) # define the loss 187 | 188 | P = smp(P_out) 189 | T = smt(T_out) 190 | 191 | mode = random.randint(0, KINDS - 1) 192 | mode = -1 193 | # Borrow p_ The calculation method of real is to calculate the temporary values of T and P at this time: N, N*N, N*N*N 194 | p_temp = count_real(KINDS, T.to(torch.device("cpu")), P.to(torch.device("cpu")), mode, _device) 195 | 196 | weight = [1.0, 1.0, 1.0] 197 | # weight = [2.0,1.0,1.0] 198 | 199 | for j in range(3): # || P1 || + || P2 || + || P3 || 200 | p_temp[j] = p_temp[j].to(_device) 201 | loss += weight[j] * torch.norm(p_estimate[j] - p_temp[j]) # / np.sqrt(N**j) 202 | 203 | if step > 100 and LOCAL and KINDS != 100: 204 | loss += torch.mean(torch.log(P + eps)) / 10 205 | 206 | return loss 207 | 208 | 209 | def calc_func(KINDS, p_estimate, LOCAL, _device, max_step=501, T0=None, p0=None, lr=0.1): 210 | # init 211 | # _device = torch.device("cpu") 212 | N = KINDS 213 | eps = 1e-8 214 | if T0 is None: 215 | T = 5 * torch.eye(N) - torch.ones((N, N)) 216 | else: 217 | T = T0 218 | 219 | if p0 is None: 220 | P = torch.ones((N, 1), device=None) / N + torch.rand((N, 1), device=None) * 0.1 # P:0-9 distribution 221 | else: 222 | P = p0 223 | 224 | T = T.to(_device) 225 | P = P.to(_device) 226 | p_estimate = [item.to(_device) for item in p_estimate] 227 | print(f'using {_device} to solve equations') 228 | 229 | T.requires_grad = True 230 | P.requires_grad = True 231 | 232 | optimizer = torch.optim.Adam([T, P], lr=lr) 233 | 234 | # train 235 | loss_min = 100.0 236 | T_rec = T.detach() 237 | P_rec = P.detach() 238 | 239 | time1 = time.time() 240 | for step in range(max_step): 241 | if step: 242 | optimizer.zero_grad() 243 | loss.backward() 244 | optimizer.step() 245 | loss = func(KINDS, p_estimate, T, P, N, step, LOCAL, _device) 246 | if loss < loss_min and step > 5: 247 | loss_min = loss.detach() 248 | T_rec = T.detach() 249 | P_rec = P.detach() 250 | # if step % 10 == 0: 251 | # print('loss {}'.format(loss)) 252 | # print(f'step: {step} time_cost: {time.time() - time1}') 253 | # print(f'T {np.round(smt(T.cpu()).detach().numpy()*100,1)}', flush=True) 254 | # print(f'P {np.round(smp(P.cpu().view(-1)).detach().numpy()*100,1)}', flush=True) 255 | # time1 = time.time() 256 | # if global_var.get_value('T_init') is None: 257 | global_var.set_value('T_init', T_rec.detach()) 258 | # tmp = global_var.get_value('T_init') 259 | # print(f'set T_init to {tmp}') 260 | # if global_var.get_value('p_init') is None: 261 | global_var.set_value('p_init', P_rec.detach()) 262 | print(f'T_init and p_init are updated') 263 | return loss_min, smt(T_rec).detach(), smp(P_rec).detach(), T_rec.detach() 264 | 265 | 266 | def count_y(KINDS, feat_cord, label, cluster_sum): 267 | # feat_cord = torch.tensor(final_feat) 268 | cnt = [[] for _ in range(3)] 269 | cnt[0] = torch.zeros(KINDS) 270 | cnt[1] = torch.zeros(KINDS, KINDS) 271 | cnt[2] = torch.zeros(KINDS, KINDS, KINDS) 272 | feat_cord = feat_cord.cpu().numpy() 273 | dist = distCosine(feat_cord, feat_cord) 274 | max_val = np.max(dist) 275 | am = np.argmin(dist, axis=1) 276 | for i in range(cluster_sum): 277 | dist[i][am[i]] = 10000.0 + max_val 278 | min_dis_id = np.argmin(dist, axis=1) 279 | for i in range(cluster_sum): 280 | dist[i][min_dis_id[i]] = 10000.0 + max_val 281 | min_dis_id2 = np.argmin(dist, axis=1) 282 | for x1 in range(cluster_sum): 283 | cnt[0][label[x1]] += 1 284 | cnt[1][label[x1]][label[min_dis_id[x1]]] += 1 285 | cnt[2][label[x1]][label[min_dis_id[x1]]][label[min_dis_id2[x1]]] += 1 286 | 287 | return cnt 288 | 289 | 290 | def count_2nn_acc(KINDS, feat_cord, label, cluster_sum): 291 | # feat_cord = torch.tensor(final_feat) 292 | cnt = [[] for _ in range(3)] 293 | cnt[0] = torch.zeros(KINDS) 294 | cnt[1] = torch.zeros(KINDS, KINDS) 295 | cnt[2] = torch.zeros(KINDS, KINDS, KINDS) 296 | feat_cord = feat_cord.cpu().numpy() 297 | dist = distCosine(feat_cord, feat_cord) 298 | # print(dist.shape) 299 | # print(f'Use Euclidean distance') 300 | # dist = distEuclidean(feat_cord, feat_cord) 301 | 302 | max_val = np.max(dist) 303 | am = np.argmin(dist, axis=1) 304 | # TODO: speedup this part 305 | for i in range(cluster_sum): 306 | dist[i][am[i]] = 10000.0 + max_val 307 | min_dis_id = np.argmin(dist, axis=1) 308 | for i in range(cluster_sum): 309 | dist[i][min_dis_id[i]] = 10000.0 + max_val 310 | min_dis_id2 = np.argmin(dist, axis=1) 311 | for x1 in range(cluster_sum): 312 | cnt[0][label[x1]] += 1 313 | cnt[1][label[x1]][label[min_dis_id[x1]]] += 1 314 | cnt[2][label[x1]][label[min_dis_id[x1]]][label[min_dis_id2[x1]]] += 1 315 | 316 | return cnt 317 | 318 | def count_knn_conf(args, feat_cord, label, cluster_sum, k): 319 | # feat_cord = torch.tensor(final_feat) 320 | KINDS = args.num_classes 321 | # cnt = [[] for _ in range(3)] 322 | # cnt[0] = torch.zeros(KINDS) 323 | # cnt[1] = torch.zeros(KINDS, KINDS) 324 | # cnt[2] = torch.zeros(KINDS, KINDS, KINDS) 325 | dist = cosDistance(feat_cord) 326 | 327 | print(f'knn parameter is k = {k}') 328 | time1 = time.time() 329 | min_similarity = args.min_similarity 330 | values, indices = dist.topk(k, dim=1, largest=False, sorted=True) 331 | knn_labels = label[indices] 332 | knn_labels_cnt = torch.zeros(cluster_sum, KINDS) 333 | 334 | for i in range(KINDS): 335 | knn_labels_cnt[:, i] += torch.sum((1.0 - min_similarity - values) * (knn_labels == i), 336 | 1) # similarity should be larger than min_similarity 337 | # print(knn_labels_cnt[0]) 338 | time2 = time.time() 339 | print(f'Running time for k = {k} is {time2 - time1}') 340 | confidence = torch.sum(knn_labels_cnt, 1).reshape(-1) 341 | return confidence 342 | 343 | 344 | def count_knn_distribution(args, feat_cord, label, cluster_sum, k, norm='l2'): 345 | # feat_cord = torch.tensor(final_feat) 346 | KINDS = args.num_classes 347 | # cnt = [[] for _ in range(3)] 348 | # cnt[0] = torch.zeros(KINDS) 349 | # cnt[1] = torch.zeros(KINDS, KINDS) 350 | # cnt[2] = torch.zeros(KINDS, KINDS, KINDS) 351 | dist = cosDistance(feat_cord) 352 | # dist = torch.cdist(feat_cord,feat_cord,p=2) 353 | # import pdb 354 | # pdb.set_trace() 355 | 356 | print(f'knn parameter is k = {k}') 357 | time1 = time.time() 358 | min_similarity = args.min_similarity 359 | values, indices = dist.topk(k, dim=1, largest=False, sorted=True) 360 | values[:, 0] = 2.0 * values[:, 1] - values[:, 2] 361 | knn_labels = label[indices] 362 | 363 | # # check knn feasibility 364 | # feasibility = torch.zeros(k) 365 | # prob = torch.zeros(k) 366 | # # import pdb 367 | # # pdb.set_trace() 368 | # e=0.4 369 | # import scipy.special as sc 370 | # for i in range(k): 371 | # feasibility[i] = torch.mean(1.0*(torch.sum(knn_labels[:,:i+1] == knn_labels[:,0].view(50000,1),1) == i+1)) 372 | # k1=int(np.ceil((i+1)/2)-1) 373 | # a = sc.betainc(i-k1+1,k1+1,1-e) 374 | # prob[i] = feasibility[i] * a 375 | 376 | # print(f'delta_k is: {1-feasibility}') 377 | # print(f'probability lower bound is: {prob}') 378 | # torch.save({'delta_k': 1-feasibility, 'prob': prob}, f'{args.pre_type}_c100_{k}.pt') 379 | 380 | # # # e=0.4 381 | # # # k=20 382 | # # # k1=int(np.ceil((k+1)/2)-1) 383 | # # # a = sc.betainc(k-k1+1,k1+1,1-e) 384 | 385 | # # # k=5 386 | # # # k1=int(np.ceil((k+1)/2)-1) 387 | # # # b = sc.betainc(k-k1+1,k1+1,1-e) 388 | # # # # b/a 389 | # # # print(f'a={a}, b={b}, b/a={a/b}') 390 | # exit() 391 | 392 | knn_labels_cnt = torch.zeros(cluster_sum, KINDS) 393 | # thre_val_tmp = torch.tensor([[0.1766, 0.2208], 394 | # [0.1423, 0.1991], 395 | # [0.1439, 0.1672], 396 | # [0.1063, 0.1464], 397 | # [0.1192, 0.1708], 398 | # [0.1318, 0.1464], 399 | # [0.1206, 0.1672], 400 | # [0.1151, 0.1795], 401 | # [0.1452, 0.2184], 402 | # [0.1517, 0.1991]]) 403 | # thre_val = torch.mean(thre_val_tmp,1) 404 | 405 | for i in range(KINDS): 406 | # knn_labels_cnt[:,i] += torch.sum(1.0 * (knn_labels == i), 1) 407 | knn_labels_cnt[:, i] += torch.sum((1.0 - min_similarity - values) * (knn_labels == i), 1) 408 | # knn_labels_cnt[:,i] += torch.sum((1.0 - min_similarity - values) * (knn_labels == i) * (values < thre_val[i]), 1) # similarity should be larger than min_similarity 409 | # print(knn_labels_cnt[0]) 410 | time2 = time.time() 411 | print(f'Running time for k = {k} is {time2 - time1}') 412 | 413 | # # ----------- old ------------- 414 | # # feat_cord = feat_cord.cpu().numpy() 415 | # # dist = distCosine(feat_cord, feat_cord) 416 | # # import pdb 417 | # # pdb.set_trace() 418 | 419 | # # print(f'Use Euclidean distance') 420 | # # dist = distEuclidean(feat_cord, feat_cord) 421 | 422 | # max_val = np.max(dist) 423 | # k += 1 # k-nn -> k+1 instances 424 | # knn_labels_cnt = torch.zeros(cluster_sum, KINDS) 425 | # for k_loop in range(k): 426 | # # print(k_loop, flush=True) 427 | # min_dis_id = np.argmin(dist,axis=1) 428 | # knn_labels = label[min_dis_id] 429 | 430 | # # not count self label 431 | # # if k_loop > 0: 432 | # # for i in range(cluster_sum): 433 | # # knn_labels_cnt[i, knn_labels[i]] += 1 434 | # # dist[i][min_dis_id[i]] = 10000.0 + max_val 435 | # # else: 436 | # # for i in range(cluster_sum): 437 | # # dist[i][min_dis_id[i]] = 10000.0 + max_val 438 | 439 | # # # count self label 440 | # # for i in range(cluster_sum): 441 | # # knn_labels_cnt[i, knn_labels[i]] += 1 442 | # # dist[i][min_dis_id[i]] = 10000.0 + max_val 443 | 444 | # # count self label, distance as weights (weight = 1-dist) 445 | # for i in range(cluster_sum): 446 | # knn_labels_cnt[i, knn_labels[i]] += 1-dist[i][min_dis_id[i]] 447 | # dist[i][min_dis_id[i]] = 10000.0 + max_val 448 | 449 | if norm == 'l2': 450 | # normalized by l2-norm -- cosine distance 451 | knn_labels_prob = F.normalize(knn_labels_cnt, p=2.0, dim=1) 452 | elif norm == 'l1': 453 | # normalized by mean 454 | knn_labels_prob = knn_labels_cnt / torch.sum(knn_labels_cnt, 1).reshape(-1, 1) 455 | else: 456 | raise NameError('Undefined norm') 457 | return knn_labels_prob 458 | 459 | 460 | def get_score(knn_labels_cnt, label, k, method='cores', prior=None): # method = ['cores', 'peer'] 461 | # knn_labels_cnt: sampleSize * #class 462 | # knn_labels_cnt /= (k*1.0) 463 | # import pdb 464 | # pdb.set_trace() 465 | loss = F.nll_loss(torch.log(knn_labels_cnt + 1e-8), label, reduction='none') 466 | # loss = -torch.tanh(-F.nll_loss(knn_labels_cnt, label, reduction = 'none')) # TV 467 | # loss = -(-F.nll_loss(knn_labels_cnt, label, reduction = 'none')) # 468 | # loss_numpy = loss.data.cpu().numpy() 469 | # num_batch = len(loss_numpy) 470 | # loss_v = np.zeros(num_batch) 471 | # loss_div_numpy = float(np.array(0)) 472 | 473 | # loss_ = -(knn_labels_cnt) # 474 | # loss_ = -torch.tanh(knn_labels_cnt) # TV 475 | # import pdb 476 | # pdb.set_trace() 477 | loss_ = -torch.log(knn_labels_cnt + 1e-8) 478 | if method == 'cores': 479 | score = loss - torch.mean(loss_, 1) 480 | # score = loss 481 | elif method == 'peer': 482 | prior = torch.tensor(prior) 483 | score = loss - torch.sum(torch.mul(prior, loss_), 1) 484 | elif method == 'ce': 485 | score = loss 486 | elif method == 'avg': 487 | score = - torch.mean(loss_, 1) 488 | elif method == 'new': 489 | score = 1.1 * loss - torch.mean(loss_, 1) 490 | else: 491 | raise NameError('Undefined method') 492 | 493 | return score 494 | -------------------------------------------------------------------------------- /data/cifar.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import os 4 | import os.path 5 | import sys 6 | 7 | import numpy as np 8 | from PIL import Image 9 | 10 | if sys.version_info[0] == 2: 11 | import cPickle as pickle 12 | else: 13 | import pickle 14 | import torch 15 | import torch.utils.data as data 16 | from .utils import download_url, check_integrity, noisify, noisify_instance, multiclass_noisify 17 | 18 | 19 | class CIFAR10(data.Dataset): 20 | """`CIFAR10 `_ Dataset. 21 | 22 | Args: 23 | root (string): Root directory of dataset where directory 24 | ``cifar-10-batches-py`` exists or will be saved to if download is set to True. 25 | train (bool, optional): If True, creates dataset from training set, otherwise 26 | creates from test set. 27 | transform (callable, optional): A function/transform that takes in an PIL image 28 | and returns a transformed version. E.g, ``transforms.RandomCrop`` 29 | target_transform (callable, optional): A function/transform that takes in the 30 | target and transforms it. 31 | download (bool, optional): If true, downloads the dataset from the internet and 32 | puts it in root directory. If dataset is already downloaded, it is not 33 | downloaded again. 34 | 35 | """ 36 | base_folder = 'cifar-10-batches-py' 37 | url = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz" 38 | filename = "cifar-10-python.tar.gz" 39 | tgz_md5 = 'c58f30108f718f92721af3b95e74349a' 40 | train_list = [ 41 | ['data_batch_1', 'c99cafc152244af753f735de768cd75f'], 42 | ['data_batch_2', 'd4bba439e000b95fd0a9bffe97cbabec'], 43 | ['data_batch_3', '54ebc095f3ab1f0389bbae665268c751'], 44 | ['data_batch_4', '634d18415352ddfa80567beed471001a'], 45 | ['data_batch_5', '482c414d41f54cd18b22e5b47cb7c3cb'], 46 | ] 47 | 48 | test_list = [ 49 | ['test_batch', '40351d587109b95175f43aff81a1287e'], 50 | ] 51 | 52 | def __init__(self, root, train=True, 53 | transform=None, target_transform=None, 54 | download=False, 55 | noise_type=None, noise_rate=0.2, random_state=0, noise_file=None, synthetic=False): 56 | self.root = os.path.expanduser(root) 57 | self.transform = transform 58 | self.target_transform = target_transform 59 | self.train = train # training set or test set 60 | self.dataset = 'cifar10' 61 | self.noise_type = noise_type 62 | self.nb_classes = 10 63 | self.noise_file = noise_file 64 | idx_each_class_noisy = [[] for i in range(10)] 65 | if download: 66 | self.download() 67 | 68 | if not self._check_integrity(): 69 | self.download() 70 | if not self._check_integrity(): 71 | raise RuntimeError('Dataset not found or corrupted.' + 72 | ' You can use download=True to download it') 73 | 74 | # now load the picked numpy arrays 75 | if self.train: 76 | self.train_data = [] 77 | self.train_labels = [] 78 | for fentry in self.train_list: 79 | f = fentry[0] 80 | file = os.path.join(self.root, self.base_folder, f) 81 | fo = open(file, 'rb') 82 | if sys.version_info[0] == 2: 83 | entry = pickle.load(fo) 84 | else: 85 | entry = pickle.load(fo, encoding='latin1') 86 | self.train_data.append(entry['data']) 87 | if 'labels' in entry: 88 | self.train_labels += entry['labels'] 89 | else: 90 | self.train_labels += entry['fine_labels'] 91 | fo.close() 92 | 93 | self.train_data = np.concatenate(self.train_data) 94 | self.train_data = self.train_data.reshape((50000, 3, 32, 32)) 95 | self.train_data = self.train_data.transpose((0, 2, 3, 1)) # convert to HWC 96 | self.noise_prior = None 97 | self.noise_or_not = None 98 | # if noise_type is not None: 99 | if noise_type != 'clean': 100 | # noisify train data 101 | if noise_type in ['symmetric', 'pairflip']: 102 | self.train_labels = np.asarray([[self.train_labels[i]] for i in range(len(self.train_labels))]) 103 | self.train_noisy_labels, self.actual_noise_rate = noisify(dataset=self.dataset, 104 | train_labels=self.train_labels, 105 | noise_type=noise_type, 106 | noise_rate=noise_rate, 107 | random_state=random_state, 108 | nb_classes=self.nb_classes) 109 | self.train_noisy_labels = [i[0] for i in self.train_noisy_labels] 110 | _train_labels = [i[0] for i in self.train_labels] 111 | for i in range(len(_train_labels)): 112 | idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 113 | class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(10)] 114 | self.noise_prior = np.array(class_size_noisy) / sum(class_size_noisy) 115 | print(f'The noisy data ratio in each class is {self.noise_prior}') 116 | self.noise_or_not = np.transpose(self.train_noisy_labels) != np.transpose(_train_labels) 117 | elif noise_type == 'instance': 118 | self.train_noisy_labels, self.actual_noise_rate = noisify_instance(self.train_data, 119 | self.train_labels, 120 | noise_rate=noise_rate) 121 | print('over all noise rate is ', self.actual_noise_rate) 122 | # self.train_noisy_labels=[i[0] for i in self.train_noisy_labels] 123 | # self.train_noisy_labels=[i[0] for i in self.train_noisy_labels] 124 | # _train_labels=[i[0] for i in self.train_labels] 125 | for i in range(len(self.train_labels)): 126 | idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 127 | class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(10)] 128 | self.noise_prior = np.array(class_size_noisy) / sum(class_size_noisy) 129 | print(f'The noisy data ratio in each class is {self.noise_prior}') 130 | self.noise_or_not = np.transpose(self.train_noisy_labels) != np.transpose(self.train_labels) 131 | elif noise_type == 'manual': # manual noise 132 | # load noise label 133 | train_noisy_labels = self.load_label() 134 | self.train_noisy_labels = train_noisy_labels.numpy().tolist() 135 | print(f'noisy labels loaded from {self.noise_file}') 136 | 137 | for i in range(len(self.train_noisy_labels)): 138 | idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 139 | class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(10)] 140 | self.noise_prior = np.array(class_size_noisy) / sum(class_size_noisy) 141 | print(f'The noisy data ratio in each class is {self.noise_prior}') 142 | self.noise_or_not = np.transpose(self.train_noisy_labels) != np.transpose(self.train_labels) 143 | self.actual_noise_rate = np.sum(self.noise_or_not) / 50000 144 | print('over all noise rate is ', self.actual_noise_rate) 145 | elif noise_type == 'rand_label': # random labels 146 | idx = np.arange(50000) 147 | np.random.shuffle(idx) 148 | self.train_noisy_labels = list(np.array(self.train_labels)[idx]) 149 | print(f'Use random labels: {self.train_noisy_labels[:10]}', flush=True) 150 | # load noise label 151 | # train_noisy_labels = self.load_label_human_new() 152 | # self.train_noisy_labels = train_noisy_labels.tolist().copy() 153 | # print(f'noisy labels loaded from {self.noise_file}') 154 | 155 | # for i in range(len(self.train_noisy_labels)): 156 | # idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 157 | # class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(10)] 158 | # self.noise_prior = np.array(class_size_noisy)/sum(class_size_noisy) 159 | # print(f'The noisy data ratio in each class is {self.noise_prior}') 160 | # self.noise_or_not = np.transpose(self.train_noisy_labels)!=np.transpose(self.train_labels) 161 | # self.actual_noise_rate = np.sum(self.noise_or_not)/50000 162 | # print('over all noise rate is ', self.actual_noise_rate) 163 | else: 164 | # load noise label 165 | train_noisy_labels = self.load_label_human_new() 166 | self.train_noisy_labels = train_noisy_labels.tolist() 167 | print(f'noisy labels loaded from {self.noise_file}') 168 | 169 | if synthetic: 170 | T = np.zeros((self.nb_classes, self.nb_classes)) 171 | for i in range(len(self.train_noisy_labels)): 172 | T[self.train_labels[i]][self.train_noisy_labels[i]] += 1 173 | T = T / np.sum(T, axis=1) 174 | print(f'Noise transition matrix is \n{T}') 175 | train_noisy_labels = multiclass_noisify(y=np.array(self.train_labels), P=T, 176 | random_state=random_state) # np.random.randint(1,10086) 177 | self.train_noisy_labels = train_noisy_labels.tolist() 178 | T = np.zeros((self.nb_classes, self.nb_classes)) 179 | for i in range(len(self.train_noisy_labels)): 180 | T[self.train_labels[i]][self.train_noisy_labels[i]] += 1 181 | T = T / np.sum(T, axis=1) 182 | print(f'New synthetic noise transition matrix is \n{T}') 183 | 184 | for i in range(len(self.train_noisy_labels)): 185 | idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 186 | class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(10)] 187 | self.noise_prior = np.array(class_size_noisy) / sum(class_size_noisy) 188 | print(f'The noisy data ratio in each class is {self.noise_prior}') 189 | self.noise_or_not = np.transpose(self.train_noisy_labels) != np.transpose(self.train_labels) 190 | self.actual_noise_rate = np.sum(self.noise_or_not) / 50000 191 | print('over all noise rate is ', self.actual_noise_rate) 192 | 193 | imbalance = False 194 | if imbalance: 195 | np.random.seed(1) 196 | img_num_list = self.get_img_num_per_cls(self.nb_classes, imb_type='step', imb_factor=0.1) 197 | self.gen_imbalanced_data(img_num_list) 198 | print(f'img_num_list is {img_num_list}') 199 | 200 | 201 | else: 202 | f = self.test_list[0][0] 203 | file = os.path.join(self.root, self.base_folder, f) 204 | fo = open(file, 'rb') 205 | if sys.version_info[0] == 2: 206 | entry = pickle.load(fo) 207 | else: 208 | entry = pickle.load(fo, encoding='latin1') 209 | self.test_data = entry['data'] 210 | if 'labels' in entry: 211 | self.test_labels = entry['labels'] 212 | else: 213 | self.test_labels = entry['fine_labels'] 214 | fo.close() 215 | self.test_data = self.test_data.reshape((10000, 3, 32, 32)) 216 | self.test_data = self.test_data.transpose((0, 2, 3, 1)) # convert to HWC 217 | 218 | def load_label_human_new(self): 219 | # NOTE only load manual training label 220 | noise_label = torch.load(self.noise_file) 221 | if isinstance(noise_label, dict): 222 | if "clean_label" in noise_label.keys(): 223 | clean_label = torch.tensor(noise_label['clean_label']) 224 | assert torch.sum(torch.tensor(self.train_labels) - clean_label) == 0 225 | print(f'Loaded {self.noise_type} from {self.noise_file}.') 226 | print(f'The overall noise rate is {1 - np.mean(clean_label.numpy() == noise_label[self.noise_type])}') 227 | return noise_label[self.noise_type].reshape(-1) 228 | else: 229 | raise Exception('Input Error') 230 | 231 | def load_label(self): 232 | ''' 233 | I adopt .pt rather .pth according to this discussion: 234 | https://github.com/pytorch/pytorch/issues/14864 235 | ''' 236 | # NOTE presently only use for load manual training label 237 | # noise_label = torch.load(self.noise_type) # f'../../{self.noise_type}' 238 | # noise_label = torch.load(f'noise_label/cifar-10/{self.noise_type}') 239 | assert self.noise_file != 'None' 240 | noise_label = torch.load(self.noise_file) 241 | if isinstance(noise_label, dict): 242 | if "clean_label_train" in noise_label.keys(): 243 | clean_label = noise_label['clean_label_train'] 244 | assert torch.sum(torch.tensor( 245 | self.train_labels) - clean_label) == 0 # commented for noise identification (NID) since we need to replace labels 246 | if "clean_label" in noise_label.keys() and 'raw_index' in noise_label.keys(): 247 | assert torch.sum( 248 | torch.tensor(self.train_labels)[noise_label['raw_index']] != noise_label['clean_label']) == 0 249 | noise_level = torch.sum(noise_label['clean_label'] == noise_label['noisy_label']) * 1.0 / ( 250 | noise_label['clean_label'].shape[0]) 251 | print(f'the overall noise level is {noise_level}') 252 | self.train_data = self.train_data[noise_label['raw_index']] 253 | return noise_label['noise_label_train'].view(-1).long() if 'noise_label_train' in noise_label.keys() else \ 254 | noise_label['noisy_label'].view(-1).long() # % 10 255 | 256 | else: 257 | return noise_label.view(-1).long() 258 | 259 | def get_img_num_per_cls(self, cls_num, imb_type, imb_factor): 260 | img_max = len(self.train_data) / cls_num 261 | img_num_per_cls = [] 262 | if imb_type == 'exp': 263 | for cls_idx in range(cls_num): 264 | num = img_max * (imb_factor ** ((cls_num - 1.0 - cls_idx) / (cls_num - 1.0))) 265 | img_num_per_cls.append(int(num)) 266 | elif imb_type == 'step': 267 | for cls_idx in range(cls_num // 2): 268 | img_num_per_cls.append(int(img_max * imb_factor)) 269 | for cls_idx in range(cls_num // 2): 270 | img_num_per_cls.append(int(img_max)) 271 | 272 | else: 273 | img_num_per_cls.extend([int(img_max)] * cls_num) 274 | return img_num_per_cls 275 | 276 | def gen_imbalanced_data(self, img_num_per_cls): 277 | idx_each_class_noisy = [[] for _ in range(10)] 278 | new_data = [] 279 | new_targets = [] 280 | new_noisy_label = [] 281 | targets_np = np.array(self.train_labels, dtype=np.int64) 282 | train_noisy_labels = np.array(self.train_noisy_labels, dtype=np.int64) 283 | classes = np.unique(targets_np) 284 | self.num_per_cls_dict = dict() 285 | 286 | for the_class, the_img_num in zip(classes, img_num_per_cls): 287 | self.num_per_cls_dict[the_class] = the_img_num 288 | idx = np.where(targets_np == the_class)[0] 289 | np.random.shuffle(idx) 290 | reshape_times = the_img_num // idx.shape[0] + 1 291 | selec_idx = idx.repeat(reshape_times)[:the_img_num] 292 | new_data.append(self.train_data[selec_idx, ...]) 293 | new_noisy_label += train_noisy_labels[selec_idx].tolist() 294 | new_targets.extend([the_class, ] * the_img_num) 295 | new_data = np.vstack(new_data) 296 | self.train_data = new_data 297 | self.train_labels = new_targets 298 | self.train_noisy_labels = new_noisy_label 299 | for i in range(len(self.train_noisy_labels)): 300 | idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 301 | class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(10)] 302 | self.noise_prior = np.array(class_size_noisy) / sum(class_size_noisy) 303 | print(f'The noisy data ratio in each class is {self.noise_prior}') 304 | # import pdb 305 | # pdb.set_trace() 306 | self.noise_or_not = np.transpose(self.train_noisy_labels) != np.transpose(self.train_labels) 307 | self.actual_noise_rate = np.sum(self.noise_or_not) / self.noise_or_not.shape[0] 308 | print('over all noise rate is ', self.actual_noise_rate) 309 | 310 | def get_cls_num_list(self): 311 | cls_num_list = [] 312 | for i in range(self.nb_classes): 313 | cls_num_list.append(self.num_per_cls_dict[i]) 314 | return cls_num_list 315 | 316 | def __getitem__(self, index): 317 | """ 318 | Args: 319 | index (int): Index 320 | 321 | Returns: 322 | tuple: (image, target) where target is index of the target class. 323 | """ 324 | if self.train: 325 | if self.noise_type != 'clean': 326 | img, target = self.train_data[index], self.train_noisy_labels[index] 327 | else: 328 | img, target = self.train_data[index], self.train_labels[index] 329 | else: 330 | img, target = self.test_data[index], self.test_labels[index] 331 | 332 | # doing this so that it is consistent with all other datasets 333 | # to return a PIL Image 334 | img = Image.fromarray(img) 335 | 336 | if self.transform is not None: 337 | img = self.transform(img) 338 | 339 | if self.target_transform is not None: 340 | target = self.target_transform(target) 341 | 342 | return img, target, index 343 | 344 | def __len__(self): 345 | if self.train: 346 | return len(self.train_data) 347 | else: 348 | return len(self.test_data) 349 | 350 | def _check_integrity(self): 351 | root = self.root 352 | for fentry in (self.train_list + self.test_list): 353 | filename, md5 = fentry[0], fentry[1] 354 | fpath = os.path.join(root, self.base_folder, filename) 355 | if not check_integrity(fpath, md5): 356 | return False 357 | return True 358 | 359 | def download(self): 360 | import tarfile 361 | 362 | if self._check_integrity(): 363 | print('Files already downloaded and verified') 364 | return 365 | 366 | root = self.root 367 | download_url(self.url, root, self.filename, self.tgz_md5) 368 | 369 | # extract file 370 | cwd = os.getcwd() 371 | tar = tarfile.open(os.path.join(root, self.filename), "r:gz") 372 | os.chdir(root) 373 | tar.extractall() 374 | tar.close() 375 | os.chdir(cwd) 376 | 377 | def __repr__(self): 378 | fmt_str = 'Dataset ' + self.__class__.__name__ + '\n' 379 | fmt_str += ' Number of datapoints: {}\n'.format(self.__len__()) 380 | tmp = 'train' if self.train is True else 'test' 381 | fmt_str += ' Split: {}\n'.format(tmp) 382 | fmt_str += ' Root Location: {}\n'.format(self.root) 383 | tmp = ' Transforms (if any): ' 384 | fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp))) 385 | tmp = ' Target Transforms (if any): ' 386 | fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\n', '\n' + ' ' * len(tmp))) 387 | return fmt_str 388 | 389 | 390 | class CIFAR100(data.Dataset): 391 | """`CIFAR100 `_ Dataset. 392 | 393 | Args: 394 | root (string): Root directory of dataset where directory 395 | ``cifar-10-batches-py`` exists or will be saved to if download is set to True. 396 | train (bool, optional): If True, creates dataset from training set, otherwise 397 | creates from test set. 398 | transform (callable, optional): A function/transform that takes in an PIL image 399 | and returns a transformed version. E.g, ``transforms.RandomCrop`` 400 | target_transform (callable, optional): A function/transform that takes in the 401 | target and transforms it. 402 | download (bool, optional): If true, downloads the dataset from the internet and 403 | puts it in root directory. If dataset is already downloaded, it is not 404 | downloaded again. 405 | 406 | """ 407 | base_folder = 'cifar-100-python' 408 | url = "https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz" 409 | filename = "cifar-100-python.tar.gz" 410 | tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85' 411 | train_list = [ 412 | ['train', '16019d7e3df5f24257cddd939b257f8d'], 413 | ] 414 | 415 | test_list = [ 416 | ['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'], 417 | ] 418 | 419 | def __init__(self, root, train=True, 420 | transform=None, target_transform=None, 421 | download=False, 422 | noise_type=None, noise_rate=0.2, random_state=0, noise_file=None): 423 | self.root = os.path.expanduser(root) 424 | self.transform = transform 425 | self.target_transform = target_transform 426 | self.train = train # training set or test set 427 | self.dataset = 'cifar100' 428 | self.noise_type = noise_type 429 | self.nb_classes = 100 430 | self.noise_file = noise_file 431 | idx_each_class_noisy = [[] for i in range(100)] 432 | 433 | if download: 434 | self.download() 435 | 436 | if not self._check_integrity(): 437 | raise RuntimeError('Dataset not found or corrupted.' + 438 | ' You can use download=True to download it') 439 | 440 | # now load the picked numpy arrays 441 | if self.train: 442 | self.train_data = [] 443 | self.train_labels = [] 444 | for fentry in self.train_list: 445 | f = fentry[0] 446 | file = os.path.join(self.root, self.base_folder, f) 447 | fo = open(file, 'rb') 448 | if sys.version_info[0] == 2: 449 | entry = pickle.load(fo) 450 | else: 451 | entry = pickle.load(fo, encoding='latin1') 452 | self.train_data.append(entry['data']) 453 | if 'labels' in entry: 454 | self.train_labels += entry['labels'] 455 | else: 456 | self.train_labels += entry['fine_labels'] 457 | fo.close() 458 | 459 | self.train_data = np.concatenate(self.train_data) 460 | self.train_data = self.train_data.reshape((50000, 3, 32, 32)) 461 | self.train_data = self.train_data.transpose((0, 2, 3, 1)) # convert to HWC 462 | # if noise_type is not None: 463 | # # noisify train data 464 | # self.train_labels=np.asarray([[self.train_labels[i]] for i in range(len(self.train_labels))]) 465 | # self.train_noisy_labels, self.actual_noise_rate = noisify(dataset=self.dataset, train_labels=self.train_labels, noise_type=noise_type, noise_rate=noise_rate, random_state=random_state, nb_classes=self.nb_classes) 466 | # self.train_noisy_labels=[i[0] for i in self.train_noisy_labels] 467 | # _train_labels=[i[0] for i in self.train_labels] 468 | # for i in range(len(_train_labels)): 469 | # idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 470 | # class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(100)] 471 | # self.noise_prior = np.array(class_size_noisy)/sum(class_size_noisy) 472 | # print(f'The noisy data ratio in each class is {self.noise_prior}') 473 | # self.noise_or_not = np.transpose(self.train_noisy_labels)!=np.transpose(_train_labels) 474 | if noise_type != 'clean': 475 | # noisify train data 476 | if noise_type in ['symmetric', 'pairflip']: 477 | self.train_labels = np.asarray([[self.train_labels[i]] for i in range(len(self.train_labels))]) 478 | self.train_noisy_labels, self.actual_noise_rate = noisify(dataset=self.dataset, 479 | train_labels=self.train_labels, 480 | noise_type=noise_type, 481 | noise_rate=noise_rate, 482 | random_state=random_state, 483 | nb_classes=self.nb_classes) 484 | self.train_noisy_labels = [i[0] for i in self.train_noisy_labels] 485 | _train_labels = [i[0] for i in self.train_labels] 486 | for i in range(len(_train_labels)): 487 | idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 488 | class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(100)] 489 | self.noise_prior = np.array(class_size_noisy) / sum(class_size_noisy) 490 | print(f'The noisy data ratio in each class is {self.noise_prior}') 491 | self.noise_or_not = np.transpose(self.train_noisy_labels) != np.transpose(_train_labels) 492 | elif noise_type == 'instance': 493 | self.train_noisy_labels, self.actual_noise_rate = noisify_instance(self.train_data, 494 | self.train_labels, 495 | noise_rate=noise_rate) 496 | print('over all noise rate is ', self.actual_noise_rate) 497 | # self.train_noisy_labels=[i[0] for i in self.train_noisy_labels] 498 | # self.train_noisy_labels=[i[0] for i in self.train_noisy_labels] 499 | # _train_labels=[i[0] for i in self.train_labels] 500 | for i in range(len(self.train_labels)): 501 | idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 502 | class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(100)] 503 | self.noise_prior = np.array(class_size_noisy) / sum(class_size_noisy) 504 | print(f'The noisy data ratio in each class is {self.noise_prior}') 505 | self.noise_or_not = np.transpose(self.train_noisy_labels) != np.transpose(self.train_labels) 506 | elif noise_type == 'manual': # manual noise 507 | # load noise label 508 | train_noisy_labels = self.load_label() 509 | self.train_noisy_labels = train_noisy_labels.numpy().tolist() 510 | print(f'noisy labels loaded from {self.noise_file}') 511 | 512 | for i in range(len(self.train_noisy_labels)): 513 | idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 514 | class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(100)] 515 | self.noise_prior = np.array(class_size_noisy) / sum(class_size_noisy) 516 | print(f'The noisy data ratio in each class is {self.noise_prior}') 517 | self.noise_or_not = np.transpose(self.train_noisy_labels) != np.transpose(self.train_labels) 518 | else: # random labels 519 | train_noisy_labels = self.load_label_human_new() 520 | self.train_noisy_labels = train_noisy_labels.tolist() 521 | print(f'noisy labels loaded from {self.noise_file}') 522 | 523 | for i in range(len(self.train_noisy_labels)): 524 | idx_each_class_noisy[self.train_noisy_labels[i]].append(i) 525 | class_size_noisy = [len(idx_each_class_noisy[i]) for i in range(100)] 526 | self.noise_prior = np.array(class_size_noisy) / sum(class_size_noisy) 527 | print(f'The noisy data ratio in each class is {self.noise_prior}') 528 | self.noise_or_not = np.transpose(self.train_noisy_labels) != np.transpose(self.train_labels) 529 | self.actual_noise_rate = np.sum(self.noise_or_not) / 50000 530 | print('over all noise rate is ', self.actual_noise_rate) 531 | 532 | else: 533 | f = self.test_list[0][0] 534 | file = os.path.join(self.root, self.base_folder, f) 535 | fo = open(file, 'rb') 536 | if sys.version_info[0] == 2: 537 | entry = pickle.load(fo) 538 | else: 539 | entry = pickle.load(fo, encoding='latin1') 540 | self.test_data = entry['data'] 541 | if 'labels' in entry: 542 | self.test_labels = entry['labels'] 543 | else: 544 | self.test_labels = entry['fine_labels'] 545 | fo.close() 546 | self.test_data = self.test_data.reshape((10000, 3, 32, 32)) 547 | self.test_data = self.test_data.transpose((0, 2, 3, 1)) # convert to HWC 548 | 549 | def load_label(self): 550 | ''' 551 | I adopt .pt rather .pth according to this discussion: 552 | https://github.com/pytorch/pytorch/issues/14864 553 | ''' 554 | # NOTE presently only use for load manual training label 555 | # noise_label = torch.load(self.noise_type) # f'../../{self.noise_type}' 556 | # noise_label = torch.load(f'noise_label/cifar-10/{self.noise_type}') 557 | assert self.noise_file != 'None' 558 | noise_label = torch.load(self.noise_file) 559 | if isinstance(noise_label, dict): 560 | if "clean_label_train" in noise_label.keys(): 561 | clean_label = noise_label['clean_label_train'] 562 | assert torch.sum(torch.tensor( 563 | self.train_labels) - clean_label) == 0 # commented for noise identification (NID) since we need to replace labels 564 | if "clean_label" in noise_label.keys() and 'raw_index' in noise_label.keys(): 565 | assert torch.sum( 566 | torch.tensor(self.train_labels)[noise_label['raw_index']] != noise_label['clean_label']) == 0 567 | noise_level = torch.sum(noise_label['clean_label'] == noise_label['noisy_label']) * 1.0 / ( 568 | noise_label['clean_label'].shape[0]) 569 | print(f'the overall noise level is {noise_level}') 570 | self.train_data = self.train_data[noise_label['raw_index']] 571 | return noise_label['noise_label_train'].view(-1).long() if 'noise_label_train' in noise_label.keys() else \ 572 | noise_label['noisy_label'].view(-1).long() # % 10 573 | 574 | else: 575 | return noise_label.view(-1).long() # % 10 576 | 577 | def __getitem__(self, index): 578 | """ 579 | Args: 580 | index (int): Index 581 | 582 | Returns: 583 | tuple: (image, target) where target is index of the target class. 584 | """ 585 | if self.train: 586 | # if self.noise_type is not None: 587 | if self.noise_type != 'clean': 588 | img, target = self.train_data[index], self.train_noisy_labels[index] 589 | else: 590 | img, target = self.train_data[index], self.train_labels[index] 591 | else: 592 | img, target = self.test_data[index], self.test_labels[index] 593 | 594 | # doing this so that it is consistent with all other datasets 595 | # to return a PIL Image 596 | img = Image.fromarray(img) 597 | 598 | if self.transform is not None: 599 | img = self.transform(img) 600 | 601 | if self.target_transform is not None: 602 | target = self.target_transform(target) 603 | 604 | return img, target, index 605 | 606 | def __len__(self): 607 | if self.train: 608 | return len(self.train_data) 609 | else: 610 | return len(self.test_data) 611 | 612 | def _check_integrity(self): 613 | root = self.root 614 | for fentry in (self.train_list + self.test_list): 615 | filename, md5 = fentry[0], fentry[1] 616 | fpath = os.path.join(root, self.base_folder, filename) 617 | if not check_integrity(fpath, md5): 618 | return False 619 | return True 620 | 621 | def download(self): 622 | import tarfile 623 | 624 | if self._check_integrity(): 625 | print('Files already downloaded and verified') 626 | return 627 | 628 | root = self.root 629 | download_url(self.url, root, self.filename, self.tgz_md5) 630 | 631 | # extract file 632 | cwd = os.getcwd() 633 | tar = tarfile.open(os.path.join(root, self.filename), "r:gz") 634 | os.chdir(root) 635 | tar.extractall() 636 | tar.close() 637 | os.chdir(cwd) 638 | 639 | def __repr__(self): 640 | fmt_str = 'Dataset ' + self.__class__.__name__ + '\n' 641 | fmt_str += ' Number of datapoints: {}\n'.format(self.__len__()) 642 | tmp = 'train' if self.train is True else 'test' 643 | fmt_str += ' Split: {}\n'.format(tmp) 644 | fmt_str += ' Root Location: {}\n'.format(self.root) 645 | tmp = ' Transforms (if any): ' 646 | fmt_str += '{0}{1}\n'.format(tmp, self.transform.__repr__().replace('\n', '\n' + ' ' * len(tmp))) 647 | tmp = ' Target Transforms (if any): ' 648 | fmt_str += '{0}{1}'.format(tmp, self.target_transform.__repr__().replace('\n', '\n' + ' ' * len(tmp))) 649 | return fmt_str 650 | 651 | def load_label_human_new(self): 652 | # NOTE only load manual training label 653 | noise_label = torch.load(self.noise_file) 654 | # import pdb 655 | # pdb.set_trace() 656 | if isinstance(noise_label, dict): 657 | if "clean_label" in noise_label.keys(): 658 | clean_label = torch.tensor(noise_label['clean_label']) 659 | assert torch.sum(torch.tensor(self.train_labels) - clean_label) == 0 660 | print(f'Loaded {self.noise_type} from {self.noise_file}.') 661 | print(f'The overall noise rate is {1 - np.mean(clean_label.numpy() == noise_label[self.noise_type])}') 662 | return noise_label[self.noise_type].reshape(-1) 663 | else: 664 | raise Exception('Input Error') 665 | --------------------------------------------------------------------------------