Path: blob/main/a1/exploring_word_vectors_22_23.ipynb
995 views
CS224N Assignment 1: Exploring Word Vectors (25 Points)
Due 4:30pm, Tue Jan 17
Welcome to CS224N!
Before you start, make sure you read the README.txt in the same directory as this notebook for important setup information. A lot of code is provided in this notebook, and we highly encourage you to read and understand it as part of the learning 😃
If you aren't super familiar with Python, Numpy, or Matplotlib, we recommend you check out the review session on Friday. The session will be recorded and the material will be made available on our website. The CS231N Python/Numpy tutorial is also a great resource.
Assignment Notes: Please make sure to save the notebook as you go along. Submission Instructions are located at the bottom of the notebook.
Word Vectors
Word Vectors are often used as a fundamental component for downstream NLP tasks, e.g. question answering, text generation, translation, etc., so it is important to build some intuitions as to their strengths and weaknesses. Here, you will explore two types of word vectors: those derived from co-occurrence matrices, and those derived via GloVe.
Note on Terminology: The terms "word vectors" and "word embeddings" are often used interchangeably. The term "embedding" refers to the fact that we are encoding aspects of a word's meaning in a lower dimensional space. As Wikipedia states, "conceptually it involves a mathematical embedding from a space with one dimension per word to a continuous vector space with a much lower dimension".
Part 1: Count-Based Word Vectors (10 points)
Most word vector models start from the following idea:
You shall know a word by the company it keeps (Firth, J. R. 1957:11)
Many word vector implementations are driven by the idea that similar words, i.e., (near) synonyms, will be used in similar contexts. As a result, similar words will often be spoken or written along with a shared subset of words, i.e., contexts. By examining these contexts, we can try to develop embeddings for our words. With this intuition in mind, many "old school" approaches to constructing word vectors relied on word counts. Here we elaborate upon one of those strategies, co-occurrence matrices (for more information, see here or here).
Co-Occurrence
A co-occurrence matrix counts how often things co-occur in some environment. Given some word occurring in the document, we consider the context window surrounding . Supposing our fixed window size is , then this is the preceding and subsequent words in that document, i.e. words and . We build a co-occurrence matrix , which is a symmetric word-by-word matrix in which is the number of times appears inside 's window among all documents.
Example: Co-Occurrence with Fixed Window of n=1:
Document 1: "all that glitters is not gold"
Document 2: "all is well that ends well"
* | <START> | all | that | glitters | is | not | gold | well | ends | <END> |
---|---|---|---|---|---|---|---|---|---|---|
<START> | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
all | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
that | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 |
glitters | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 |
is | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 |
not | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 |
gold | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 1 |
well | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 |
ends | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 |
<END> | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
Note: In NLP, we often add <START>
and <END>
tokens to represent the beginning and end of sentences, paragraphs or documents. In this case we imagine <START>
and <END>
tokens encapsulating each document, e.g., "<START>
All that glitters is not gold <END>
", and include these tokens in our co-occurrence counts.
The rows (or columns) of this matrix provide one type of word vectors (those based on word-word co-occurrence), but the vectors will be large in general (linear in the number of distinct words in a corpus). Thus, our next step is to run dimensionality reduction. In particular, we will run SVD (Singular Value Decomposition), which is a kind of generalized PCA (Principal Components Analysis) to select the top principal components. Here's a visualization of dimensionality reduction with SVD. In this picture our co-occurrence matrix is with rows corresponding to words. We obtain a full matrix decomposition, with the singular values ordered in the diagonal matrix, and our new, shorter length- word vectors in .
This reduced-dimensionality co-occurrence representation preserves semantic relationships between words, e.g. doctor and hospital will be closer than doctor and dog.
Notes: If you can barely remember what an eigenvalue is, here's a slow, friendly introduction to SVD. If you want to learn more thoroughly about PCA or SVD, feel free to check out lectures 7, 8, and 9 of CS168. These course notes provide a great high-level treatment of these general purpose algorithms. Though, for the purpose of this class, you only need to know how to extract the k-dimensional embeddings by utilizing pre-programmed implementations of these algorithms from the numpy, scipy, or sklearn python packages. In practice, it is challenging to apply full SVD to large corpora because of the memory needed to perform PCA or SVD. However, if you only want the top vector components for relatively small — known as Truncated SVD — then there are reasonably scalable techniques to compute those iteratively.
Plotting Co-Occurrence Word Embeddings
Here, we will be using the Reuters (business and financial news) corpus. If you haven't run the import cell at the top of this page, please run it now (click it and press SHIFT-RETURN). The corpus consists of 10,788 news documents totaling 1.3 million words. These documents span 90 categories and are split into train and test. For more details, please see https://www.nltk.org/book/ch02.html. We provide a read_corpus
function below that pulls out only articles from the "gold" (i.e. news articles about gold, mining, etc.) category. The function also adds <START>
and <END>
tokens to each of the documents, and lowercases words. You do not have to perform any other kind of pre-processing.
Let's have a look what these documents are like….
Question 1.1: Implement distinct_words
[code] (2 points)
Write a method to work out the distinct words (word types) that occur in the corpus. You can do this with for
loops, but it's more efficient to do it with Python list comprehensions. In particular, this may be useful to flatten a list of lists. If you're not familiar with Python list comprehensions in general, here's more information.
Your returned corpus_words
should be sorted. You can use python's sorted
function for this.
You may find it useful to use Python sets to remove duplicate words.
Question 1.2: Implement compute_co_occurrence_matrix
[code] (3 points)
Write a method that constructs a co-occurrence matrix for a certain window-size (with a default of 4), considering words before and after the word in the center of the window. Here, we start to use numpy (np)
to represent vectors, matrices, and tensors. If you're not familiar with NumPy, there's a NumPy tutorial in the second half of this cs231n Python NumPy tutorial.
Question 1.3: Implement reduce_to_k_dim
[code] (1 point)
Construct a method that performs dimensionality reduction on the matrix to produce k-dimensional embeddings. Use SVD to take the top k components and produce a new matrix of k-dimensional embeddings.
Note: All of numpy, scipy, and scikit-learn (sklearn
) provide some implementation of SVD, but only scipy and sklearn provide an implementation of Truncated SVD, and only sklearn provides an efficient randomized algorithm for calculating large-scale Truncated SVD. So please use sklearn.decomposition.TruncatedSVD.
Question 1.4: Implement plot_embeddings
[code] (1 point)
Here you will write a function to plot a set of 2D vectors in 2D space. For graphs, we will use Matplotlib (plt
).
For this example, you may find it useful to adapt this code. In the future, a good way to make a plot is to look at the Matplotlib gallery, find a plot that looks somewhat like what you want, and adapt the code they give.
Question 1.5: Co-Occurrence Plot Analysis [written] (3 points)
Now we will put together all the parts you have written! We will compute the co-occurrence matrix with fixed window of 4 (the default window size), over the Reuters "gold" corpus. Then we will use TruncatedSVD to compute 2-dimensional embeddings of each word. TruncatedSVD returns U*S, so we need to normalize the returned vectors, so that all the vectors will appear around the unit circle (therefore closeness is directional closeness). Note: The line of code below that does the normalizing uses the NumPy concept of broadcasting. If you don't know about broadcasting, check out Computation on Arrays: Broadcasting by Jake VanderPlas.
Run the below cell to produce the plot. It'll probably take a few seconds to run.
Verify that your figure matches "question_1.5.png" in the assignment zip. If not, use that figure to answer the next two questions.
a. Find at least two groups of words that cluster together in 2-dimensional embedding space. Give an explanation for each cluster you observe.
SOLUTION BEGIN
For example, the word "silver" and 'reserves' is belong to the same group, because they all mean some resources.
The word "Platium" and "metal" is in the same group, because they all mean some metal or chemstry materials.
SOLUTION END
b. What doesn't cluster together that you might think should have? Describe at least two examples.
SOLUTION BEGIN
China and Australia should be clustered together, because they both are country.
copper is a kind of metal but not be clustered together with "metal".
SOLUTION END
Part 2: Prediction-Based Word Vectors (15 points)
As discussed in class, more recently prediction-based word vectors have demonstrated better performance, such as word2vec and GloVe (which also utilizes the benefit of counts). Here, we shall explore the embeddings produced by GloVe. Please revisit the class notes and lecture slides for more details on the word2vec and GloVe algorithms. If you're feeling adventurous, challenge yourself and try reading GloVe's original paper.
Then run the following cells to load the GloVe vectors into memory. Note: If this is your first time to run these cells, i.e. download the embedding model, it will take a couple minutes to run. If you've run these cells before, rerunning them will load the model without redownloading it, which will take about 1 to 2 minutes.
Note: If you are receiving a "reset by peer" error, rerun the cell to restart the download. If you run into an "attribute" error, you may need to update to the most recent version of gensim and numpy. You can upgrade them inline by uncommenting and running the below cell:
Reducing dimensionality of Word Embeddings
Let's directly compare the GloVe embeddings to those of the co-occurrence matrix. In order to avoid running out of memory, we will work with a sample of 10000 GloVe vectors instead. Run the following cells to:
Put 10000 Glove vectors into a matrix M
Run
reduce_to_k_dim
(your Truncated SVD function) to reduce the vectors from 200-dimensional to 2-dimensional.
Note: If you are receiving out of memory issues on your local machine, try closing other applications to free more memory on your device. You may want to try restarting your machine so that you can free up extra memory. Then immediately run the jupyter notebook and see if you can load the word vectors properly. If you still have problems with loading the embeddings onto your local machine after this, please go to office hours or contact course staff.
Question 2.1: GloVe Plot Analysis [written] (3 points)
Run the cell below to plot the 2D GloVe embeddings for ['value', 'gold', 'platinum', 'reserves', 'silver', 'metals', 'copper', 'belgium', 'australia', 'china', 'grammes', "mine"]
.
a. What is one way the plot is different from the one generated earlier from the co-occurrence matrix? What is one way it's similar?
SOLUTION BEGIN
The reduced features are centralized on the x-axis but distributed on the y-axis. But the co-occurence matrix's embedding vector is distributed on both two features.
SOLUTION END
b. What is a possible cause for the difference?
SOLUTION BEGIN
Because the Glove is trained on a lager dataset and use the deep learning method, the x-axis feature depart the word "grammes" and others and the y-axis feature contains more semantic information. The word group on the "right" have some family feature on x but have different features on the y-axis because they means differently in semantic representation.
SOLUTION END
Cosine Similarity
Now that we have word vectors, we need a way to quantify the similarity between individual words, according to these vectors. One such metric is cosine-similarity. We will be using this to find words that are "close" and "far" from one another.
We can think of n-dimensional vectors as points in n-dimensional space. If we take this perspective L1 and L2 Distances help quantify the amount of space "we must travel" to get between these two points. Another approach is to examine the angle between two vectors. From trigonometry we know that:
Instead of computing the actual angle, we can leave the similarity in terms of . Formally the Cosine Similarity between two vectors and is defined as:
Question 2.2: Words with Multiple Meanings (1.5 points) [code + written]
Polysemes and homonyms are words that have more than one meaning (see this wiki page to learn more about the difference between polysemes and homonyms ). Find a word with at least two different meanings such that the top-10 most similar words (according to cosine similarity) contain related words from both meanings. For example, "leaves" has both "go_away" and "a_structure_of_a_plant" meaning in the top 10, and "scoop" has both "handed_waffle_cone" and "lowdown". You will probably need to try several polysemous or homonymic words before you find one.
Please state the word you discover and the multiple meanings that occur in the top 10. Why do you think many of the polysemous or homonymic words you tried didn't work (i.e. the top-10 most similar words only contain one of the meanings of the words)?
Note: You should use the wv_from_bin.most_similar(word)
function to get the top 10 similar words. This function ranks all other words in the vocabulary with respect to their cosine similarity to the given word. For further assistance, please check the GenSim documentation.
SOLUTION BEGIN
For convience, we will explain the word close by Chinese, meaning 1 means "关闭", and 2 means "近". So, the meaning 1 similar word contains: closed, the meaning 2 similar word contains: closing, up, down, far, time, while and so on.
SOLUTION END
Question 2.3: Synonyms & Antonyms (2 points) [code + written]
When considering Cosine Similarity, it's often more convenient to think of Cosine Distance, which is simply 1 - Cosine Similarity.
Find three words where and are synonyms and and are antonyms, but Cosine Distance Cosine Distance .
As an example, ="happy" is closer to ="sad" than to ="cheerful". Please find a different example that satisfies the above. Once you have found your example, please give a possible explanation for why this counter-intuitive result may have happened.
You should use the the wv_from_bin.distance(w1, w2)
function here in order to compute the cosine distance between two words. Please see the GenSim documentation for further assistance.
SOLUTION BEGIN
We found that the word "like" and "dislike" is more similar but "like" and "love" is less similar, because the word front both contain "like".
SOLUTION END
Question 2.4: Analogies with Word Vectors [written] (1.5 points)
Word vectors have been shown to sometimes exhibit the ability to solve analogies.
As an example, for the analogy "man : grandfather :: woman : x" (read: man is to grandfather as woman is to x), what is x?
In the cell below, we show you how to use word vectors to find x using the most_similar
function from the GenSim documentation. The function finds words that are most similar to the words in the positive
list and most dissimilar from the words in the negative
list (while omitting the input words, which are often the most similar; see this paper). The answer to the analogy will have the highest cosine similarity (largest returned numerical value).
Let , , , and denote the word vectors for man
, grandfather
, woman
, and the answer, respectively. Using only vectors , , , and the vector arithmetic operators and in your answer, to what expression are we maximizing 's cosine similarity?
Hint: Recall that word vectors are simply multi-dimensional vectors that represent a word. It might help to draw out a 2D example using arbitrary locations of each vector. Where would man
and woman
lie in the coordinate plane relative to grandfather
and the answer?
SOLUTION BEGIN
We have then , the answer consider the gender reason.
SOLUTION END
Question 2.5: Finding Analogies [code + written] (1.5 points)
a. For the previous example, it's clear that "grandmother" completes the analogy. But give an intuitive explanation as to why the most_similar
function gives us words like "granddaughter", "daughter", or "mother?
SOLUTION BEGIN
Because the negative sample is man, then the most similar gender is female. Also, these words are all kinsfolk words which is similar to "grandmother".
SOLUTION END
b. Find an example of analogy that holds according to these vectors (i.e. the intended word is ranked top). In your solution please state the full analogy in the form x:y :: a:b. If you believe the analogy is complicated, explain why the analogy holds in one or two sentences.
Note: You may have to try many analogies to find one that works!
SOLUTION BEGIN
Because the difference between "actor" and "actress" is only gender and the difference between "man" and "woman" is only gender too.
SOLUTION END
Question 2.6: Incorrect Analogy [code + written] (1.5 points)
a. Below, we expect to see the intended analogy "hand : glove :: foot : sock", but we see an unexpected result instead. Give a potential reason as to why this particular analogy turned out the way it did?
SOLUTION BEGIN
Because the word "glove" also means a word embeding model, the model would learn many "glove" context consisting "%square" words.
SOLUTION END
b. Find another example of analogy that does not hold according to these vectors. In your solution, state the intended analogy in the form x:y :: a:b, and state the incorrect value of b according to the word vectors (in the previous example, this would be '45,000-square').
SOLUTION BEGIN
The analogy of up and down with a negative example "hat", the right answer should be shoes, but the prediction is out.
SOLUTION END
Question 2.7: Guided Analysis of Bias in Word Vectors [written] (1 point)
It's important to be cognizant of the biases (gender, race, sexual orientation etc.) implicit in our word embeddings. Bias can be dangerous because it can reinforce stereotypes through applications that employ these models.
Run the cell below, to examine (a) which terms are most similar to "woman" and "profession" and most dissimilar to "man", and (b) which terms are most similar to "man" and "profession" and most dissimilar to "woman". Point out the difference between the list of female-associated words and the list of male-associated words, and explain how it is reflecting gender bias.
SOLUTION BEGIN
(a) The word for a man with profession would be connected to "reputation", "skill", "ethic", "business", "respected". (b) The word for a woman with profession would be connected to "teaching", "nursing", "educator" and so on. Because the model learn the semantic meaning by the dataset, but dataset would always have bias and stereotype because of the limitation of history.
SOLUTION END
Question 2.8: Independent Analysis of Bias in Word Vectors [code + written] (1 point)
Use the most_similar
function to find another pair of analogies that demonstrates some bias is exhibited by the vectors. Please briefly explain the example of bias that you discover.
SOLUTION BEGIN
We proposed the color "white" and "blcak" which is associated with race and racial discrimination. The bias of this model is that it consider black people do work, hiring, and employment. But the white people work in office and administration. It's a stereotype of the model.
SOLUTION END
Question 2.9: Thinking About Bias [written] (2 points)
a. Give one explanation of how bias gets into the word vectors. Briefly describe a real-world example that demonstrates this source of bias.
SOLUTION BEGIN
The training set is via all the history, but there is a lot of inequality events in the history. So the model learns it. For example, there are many news about black people living in slums but white people work in goverment.
SOLUTION END
b. What is one method you can use to mitigate bias exhibited by word vectors? Briefly describe a real-world example that demonstrates this method.
SOLUTION BEGIN
We could learn newer text which represents the newest thought of people.
SOLUTION END
Submission Instructions
Click the Save button at the top of the Jupyter Notebook.
Select Cell -> All Output -> Clear. This will clear all the outputs from all cells (but will keep the content of all cells).
Select Cell -> Run All. This will run all the cells in order, and will take several minutes.
Once you've rerun everything, select File -> Download as -> PDF via LaTeX (If you have trouble using "PDF via LaTex", you can also save the webpage as pdf. Make sure all your solutions especially the coding parts are displayed in the pdf, it's okay if the provided codes get cut off because lines are not wrapped in code cells).
Look at the PDF file and make sure all your solutions are there, displayed correctly. The PDF is the only thing your graders will see!
Submit your PDF on Gradescope.