-
Notifications
You must be signed in to change notification settings - Fork 0
/
data.py
239 lines (214 loc) · 10.4 KB
/
data.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
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
import argparse
import numpy as np
import pandas as pd
import tensorly as tl
import torch
import os
from torchvision import transforms
from PIL import Image
from torch.utils.data import Dataset
from sklearn.model_selection import train_test_split
from sklearn.dummy import DummyClassifier
tl.set_backend('pytorch')
parser = argparse.ArgumentParser(
description="Handles processing and chunking of dataset",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--dataset-path",
default="",
type=str,
help="Path to the EPIC-KITCHENS folder on the device"
)
parser.add_argument(
"--label",
default="EPIC",
type=str,
help="Label to prepend to preprocessed dataset files"
)
parser.add_argument(
"--num-annotations",
default=1000,
type=int,
help="Number of annotations to preprocess from EPIC-KITCHENS"
)
parser.add_argument(
"--chunks",
default=1,
type=int,
help="Number of evenly sized chunks to preprocess into"
)
parser.add_argument(
"--ratio",
nargs=3,
default=[80, 10, 10],
type=int,
help="Ratio of train/val/test splits respectively in preprocessed dataset"
)
parser.add_argument(
"--seed",
default=0,
type=int,
help="Random seed used to generate train/val/test splits"
)
parser.add_argument(
"--segment-count",
default=8,
type=int,
help="Number of temporal segments to sample from"
)
parser.add_argument(
"--random-perf",
default=False,
action="store_true",
help="Print random performance of dataset splits"
)
class PreprocessedEPICDataset(Dataset):
def __init__(self, dataprocessor, label, chunks, split_type):
self.dataprocessor = dataprocessor
self.label = label
self.chunks = chunks
self.split_type = split_type
self.length = 0
for i in range(1, chunks + 1):
self.length += dataprocessor.load_from_pt(label, f'{label}_{i}_{split_type}_Y.pt').size(0)
self.chunk_reference = {}
chunk_index = 1
for chunk in np.array_split(np.arange(self.length), chunks):
element_index = 0
for element in chunk:
self.chunk_reference.update({str(element): {'chunk_index': chunk_index,'element_index': element_index}})
element_index += 1
chunk_index += 1
def __getitem__(self, index):
chunk_index = self.chunk_reference[str(index)]['chunk_index']
element_index = self.chunk_reference[str(index)]['element_index']
x = self.dataprocessor.load_from_pt(self.label, f'{self.label}_{chunk_index}_{self.split_type}_X.pt')[element_index]
y = self.dataprocessor.load_from_pt(self.label, f'{self.label}_{chunk_index}_{self.split_type}_Y.pt')[element_index]
return x, y
def __len__(self):
return self.length
class PostprocessedEPICDataset(Dataset):
def __init__(self, dataset_path, annotations, transform, segment_count):
self.dataset_path = dataset_path
self.annotations = annotations
self.transform = transform
self.segment_count = segment_count
def __getitem__(self, index):
participant_id = self.annotations.at[index, 'participant_id']
video_id = self.annotations.at[index, 'video_id']
start_frame = self.annotations.at[index, 'start_frame']
stop_frame = self.annotations.at[index, 'stop_frame']
zero = '0'
segments = np.array_split(
np.arange(start_frame, stop_frame + 1), self.segment_count)
frames = []
for i in range(self.segment_count):
snippet = str(np.random.default_rng().choice(segments[i]))
file_name = f'{(10 - len(snippet)) * zero}{snippet}'
frame = self.transform(Image.open(f'{self.dataset_path}/{participant_id}/rgb_frames/{video_id}/frame_{file_name}.jpg'))
frames.append(frame)
return torch.stack(frames), self.annotations.loc[:, ['verb_class', 'noun_class']].values[index]
def __len__(self):
return len(self.annotations)
class DataProcessor:
def __init__(self, dataset_path, annotations_path, data_path):
self.dataset_path = dataset_path
self.annotations = pd.read_csv(
f'{annotations_path}/EPIC.csv')
self.data_path = data_path
def get_annotation_snippets(self, annotation, segment_count):
participant_id = annotation[0]
video_id = annotation[1]
start_frame = annotation[2]
stop_frame = annotation[3]
zero = '0'
transform = transforms.Compose(
[transforms.PILToTensor(), transforms.Resize((224, 224))])
segments = np.array_split(
np.arange(start_frame, stop_frame + 1), segment_count)
frames = []
for i in range(segment_count):
snippet = str(np.random.default_rng().choice(segments[i]))
file_name = f'{(10 - len(snippet)) * zero}{snippet}'
frame = transform(Image.open(f'{self.dataset_path}/{participant_id}/rgb_frames/{video_id}/frame_{file_name}.jpg'))
frames.append(frame)
return torch.stack(frames)
def get_split(self, split, segment_count):
annotations = split.loc[:, ['participant_id', 'video_id', 'start_frame', 'stop_frame']].values
split_X = torch.stack(
list(map(lambda x: self.get_annotation_snippets(x, segment_count), annotations)))
split_Y = torch.tensor(split.loc[:, ['verb_class', 'noun_class']].values)
return split_X, split_Y
def split_annotations(self, num_annotations, ratio, seed):
train_size = ratio[0]/100.0
train, temp = train_test_split(self.annotations[:num_annotations], train_size=train_size , random_state=seed)
val_size = (ratio[1]/100.0) / (ratio[1]/100.0 + ratio[2]/100.0)
val, test = train_test_split(temp, train_size=val_size, random_state=seed)
return train, val, test
def save_to_pt(self, label, filename, tensor):
if not os.path.exists(f'{self.data_path}/{label}'):
os.makedirs(f'{self.data_path}/{label}')
torch.save(tensor, f'{self.data_path}/{label}/{filename}')
def load_from_pt(self, label, filename):
return torch.load(f'{self.data_path}/{label}/{filename}')
def load_annotations(self, label):
train = pd.read_csv(f'{self.data_path}/{label}/{label}_train.csv')
val = pd.read_csv(f'{self.data_path}/{label}/{label}_val.csv')
test = pd.read_csv(f'{self.data_path}/{label}/{label}_test.csv')
return train, val, test
def preprocess_epic(label, num_annotations, chunks, ratio, dataprocessor, segment_count, seed):
train, val, test = dataprocessor.split_annotations(num_annotations, ratio, seed)
train_chunks = np.array_split(train, chunks)
for i in range(len(train_chunks)):
chunk_X, chunk_Y = dataprocessor.get_split(train_chunks[i].reset_index(), segment_count)
dataprocessor.save_to_pt(label, f'{label}_{i + 1}_train_X.pt', chunk_X)
dataprocessor.save_to_pt(label, f'{label}_{i + 1}_train_Y.pt', chunk_Y)
val_chunks = np.array_split(val, chunks)
for i in range(len(val_chunks)):
chunk_X, chunk_Y = dataprocessor.get_split(val_chunks[i].reset_index(), segment_count)
dataprocessor.save_to_pt(label, f'{label}_{i + 1}_val_X.pt', chunk_X)
dataprocessor.save_to_pt(label, f'{label}_{i + 1}_val_Y.pt', chunk_Y)
test_chunks = np.array_split(test, chunks)
for i in range(len(test_chunks)):
chunk_X, chunk_Y = dataprocessor.get_split(test_chunks[i].reset_index(), segment_count)
dataprocessor.save_to_pt(label, f'{label}_{i + 1}_test_X.pt', chunk_X)
dataprocessor.save_to_pt(label, f'{label}_{i + 1}_test_Y.pt', chunk_Y)
train.reset_index(drop=True).to_csv(f'{dataprocessor.data_path}/{label}/{label}_train.csv', index=False)
val.reset_index(drop=True).to_csv(f'{dataprocessor.data_path}/{label}/{label}_val.csv', index=False)
test.reset_index(drop=True).to_csv(f'{dataprocessor.data_path}/{label}/{label}_test.csv', index=False)
def main(args):
dataprocessor = DataProcessor(args.dataset_path, 'annotations', 'data')
if args.random_perf:
train, val, test = dataprocessor.load_annotations(args.label)
verb_clf, noun_clf = DummyClassifier(strategy='stratified', random_state=0), DummyClassifier(strategy='stratified', random_state=0)
verb_clf = verb_clf.fit(None, train['verb_class'])
noun_clf = noun_clf.fit(None, train['noun_class'])
accuracies = []
for i in range(1000):
accuracies.append([verb_clf.score(None, train["verb_class"]),
noun_clf.score(None, train["noun_class"]),
verb_clf.score(None, val["verb_class"]),
noun_clf.score(None, val["noun_class"]),
verb_clf.score(None, test["verb_class"]),
noun_clf.score(None, test["noun_class"])])
accuracies = np.mean(np.array(accuracies), axis=0)
print(f'random train verb {accuracies[0]* 100:.2f}, random train noun {accuracies[1]* 100:.2f}')
print(f'random val verb {accuracies[2]* 100:.2f}, random val noun {accuracies[3]* 100:.2f}')
print(f'random test verb {accuracies[4]* 100:.2f}, random test noun {accuracies[5]* 100:.2f}')
verb_clf, noun_clf = DummyClassifier(strategy='most_frequent'), DummyClassifier(strategy='most_frequent')
verb_clf = verb_clf.fit(None, train['verb_class'])
noun_clf = noun_clf.fit(None, train['noun_class'])
accuracies = [verb_clf.score(None, train["verb_class"]),
noun_clf.score(None, train["noun_class"]),
verb_clf.score(None, val["verb_class"]),
noun_clf.score(None, val["noun_class"]),
verb_clf.score(None, test["verb_class"]),
noun_clf.score(None, test["noun_class"])]
print(f'deterministic train verb {accuracies[0]* 100:.2f}, deterministic train noun {accuracies[1]* 100:.2f}')
print(f'deterministic val verb {accuracies[2]* 100:.2f}, deterministic val noun {accuracies[3]* 100:.2f}')
print(f'deterministic test verb {accuracies[4]* 100:.2f}, deterministic test noun {accuracies[5]* 100:.2f}')
else:
preprocess_epic(args.label, args.num_annotations, args.chunks, tuple(args.ratio), dataprocessor, args.segment_count, args.seed)
if __name__ == "__main__":
main(parser.parse_args())