-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsentence_encoder.py
194 lines (156 loc) · 6.6 KB
/
sentence_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
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
import nltk
from InferSent.models import InferSent
from torch.utils.data import Dataset, DataLoader
import torch
import pandas as pd
import pickle
class TextBookDataset(Dataset):
"""
Dataset for title classification
"""
def __init__(self, csv_file, datasetTransform, transform=None):
cols = ["index", "filename", "url", "title", "author", "class", "class_name"]
self.dataset = pd.read_csv(csv_file, header = None, names = cols, encoding = "ISO-8859-1")
self.titles = datasetTransform.transform_titles(self.dataset)
self.transform = transform
#Create list of classes
df = self.dataset.reset_index().drop_duplicates(subset='class', keep='last').set_index('index')
df = df.sort_values(by=['class'])
self.classes = df['class_name'].tolist()
def __len__(self):
return len(self.dataset)
def __getitem__(self, idx):
line = self.dataset.iloc[idx]
title = self.titles[idx]
label = line["class"]
if self.transform:
cover = self.transform(cover)
return (torch.from_numpy(title).float(), label)
class SentenceEmbedding():
"""
Embed sentences using Infersent and FastText word embedding
"""
def __init__(self, csvFiles):
"""
csvFiles: A list of csv files containing the datasets used.
"""
V = 2
MODEL_PATH = 'InferSent/encoder/infersent%s.pickle' % V
params_model = {'bsize': 64, 'word_emb_dim': 300, 'enc_lstm_dim': 2048,
'pool_type': 'max', 'dpout_model': 0.0, 'version': V}
self.infersent = InferSent(params_model)
self.infersent.cuda()
self.infersent.load_state_dict(torch.load(MODEL_PATH))
W2V_PATH = 'InferSent/dataset/fastText/crawl-300d-2M-subword.vec'
self.infersent.set_w2v_path(W2V_PATH)
sentences = []
for file in csvFiles:
cols = ["index", "filename", "url", "title", "author", "class", "class_name"]
dataset = pd.read_csv(file, header = None, names = cols, encoding = "ISO-8859-1")
titles = dataset['title'].tolist()
sentences.extend(titles)
self.infersent.build_vocab(sentences, tokenize=True)
def transform_titles(self, dataset):
transformedTitles = self.infersent.encode(dataset['title'], tokenize=True)
print(transformedTitles.shape)
print(type(transformedTitles))
print(type(transformedTitles[0]))
return transformedTitles
class SentenceEmbeddingGlove():
"""
Embed sentences using Infersent and Glove word embedding
"""
def __init__(self, csvFiles):
"""
csvFiles: A list of csv files containing the datasets used.
"""
V = 1
MODEL_PATH = 'InferSent/encoder/infersent%s.pickle' % V
params_model = {'bsize': 64, 'word_emb_dim': 300, 'enc_lstm_dim': 2048,
'pool_type': 'max', 'dpout_model': 0.0, 'version': V}
self.infersent = InferSent(params_model)
self.infersent.cuda()
self.infersent.load_state_dict(torch.load(MODEL_PATH))
W2V_PATH = 'InferSent/dataset/fastText/crawl-300d-2M-subword.vec'
self.infersent.set_w2v_path(W2V_PATH)
sentences = []
for file in csvFiles:
cols = ["index", "filename", "url", "title", "author", "class", "class_name"]
dataset = pd.read_csv(file, header = None, names = cols, encoding = "ISO-8859-1")
titles = dataset['title'].tolist()
sentences.extend(titles)
self.infersent.build_vocab(sentences, tokenize=True)
def transform_titles(self, dataset):
transformedTitles = self.infersent.encode(dataset['title'], tokenize=True)
print(transformedTitles.shape)
print(type(transformedTitles))
print(type(transformedTitles[0]))
return transformedTitles
def create_text_data_loaders(train_csv_file, val_csv_file, test_csv_file, batch_size, num_workers = 1, word_emb = "FastText"):
"""
Create dataloaders for title classification with InferSent
"""
if word_emb == "FastText":
datasetTransform = SentenceEmbedding([train_csv_file, val_csv_file, test_csv_file])
elif word_emb == "Glove":
datasetTransform = SentenceEmbeddingGlove([train_csv_file, val_csv_file, test_csv_file])
else:
return None
print("creating datasets")
train_set = TextBookDataset(train_csv_file, datasetTransform = datasetTransform)
val_set = TextBookDataset(val_csv_file, datasetTransform = datasetTransform)
test_set = TextBookDataset(test_csv_file, datasetTransform = datasetTransform)
print("creating dataloaders")
data_loaders = {
"train": DataLoader(train_set, batch_size = batch_size, shuffle = True,
num_workers = num_workers),
"val": DataLoader(val_set, batch_size = batch_size, shuffle = True,
num_workers = num_workers),
"test": DataLoader(test_set, batch_size = batch_size, shuffle = True,
num_workers = num_workers)
}
return data_loaders
def save_text_data_loaders(pickle_file_name, batch_size, num_workers = 0, word_emb = "FastText"):
"""
Save dataloaders for title classification with InferSent
"""
train_csv_path = "dataset/train_set_cleaned.csv"
val_csv_path = "dataset/validation_set_cleaned.csv"
test_csv_path = "dataset/book30-listing-test_cleaned.csv"
data_loaders = create_text_data_loaders(train_csv_path, val_csv_path, test_csv_path, batch_size, num_workers, word_emb)
if data_loaders:
print("pickling dataloaders")
with open(pickle_file_name, "wb") as fp:
pickle.dump(data_loaders, fp)
else:
print("Invalid word_emb arg")
def save_text_10_classes_data_loaders(pickle_file_name, batch_size, num_workers = 0, word_emb = "FastText"):
"""
Create dataloaders for title classification with InferSent
for 10 classes dataset
"""
train_csv_path = "dataset/train_set_cleaned_10.csv"
val_csv_path = "dataset/validation_set_cleaned_10.csv"
test_csv_path = "dataset/book30-listing-test_cleaned_10.csv"
data_loaders = create_text_data_loaders(train_csv_path, val_csv_path, test_csv_path, batch_size, num_workers, word_emb)
if data_loaders:
print("pickling dataloaders")
with open(pickle_file_name, "wb") as fp:
pickle.dump(data_loaders, fp)
else:
print("Invalid word_emb arg")
if __name__ == "__main__":
BATCH_SIZES = [4, 8, 16, 32, 64]
nltk.download('punkt')
for batch_size in BATCH_SIZES:
"""
pickle_file_name = "dataloaders/encoded_text_data_loaders_{}.pickle".format(batch_size)
save_text_data_loaders(pickle_file_name, batch_size, 0)
pickle_file_name = "dataloaders/final_encoded_text_data_loaders_{}.pickle".format(batch_size)
save_final_text_data_loaders(pickle_file_name, batch_size, 0)
pickle_file_name = "dataloaders/encoded_text_data_loaders_glove_{}.pickle".format(batch_size)
save_text_data_loaders(pickle_file_name, batch_size, 0, "Glove")
pickle_file_name = "dataloaders/final_encoded_text_data_loaders_glove_{}.pickle".format(batch_size)
save_final_text_data_loaders(pickle_file_name, batch_size, 0, "Glove")
"""
save_text_10_classes_data_loaders("dataloaders/encoded_text_data_loaders_{}_10.pickle".format(batch_size), batch_size)