-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathdataset.py
62 lines (44 loc) · 1.8 KB
/
dataset.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May 17 11:05:05 2021
@author: laurent
"""
import torch
from torch.utils.data.sampler import SubsetRandomSampler
import torchvision
def getSets(filteredClass = None, removeFiltered = True) :
"""
Return a torch dataset
"""
train = torchvision.datasets.MNIST('./data/', train=True, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.1307,), (0.3081,))
]))
test = torchvision.datasets.MNIST('./data/', train=False, download=True,
transform=torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.1307,), (0.3081,))
]))
if filteredClass is not None :
train_loader = torch.utils.data.DataLoader(train, batch_size=len(train))
train_labels = next(iter(train_loader))[1].squeeze()
test_loader = torch.utils.data.DataLoader(test, batch_size=len(test))
test_labels = next(iter(test_loader))[1].squeeze()
if removeFiltered :
trainIndices = torch.nonzero(train_labels != filteredClass).squeeze()
testIndices = torch.nonzero(test_labels != filteredClass).squeeze()
else :
trainIndices = torch.nonzero(train_labels == filteredClass).squeeze()
testIndices = torch.nonzero(test_labels == filteredClass).squeeze()
train = torch.utils.data.Subset(train, trainIndices)
test = torch.utils.data.Subset(test, testIndices)
return train, test
if __name__ == "__main__" :
#test getSets function
train, test = getSets(filteredClass = 3, removeFiltered = False)
test_loader = torch.utils.data.DataLoader(test, batch_size=len(test))
images, labels = next(iter(test_loader))
print(images.shape)
print(torch.unique(labels.squeeze()))