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
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Mini Project 1 - Part 1: Getting Familiar with Word Embeddings.
2
+ # This assignment introduces students to text similarity measures using cosine similarity and sentence embeddings.
3
+ # Students will implement and compare different methods for computing and analyzing text similarity using GloVe and Sentence Transformers.
4
+
5
+ #Learning Objectives
6
+ #By the end of this assignment, students will:
7
+ #Understand how cosine similarity is used to measure text similarity.
8
+ #Learn to encode sentences using GloVe embeddings and Sentence Transformers.
9
+ #Compare the performance of different embedding techniques.
10
+ #Create a Web interface for your model
11
+
12
+ # Context: In this part, you are going to play around with some commonly used pretrained text embeddings for text search. For example, GloVe is an unsupervised learning algorithm for obtaining vector representations for words. Pretrained on
13
+ # 2 billion tweets with vocabulary size of 1.2 million. Download from [Stanford NLP](http://nlp.stanford.edu/data/glove.twitter.27B.zip).
14
+ # Jeffrey Pennington, Richard Socher, and Christopher D. Manning. 2014. *GloVe: Global Vectors for Word Representation*.
15
+
16
+
17
+ ### Import necessary libraries: here you will use streamlit library to run a text search demo, please make sure to install it.
18
+ import streamlit as st
19
+ import numpy as np
20
+ import pickle
21
+ import os
22
+ import gdown
23
+ from sentence_transformers import SentenceTransformer
24
+ import matplotlib.pyplot as plt
25
+
26
+
27
+ ### Some predefined utility functions for you to load the text embeddings
28
+
29
+ # Function to Load Glove Embeddings
30
+ def load_glove_embeddings(glove_path="Data/embeddings.pkl"):
31
+ with open(glove_path, "rb") as f:
32
+ embeddings_dict = pickle.load(f, encoding="latin1")
33
+
34
+ return embeddings_dict # A dictionary where the keys are words (or tokens) and the values are their corresponding GloVe embeddings.
35
+
36
+
37
+ def get_model_id_gdrive(model_type):
38
+ if model_type == "25d": # the dimension of the GloVe embeddings
39
+ word_index_id = "13qMXs3-oB9C6kfSRMwbAtzda9xuAUtt8" # Google Drive ID for the word index dictionary
40
+ embeddings_id = "1-RXcfBvWyE-Av3ZHLcyJVsps0RYRRr_2" # Google Drive ID for the embeddings file.
41
+ elif model_type == "50d":
42
+ embeddings_id = "1DBaVpJsitQ1qxtUvV1Kz7ThDc3az16kZ"
43
+ word_index_id = "1rB4ksHyHZ9skes-fJHMa2Z8J1Qa7awQ9"
44
+ elif model_type == "100d":
45
+ word_index_id = "1-oWV0LqG3fmrozRZ7WB1jzeTJHRUI3mq"
46
+ embeddings_id = "1SRHfX130_6Znz7zbdfqboKosz-PfNvNp"
47
+
48
+ return word_index_id, embeddings_id
49
+
50
+
51
+ def download_glove_embeddings_gdrive(model_type):
52
+ # Get glove embeddings from google drive
53
+ word_index_id, embeddings_id = get_model_id_gdrive(model_type)
54
+
55
+ # Use gdown to get files from google drive
56
+ embeddings_temp = "embeddings_" + str(model_type) + "_temp.npy"
57
+ word_index_temp = "word_index_dict_" + str(model_type) + "_temp.pkl"
58
+
59
+ # Download word_index pickle file
60
+ print("Downloading word index dictionary....\n")
61
+ gdown.download(id=word_index_id, output=word_index_temp, quiet=False)
62
+
63
+ # Download embeddings numpy file
64
+ print("Donwloading embedings...\n\n")
65
+ gdown.download(id=embeddings_id, output=embeddings_temp, quiet=False)
66
+
67
+
68
+ # @st.cache_data()
69
+ def load_glove_embeddings_gdrive(model_type):
70
+ word_index_temp = "word_index_dict_" + str(model_type) + "_temp.pkl"
71
+ embeddings_temp = "embeddings_" + str(model_type) + "_temp.npy"
72
+
73
+ # Load word index dictionary
74
+ word_index_dict = pickle.load(open(word_index_temp, "rb"), encoding="latin")
75
+
76
+ # Load embeddings numpy
77
+ embeddings = np.load(embeddings_temp)
78
+
79
+ return word_index_dict, embeddings
80
+
81
+
82
+ @st.cache_resource()
83
+ def load_sentence_transformer_model(model_name):
84
+ sentenceTransformer = SentenceTransformer(model_name)
85
+ return sentenceTransformer
86
+
87
+
88
+ def get_sentence_transformer_embeddings(sentence, model_name="all-MiniLM-L6-v2"):
89
+ """
90
+ Get sentence transformer embeddings for a sentence
91
+ """
92
+ # 384 dimensional embedding
93
+ # Default model: https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2
94
+
95
+ sentenceTransformer = load_sentence_transformer_model(model_name)
96
+
97
+ try:
98
+ return sentenceTransformer.encode(sentence)
99
+ except:
100
+ if model_name == "all-MiniLM-L6-v2":
101
+ return np.zeros(384)
102
+ else:
103
+ return np.zeros(512)
104
+
105
+
106
+ def get_glove_embeddings(word, word_index_dict, embeddings, model_type):
107
+ """
108
+ Get glove embedding for a single word
109
+ """
110
+ if word.lower() in word_index_dict:
111
+ return embeddings[word_index_dict[word.lower()]]
112
+ else:
113
+ return np.zeros(int(model_type.split("d")[0]))
114
+
115
+
116
+ def get_category_embeddings(embeddings_metadata):
117
+ """
118
+ Get embeddings for each category
119
+ 1. Split categories into words
120
+ 2. Get embeddings for each word
121
+ """
122
+ model_name = embeddings_metadata["model_name"]
123
+ st.session_state["cat_embed_" + model_name] = {}
124
+ for category in st.session_state.categories.split(" "):
125
+ if model_name:
126
+ if not category in st.session_state["cat_embed_" + model_name]:
127
+ st.session_state["cat_embed_" + model_name][category] = get_sentence_transformer_embeddings(category,
128
+ model_name=model_name)
129
+ else:
130
+ if not category in st.session_state["cat_embed_" + model_name]:
131
+ st.session_state["cat_embed_" + model_name][category] = get_sentence_transformer_embeddings(category)
132
+
133
+
134
+ def update_category_embeddings(embeddings_metadata):
135
+ """
136
+ Update embeddings for each category
137
+ """
138
+ get_category_embeddings(embeddings_metadata)
139
+
140
+
141
+ ### Plotting utility functions
142
+
143
+ def plot_piechart(sorted_cosine_scores_items):
144
+ sorted_cosine_scores = np.array([
145
+ sorted_cosine_scores_items[index][1]
146
+ for index in range(len(sorted_cosine_scores_items))
147
+ ]
148
+ )
149
+ categories = st.session_state.categories.split(" ")
150
+ categories_sorted = [
151
+ categories[sorted_cosine_scores_items[index][0]]
152
+ for index in range(len(sorted_cosine_scores_items))
153
+ ]
154
+ fig, ax = plt.subplots()
155
+ ax.pie(sorted_cosine_scores, labels=categories_sorted, autopct="%1.1f%%")
156
+ st.pyplot(fig) # Figure
157
+
158
+
159
+ def plot_piechart_helper(sorted_cosine_scores_items):
160
+ sorted_cosine_scores = np.array(
161
+ [
162
+ sorted_cosine_scores_items[index][1]
163
+ for index in range(len(sorted_cosine_scores_items))
164
+ ]
165
+ )
166
+ categories = st.session_state.categories.split(" ")
167
+ categories_sorted = [
168
+ categories[sorted_cosine_scores_items[index][0]]
169
+ for index in range(len(sorted_cosine_scores_items))
170
+ ]
171
+ fig, ax = plt.subplots(figsize=(3, 3))
172
+ my_explode = np.zeros(len(categories_sorted))
173
+ my_explode[0] = 0.2
174
+ if len(categories_sorted) == 3:
175
+ my_explode[1] = 0.1 # explode this by 0.2
176
+ elif len(categories_sorted) > 3:
177
+ my_explode[2] = 0.05
178
+ ax.pie(
179
+ sorted_cosine_scores,
180
+ labels=categories_sorted,
181
+ autopct="%1.1f%%",
182
+ explode=my_explode,
183
+ )
184
+
185
+ return fig
186
+
187
+
188
+ def plot_piecharts(sorted_cosine_scores_models):
189
+ scores_list = []
190
+ categories = st.session_state.categories.split(" ")
191
+ index = 0
192
+ for model in sorted_cosine_scores_models:
193
+ scores_list.append(sorted_cosine_scores_models[model])
194
+ # scores_list[index] = np.array([scores_list[index][ind2][1] for ind2 in range(len(scores_list[index]))])
195
+ index += 1
196
+
197
+ if len(sorted_cosine_scores_models) == 2:
198
+ fig, (ax1, ax2) = plt.subplots(2)
199
+
200
+ categories_sorted = [
201
+ categories[scores_list[0][index][0]] for index in range(len(scores_list[0]))
202
+ ]
203
+ sorted_scores = np.array(
204
+ [scores_list[0][index][1] for index in range(len(scores_list[0]))]
205
+ )
206
+ ax1.pie(sorted_scores, labels=categories_sorted, autopct="%1.1f%%")
207
+
208
+ categories_sorted = [
209
+ categories[scores_list[1][index][0]] for index in range(len(scores_list[1]))
210
+ ]
211
+ sorted_scores = np.array(
212
+ [scores_list[1][index][1] for index in range(len(scores_list[1]))]
213
+ )
214
+ ax2.pie(sorted_scores, labels=categories_sorted, autopct="%1.1f%%")
215
+
216
+ st.pyplot(fig)
217
+
218
+
219
+ def plot_alatirchart(sorted_cosine_scores_models):
220
+ models = list(sorted_cosine_scores_models.keys())
221
+ tabs = st.tabs(models)
222
+ figs = {}
223
+ for model in models:
224
+ figs[model] = plot_piechart_helper(sorted_cosine_scores_models[model])
225
+
226
+ for index in range(len(tabs)):
227
+ with tabs[index]:
228
+ st.pyplot(figs[models[index]])
229
+
230
+
231
+ ### Your Part To Complete: Follow the instructions in each function below to complete the similarity calculation between text embeddings
232
+
233
+ # Task I: Compute Cosine Similarity
234
+ def cosine_similarity(x, y):
235
+ """
236
+ Exponentiated cosine similarity
237
+ 1. Compute cosine similarity
238
+ 2. Exponentiate cosine similarity
239
+ 3. Return exponentiated cosine similarity
240
+ (20 pts)
241
+ """
242
+ ##################################
243
+ ### TODO: Add code here ##########
244
+ ##################################
245
+
246
+ # Ensure inputs are NumPy arrays
247
+ x = np.array(x)
248
+ y = np.array(y)
249
+
250
+ # Compute dot product
251
+ dot_product = np.dot(x, y)
252
+
253
+ # Compute L2 norms of both vectors
254
+ norm_x = np.linalg.norm(x)
255
+ norm_y = np.linalg.norm(y)
256
+
257
+ # Compute cosine similarity
258
+ cosine_sim = dot_product / (norm_x * norm_y)
259
+
260
+ # Exponentiate cosine similarity
261
+ exp_cosine_sim = np.exp(cosine_sim)
262
+
263
+ return exp_cosine_sim
264
+
265
+
266
+ # Task II: Average Glove Embedding Calculation
267
+ def averaged_glove_embeddings_gdrive(sentence, word_index_dict, embeddings, model_type=50):
268
+ """
269
+ Get averaged glove embeddings for a sentence
270
+ 1. Split sentence into words
271
+ 2. Get embeddings for each word
272
+ 3. Add embeddings for each word
273
+ 4. Divide by number of words
274
+ 5. Return averaged embeddings
275
+ (30 pts)
276
+ """
277
+ embedding = np.zeros(int(model_type.split("d")[0]))
278
+ ##################################
279
+ ##### TODO: Add code here ########
280
+ ##################################
281
+ # split sentence into words and convert to lowercase
282
+ words = sentence.lower().split()
283
+
284
+ # track the number of valid words found in the embeddings
285
+ valid_word_count = 0
286
+
287
+ for word in words:
288
+ if word in word_index_dict: # Check if the word exists in the vocabulary
289
+ index = word_index_dict[word] # Get the word's index in embeddings
290
+ embedding += embeddings[index] # Sum the corresponding embedding vector
291
+ valid_word_count += 1
292
+
293
+ # Compute the average embedding if any valid words were found
294
+ if valid_word_count > 0:
295
+ embedding /= valid_word_count
296
+
297
+ return embedding
298
+
299
+
300
+ # Task III: Sort the cosine similarity
301
+ # def get_sorted_cosine_similarity(embeddings_metadata):
302
+ # def get_sorted_cosine_similarity(embeddings_metadata, categories_input=None):
303
+ def get_sorted_cosine_similarity(text_search, embeddings_metadata):
304
+ """
305
+ Get sorted cosine similarity between input sentence and categories
306
+ Steps:
307
+ 1. Get embeddings for input sentence
308
+ 2. Get embeddings for categories (if not found, update category embeddings)
309
+ 3. Compute cosine similarity between input sentence and categories
310
+ 4. Sort cosine similarity
311
+ 5. Return sorted cosine similarity
312
+ (50 pts)
313
+ """
314
+ categories = st.session_state.categories.split(" ")
315
+ # categories = categories_input if categories_input is not None else st.session_state.categories.split(" ")
316
+ cosine_sim = {}
317
+ if embeddings_metadata["embedding_model"] == "glove":
318
+ word_index_dict = embeddings_metadata["word_index_dict"]
319
+ embeddings = embeddings_metadata["embeddings"]
320
+ model_type = embeddings_metadata["model_type"]
321
+
322
+ input_embedding = averaged_glove_embeddings_gdrive(text_search,
323
+ word_index_dict,
324
+ embeddings, model_type)
325
+
326
+ ##########################################
327
+ ## TODO: Get embeddings for categories ###
328
+ ##########################################
329
+ for index, category in enumerate(categories):
330
+ category_embedding = averaged_glove_embeddings_gdrive(
331
+ category,
332
+ word_index_dict,
333
+ embeddings,
334
+ model_type)
335
+ cosine_sim[index] = cosine_similarity(input_embedding, category_embedding)
336
+
337
+ else:
338
+ model_name = embeddings_metadata["model_name"]
339
+ if not "cat_embed_" + model_name in st.session_state:
340
+ get_category_embeddings(embeddings_metadata)
341
+
342
+ category_embeddings = st.session_state["cat_embed_" + model_name]
343
+
344
+ print("text_search = ", text_search)
345
+ if model_name:
346
+ input_embedding = get_sentence_transformer_embeddings(text_search, model_name=model_name)
347
+ else:
348
+ input_embedding = get_sentence_transformer_embeddings(text_search)
349
+
350
+ for index in range(len(categories)):
351
+ ##########################################
352
+ # TODO: Compute cosine similarity between input sentence and categories
353
+ # TODO: Update category embeddings if category not found
354
+ ##########################################
355
+ category = categories[index]
356
+ if category in category_embeddings:
357
+ category_embedding = category_embeddings[category]
358
+ cosine_sim[index] = cosine_similarity(input_embedding, category_embedding)
359
+ else:
360
+ update_category_embeddings(embeddings_metadata)
361
+ category_embedding = st.session_state["cat_embed_" + model_name][category]
362
+ cosine_sim[index] = cosine_similarity(input_embedding, category_embedding)
363
+
364
+ # Sort cosine similarities in descending order
365
+ sorted_items = sorted(cosine_sim.items(), key=lambda x: x[1], reverse=True)
366
+
367
+ return sorted_items
368
+
369
+
370
+ ### Below is the main function, creating the app demo for text search engine using the text embeddings.
371
+
372
+ if __name__ == "__main__":
373
+ ### Text Search ###
374
+ ### There will be Bonus marks of 10% for the teams that submit a URL for your deployed web app.
375
+ ### Bonus: You can also submit a publicly accessible link to the deployed web app.
376
+
377
+ st.sidebar.title("GloVe Twitter")
378
+ st.sidebar.markdown(
379
+ """
380
+ GloVe is an unsupervised learning algorithm for obtaining vector representations for words. Pretrained on
381
+ 2 billion tweets with vocabulary size of 1.2 million. Download from [Stanford NLP](http://nlp.stanford.edu/data/glove.twitter.27B.zip).
382
+
383
+ Jeffrey Pennington, Richard Socher, and Christopher D. Manning. 2014. *GloVe: Global Vectors for Word Representation*.
384
+ """
385
+ )
386
+
387
+ model_type = st.sidebar.selectbox("Choose the model", ("25d", "50d", "100d"), index=1)
388
+
389
+ st.title("Search Based Retrieval Demo")
390
+ st.subheader(
391
+ "Pass in space separated categories you want this search demo to be about."
392
+ )
393
+ # st.selectbox(label="Pick the categories you want this search demo to be about...",
394
+ # options=("Flowers Colors Cars Weather Food", "Chocolate Milk", "Anger Joy Sad Frustration Worry Happiness", "Positive Negative"),
395
+ # key="categories"
396
+ # )
397
+ st.text_input(
398
+ label="Categories", key="categories", value="Flowers Colors Cars Weather Food"
399
+ )
400
+ print(st.session_state["categories"])
401
+ print(type(st.session_state["categories"]))
402
+ # print("Categories = ", categories)
403
+ # st.session_state.categories = categories
404
+
405
+ st.subheader("Pass in an input word or even a sentence")
406
+ text_search = st.text_input(
407
+ label="Input your sentence",
408
+ key="text_search",
409
+ value="Roses are red, trucks are blue, and Seattle is grey right now",
410
+ )
411
+ # st.session_state.text_search = text_search
412
+
413
+ # Download glove embeddings if it doesn't exist
414
+ embeddings_path = "embeddings_" + str(model_type) + "_temp.npy"
415
+ word_index_dict_path = "word_index_dict_" + str(model_type) + "_temp.pkl"
416
+ if not os.path.isfile(embeddings_path) or not os.path.isfile(word_index_dict_path):
417
+ print("Model type = ", model_type)
418
+ glove_path = "Data/glove_" + str(model_type) + ".pkl"
419
+ print("glove_path = ", glove_path)
420
+
421
+ # Download embeddings from google drive
422
+ with st.spinner("Downloading glove embeddings..."):
423
+ download_glove_embeddings_gdrive(model_type)
424
+
425
+ # Load glove embeddings
426
+ word_index_dict, embeddings = load_glove_embeddings_gdrive(model_type)
427
+
428
+ # Find closest word to an input word
429
+ if st.session_state.text_search:
430
+ # Glove embeddings
431
+ print("Glove Embedding")
432
+ embeddings_metadata = {
433
+ "embedding_model": "glove",
434
+ "word_index_dict": word_index_dict,
435
+ "embeddings": embeddings,
436
+ "model_type": model_type,
437
+ }
438
+ with st.spinner("Obtaining Cosine similarity for Glove..."):
439
+ sorted_cosine_sim_glove = get_sorted_cosine_similarity(
440
+ st.session_state.text_search, embeddings_metadata
441
+ )
442
+
443
+ # Sentence transformer embeddings
444
+ print("Sentence Transformer Embedding")
445
+ embeddings_metadata = {"embedding_model": "transformers", "model_name": ""}
446
+ with st.spinner("Obtaining Cosine similarity for 384d sentence transformer..."):
447
+ sorted_cosine_sim_transformer = get_sorted_cosine_similarity(
448
+ st.session_state.text_search, embeddings_metadata
449
+ )
450
+
451
+ # Results and Plot Pie Chart for Glove
452
+ print("Categories are: ", st.session_state.categories)
453
+ st.subheader(
454
+ "Closest word I have between: "
455
+ + st.session_state.categories
456
+ + " as per different Embeddings"
457
+ )
458
+
459
+ print(sorted_cosine_sim_glove)
460
+ print(sorted_cosine_sim_transformer)
461
+ # print(sorted_distilbert)
462
+ # Altair Chart for all models
463
+ plot_alatirchart(
464
+ {
465
+ "glove_" + str(model_type): sorted_cosine_sim_glove,
466
+ "sentence_transformer_384": sorted_cosine_sim_transformer,
467
+ }
468
+ )
469
+ # "distilbert_512": sorted_distilbert})
470
+
471
+ st.write("")
472
+ st.write(
473
+ "Demo developed by Hongyan Liu and Yinxiu Wang(https://www.linkedin.com/in/your_id/ - Optional)"
474
+ )