-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.py
53 lines (46 loc) · 1.56 KB
/
encoder.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
import os
import torch
import pickle
from tqdm import tqdm
import dataset as ds
from splitter import Splitter
class Encoder:
def __init__(self, dataset: ds.Dataset):
self.loader = Splitter(batch_size=32).get_all(dataset)
self.dataset_name = str(dataset)
self.features = []
self.labels = []
self.pos_class = dataset.pos_class
print(f'Encoding: {self.dataset_name}')
if not os.path.exists('data'):
os.makedirs('data')
if not os.path.exists('data/encoded/'):
os.makedirs('data/encoded/')
self.root_dir = 'data/encoded/'
def encode(self):
features = []
labels = []
for data in tqdm(self.loader):
features.append(data['x'])
labels.append(data['y'])
self.features = torch.cat(features)
self.labels = torch.cat(labels)
def dump(self):
with open(f'{self.root_dir}/{self.dataset_name}_features.pt', 'wb') as f:
torch.save(self.features, f)
with open(f'{self.root_dir}/{self.dataset_name}_labels.pt', 'wb') as f:
torch.save(self.labels, f)
meta = {
'size': len(self.labels),
'n_classes': len(torch.unique(self.labels)),
'pos_class': self.pos_class
}
with open(f'{self.root_dir}/{self.dataset_name}_meta.pt', 'wb') as f:
pickle.dump(meta, f)
print(meta)
if __name__ == '__main__':
dataset_ = ds.UrbanSound8K()
dataset_.binarize()
encoder = Encoder(dataset_)
encoder.encode()
encoder.dump()