-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_data.py
78 lines (59 loc) · 2.67 KB
/
gen_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
import os
import json
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from transformers import ElectraTokenizer
from torchvision.transforms import transforms
from args import MyArgs
from preprocessing import zip_image_text_label
class MyDataset(Dataset):
def __init__(self, data, label2idx, tokenizer, max_length=256):
super(MyDataset, self).__init__()
self.data = data
self.label2idx = label2idx
self.tokenizer = tokenizer
self.max_length = max_length
def __len__(self):
return len(self.data)
def __getitem__(self, item):
image = self.data[item][0]
text = self.data[item][1]
label = self.data[item][2]
tokenizer_result = self.tokenizer.encode_plus(text, add_special_tokens=True, \
max_length=self.max_length, \
padding="max_length", \
return_tensors="pt")
input_ids = tokenizer_result["input_ids"].squeeze(dim=0)
attention_mask = tokenizer_result["attention_mask"].squeeze(dim=0)
if input_ids.shape[-1] != self.max_length:
input_ids = input_ids[:self.max_length]
if attention_mask.shape[-1] != self.max_length:
attention_mask = attention_mask[:self.max_length]
label = self.label2idx[label]
return image, input_ids, attention_mask, label
class MyTestDataset(Dataset):
def __init__(self, data, tokenizer, max_length=256):
super(MyTestDataset, self).__init__()
self.data = data
self.tokenizer = tokenizer
self.max_length = max_length
def __len__(self):
return len(self.data)
def __getitem__(self, item):
image = self.data[item][0]
text = self.data[item][1]
image_name = self.data[item][2]
tokenizer_result = self.tokenizer.encode_plus(text, add_special_tokens=True, \
max_length=self.max_length, \
padding="max_length", \
return_tensors="pt")
input_ids = tokenizer_result["input_ids"].squeeze(dim=0)
attention_mask = tokenizer_result["attention_mask"].squeeze(dim=0)
if input_ids.shape[-1] != self.max_length:
input_ids = input_ids[:self.max_length]
if attention_mask.shape[-1] != self.max_length:
attention_mask = attention_mask[:self.max_length]
return image, input_ids, attention_mask, image_name