- Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy path10_transformers.py
More file actions
Latest commit
104 lines (81 loc) · 2.48 KB
/
Copy path10_transformers.py
File metadata and controls
104 lines (81 loc) · 2.48 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
'''
Transforms can be applied to PIL images, tensors, ndarrays, or custom data
during creation of the DataSet
complete list of built-in transforms:
https://pytorch.org/docs/stable/torchvision/transforms.html
On Images
---------
CenterCrop, Grayscale, Pad, RandomAffine
RandomCrop, RandomHorizontalFlip, RandomRotation
Resize, Scale
On Tensors
----------
LinearTransformation, Normalize, RandomErasing
Conversion
----------
ToPILImage: from tensor or ndrarray
ToTensor : from numpy.ndarray or PILImage
Generic
-------
Use Lambda
Custom
------
Write own class
Compose multiple Transforms
---------------------------
composed = transforms.Compose([Rescale(256),
RandomCrop(224)])
'''
importtorch
importtorchvision
fromtorch.utils.dataimportDataset
importnumpyasnp
classWineDataset(Dataset):
def__init__(self, transform=None):
xy=np.loadtxt('./data/wine/wine.csv', delimiter=',', dtype=np.float32, skiprows=1)
self.n_samples=xy.shape[0]
# note that we do not convert to tensor here
self.x_data=xy[:, 1:]
self.y_data=xy[:, [0]]
self.transform=transform
def__getitem__(self, index):
sample=self.x_data[index], self.y_data[index]
ifself.transform:
sample=self.transform(sample)
returnsample
def__len__(self):
returnself.n_samples
# Custom Transforms
# implement __call__(self, sample)
classToTensor:
# Convert ndarrays to Tensors
def__call__(self, sample):
inputs, targets=sample
returntorch.from_numpy(inputs), torch.from_numpy(targets)
classMulTransform:
# multiply inputs with a given factor
def__init__(self, factor):
self.factor=factor
def__call__(self, sample):
inputs, targets=sample
inputs*=self.factor
returninputs, targets
print('Without Transform')
dataset=WineDataset()
first_data=dataset[0]
features, labels=first_data
print(type(features), type(labels))
print(features, labels)
print('\nWith Tensor Transform')
dataset=WineDataset(transform=ToTensor())
first_data=dataset[0]
features, labels=first_data
print(type(features), type(labels))
print(features, labels)
print('\nWith Tensor and Multiplication Transform')
composed=torchvision.transforms.Compose([ToTensor(), MulTransform(4)])
dataset=WineDataset(transform=composed)
first_data=dataset[0]
features, labels=first_data
print(type(features), type(labels))
print(features, labels)