-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsentence_embeddings.py
213 lines (169 loc) · 6.38 KB
/
sentence_embeddings.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
# -*- coding: utf-8 -*-
"""CV Project.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1QJdGnX6GctRC2oJNrvW2hAnCpTrglagb
"""
# !pip install pytorch-transformers
# !pip install transformers
# from google.colab import files
# uploaded = files.upload()
import argparse
import os
import pickle
from random import randint
parser = argparse.ArgumentParser(description='algo to use for embeddings')
parser.add_argument('--algo', type=str, default='doc2vec', metavar='a',
help="algo to create embeddings: bert,doc2vec, infersent, VSE")
args = parser.parse_args()
import pandas as pd
table_data = pd.read_csv('/scratch/ans698/wiki_movie_plots_deduped.csv')['Release Year']
# print(dataset.head())
# print(len(dataset['Plot'][0]))
# max_len = dataset['Plot'].map(len).idxmax()
# print(max_len)
# dataset.iloc[26064]
# filtered_dataset = dataset[dataset['Plot'].str.len() <= 512]
# print(len(filtered_dataset))
# print(filtered_dataset['Plot'][0])
directory = '/scratch/ans698/combined_dataset/plot'
dataset = []
year = []
if os.path.isfile('plots.p'):
dataset = pickle.load(open( "plots.p", "rb" ))
year = pickle.load(open( "year.p", "rb" ))
else:
for filename in sorted(os.listdir(directory)):
with open(directory+'/'+filename, 'rb') as f:
dataset.append(f.read().decode(errors='ignore'))
year.append(table_data[int(filename.split('.')[0])])
pickle.dump(dataset,open( "plots.p", "wb" ))
pickle.dump(year,open( "year.p", "wb" ))
print(dataset[0])
print(year[0])
print(len(dataset))
def DistilBert():
import torch
from transformers import RobertaTokenizer,RobertaModel
# Transformers has a unified API
# for 8 transformer architectures and 30 pretrained weights.
# Model | Tokenizer | Pretrained weights shortcut
# MODELS = [(BertModel, BertTokenizer, 'bert-base-uncased'),
# (OpenAIGPTModel, OpenAIGPTTokenizer, 'openai-gpt'),
# (GPT2Model, GPT2Tokenizer, 'gpt2'),
# (CTRLModel, CTRLTokenizer, 'ctrl'),
# (TransfoXLModel, TransfoXLTokenizer, 'transfo-xl-wt103'),
# (XLNetModel, XLNetTokenizer, 'xlnet-base-cased'),
# (XLMModel, XLMTokenizer, 'xlm-mlm-enfr-1024'),
# (DistilBertModel, DistilBertTokenizer, 'distilbert-base-uncased'),
# (RobertaModel, RobertaTokenizer, 'roberta-base')]
tokenizer = RobertaTokenizer.from_pretrained('roberta-base')
encoded_text = pd.Series(dataset).apply((lambda x: tokenizer.encode(x, add_special_tokens=True)))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# model.resize_token_embeddings(len(encoded_text))
print(encoded_text[0])
print(len(encoded_text))
# print(dataset.map(len).max())
# model = RobertaModel.from_pretrained('roberta-base').to(device)
parallel_model = torch.nn.DataParallel(RobertaModel.from_pretrained('roberta-base').to(device))
import numpy as np
# max_len = 512
max_len = 0
for i in encoded_text.values:
if len(i) > max_len:
max_len = len(i)
padded = np.array([i + [0]*(max_len-len(i)) for i in encoded_text.values])
attention_mask = np.where(padded != 0, 1, 0)
print(attention_mask.shape)
input_ids = torch.tensor(padded).to(device)
attention_mask = torch.tensor(attention_mask).to(device)
with torch.no_grad():
last_hidden_states = parallel_model(input_ids, attention_mask=attention_mask)
embeddings = last_hidden_states[0][:,0,:].cpu().numpy()
print(embeddings[0])
print(embeddings.shape)
return embeddings
def doc2vec():
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
import nltk
from tqdm import tqdm
import multiprocessing
def tokenize_text(text):
tokens = []
for sent in tqdm(nltk.sent_tokenize(text)):
for word in nltk.word_tokenize(sent):
if len(word) < 2:
continue
tokens.append(word.lower())
return tokens
tagged_data = [TaggedDocument(words=tokenize_text(_d.lower()), tags=[year[i]]) for i, _d in enumerate(dataset)]
cores = multiprocessing.cpu_count()
print(tagged_data[0])
max_epochs = 30
vec_size = 512
alpha = 0.025
model = Doc2Vec(vector_size=vec_size,
alpha=alpha,
min_alpha=0.000025,
min_count=2,
workers=cores,
negative=5,
hs=0,
dm =1)
model.build_vocab([x for x in tqdm(tagged_data)])
# for epoch in range(max_epochs):
# print('iteration {0}'.format(epoch))
# model.train(tagged_data,
# total_examples=model.corpus_count,
# epochs=model.iter)
# # decrease the learning rate
# model.alpha -= 0.0002
# # fix the learning rate, no decay
# model.min_alpha = model.alpha
model.train(tagged_data,total_examples=model.corpus_count, epochs=max_epochs)
model.save("d2v.model")
print("Model Saved")
return [model.infer_vector(doc.words, steps=20) for doc in tagged_data]
def inferSent():
import nltk
# nltk.download('punkt')
from InferSent.models import InferSent
import torch
# use_cuda = True
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# model = model.cuda() if use_cuda else model
# V = 2
MODEL_PATH = 'encoder/infersent2.pkl'
params_model = {'bsize': 64, 'word_emb_dim': 300, 'enc_lstm_dim': 2048,
'pool_type': 'max', 'dpout_model': 0, 'version': 2}
infersent = InferSent(params_model).to(device)
infersent.load_state_dict(torch.load(MODEL_PATH))
W2V_PATH = 'fastText/crawl-300d-2M.vec'
infersent.set_w2v_path(W2V_PATH)
print('set w2v')
infersent.build_vocab(dataset, tokenize=True)
embeddings = infersent.encode(dataset,bsize=64, tokenize=True)
idx = randint(0, len(dataset))
_, _ = infersent.visualize(dataset[idx])
print('done')
return embeddings
def VSE():
embeddings = []
return embeddings
if args.algo == 'doc2vec':
embeddings = doc2vec()
pickle.dump( embeddings, open( "doc2vecEmbeddings.p", "wb" ) )
elif args.algo == 'bert':
embeddings = DistilBert()
pickle.dump( embeddings, open( "bertEmbeddings.p", "wb" ) )
elif args.algo == 'infersent':
embeddings = inferSent()
pickle.dump( embeddings, open( "infersentEmbeddingsGPU300.p", "wb" ) )
print(type(embeddings))
print(embeddings[0])
print(embeddings.shape)
print(embeddings[0].shape)
elif args.algo == 'vse':
VSE()
else:
print('WRONG')