Word2vec
Machine learning and data mining |
---|
![]() |
Word2vec is a technique in natural language processing (NLP) for obtaining vector representations of words. These vectors capture information about the meaning of the word and their usage in context. The word2vec algorithm estimates these representations by modeling text in a large corpus. Once trained, such a model can detect synonymous words or suggest additional words for a partial sentence. As the name implies, word2vec represents each distinct word with a particular list of numbers called a vector. The vectors are chosen carefully such that they capture the semantic and syntactic qualities of words; as such, a simple mathematical function (cosine similarity) can indicate the level of semantic similarity between the words represented by those vectors.
Approach
Word2vec is a group of related models that are used to produce word embeddings. These models are shallow, two-layer neural networks that are trained to reconstruct linguistic contexts of words. Word2vec takes as its input a large corpus of text and produces a vector space, typically of several hundred dimensions, with each unique word in the corpus being assigned a corresponding vector in the space.
Word2vec can utilize either of two model architectures to produce these distributed representations of words: Continuous Bag-Of-Words (CBOW) or continuously sliding skip-gram. In both architectures, word2vec considers both individual words and a sliding context window as it iterates over the corpus.
The CBOW can be viewed as a ‘fill in the blank’ task, where the word embedding represents the way the word influences the relative probabilities of other words in the context window. Words which are semantically similar should influence these probabilities in similar ways, because semantically similar words should be used in similar contexts. The order of context words does not influence prediction (bag-of-words assumption).
In the continuous skip-gram architecture, the model uses the current word to predict the surrounding window of context words.[1][2] The skip-gram architecture weighs nearby context words more heavily than more distant context words. According to the authors' note,[3] CBOW is faster while skip-gram does a better job for infrequent words.
After the model has trained, the learned word embeddings are positioned in the vector space such that words that share common contexts in the corpus — that is, words that are semantically and syntactically similar — are located close to one another in the space.[1] More dissimilar words are located farther from one another in the space.[1]
Mathematical details
This section is based on expositions.[4][5]
A corpus is a sequence of words. Both CBOW and skip-gram are methods to learn one vector per word appearing in the corpus.
Let [math]\displaystyle{ V }[/math] ("vocabulary") be the set of all words appearing in the corpus [math]\displaystyle{ C }[/math]. Our goal is to learn one vector [math]\displaystyle{ v_w \in \R^n }[/math] for each word [math]\displaystyle{ w \in V }[/math].
The idea of skip-gram is that the vector of a word should be close to the vector of each of its neighbors. The idea of CBOW is that the vector-sum of a word's neighbors should be close to the vector of the word.
In the original publication, "closeness" is measured by softmax, but the framework allows other ways to measure closeness.
Continuous Bag of Words (CBOW)
Suppose we want each word in the corpus to be predicted by every other word in a small span of 4 words. We write the neighbor set [math]\displaystyle{ N = \{-4, -3, -2, -1, +1, +2, +3, +4\} }[/math].
Then the training objective is to maximize the following quantity:[math]\displaystyle{ \prod_{i \in C} Pr(w_i | w_j : j \in N + i) }[/math]That is, we want to maximize the total probability for the corpus, as seen by a probability model that uses word neighbors to predict words.
Products are numerically unstable, so we convert it by taking the logarithm:[math]\displaystyle{ \sum_{i \in C} \ln Pr(w_i | w_j : j \in N + i) }[/math]That is, we maximize the log-probability of the corpus.
Our probability model is as follows: Given words [math]\displaystyle{ \{w_j : j \in N+i\} }[/math], it takes their vector sum [math]\displaystyle{ v := \sum_{j \in N+i} v_{w_j} }[/math], then take the dot-product-softmax with every other vector sum (this step is similar to the attention mechanism in Transformers), to obtain the probability:[math]\displaystyle{ Pr(w | w_j : j \in N +i) := \frac{e^{v_w \cdot v}}{\sum_{w \in V} e^{v_w \cdot v}} }[/math]The quantity to be maximized is then after simplifications:[math]\displaystyle{ \sum_{i \in C, j \in N+i}\left( v_{w_i} \cdot v_{w_j} - \ln \sum_{w \in V} e^{v_w \cdot v_{w_j}} \right) }[/math]The quantity on the left is fast to compute, but the quantity on the right is slow, as it involves summing over the entire vocabulary set for each word in the corpus. Furthermore, to use gradient ascent to maximize the log-probability requires computing the gradient of the quantity on the right, which is intractable. This prompted the authors to use numerical approximation tricks.
Skip-gram
For skip-gram, the training objective is[math]\displaystyle{ \prod_{i \in C} Pr(w_j : j \in N + i | w_i) }[/math]That is, we want to maximize the total probability for the corpus, as seen by a probability model that uses words to predict its word neighbors. We predict each word-neighbor independently, thus [math]\displaystyle{ Pr(w_j : j \in N + i | w_i) = \prod_{j \in N + i} Pr(w_j | w_i) }[/math].
Products are numerically unstable, so we convert it by taking the logarithm:[math]\displaystyle{ \sum_{i \in C, j \in N + i} \ln Pr(w_j | w_i) }[/math]The probability model is still the dot-product-softmax model, so the calculation proceeds as before.[math]\displaystyle{ \sum_{i \in C, j \in N+i}\left( v_{w_i} \cdot v_{w_j} - \ln \sum_{w \in V} e^{v_w \cdot v_{w_{\color{red} i}}} \right) }[/math]There is only a single difference from the CBOW equation, highlighted in red.
History
In 2010, Tomáš Mikolov (then at Brno University of Technology) with co-authors applied a simple recurrent neural network with a single hidden layer to language modelling.[6]
Word2vec was created, patented,[7] and published in 2013 by a team of researchers led by Mikolov at Google over two papers.[1][2] Other researchers helped analyse and explain the algorithm.[4] Embedding vectors created using the Word2vec algorithm have some advantages compared to earlier algorithms[1][further explanation needed] such as latent semantic analysis.
By 2022, the Word2vec approach was described as "dated", with transformer models being regarded as the state of the art in NLP.[8]
Parameterization
Results of word2vec training can be sensitive to parametrization. The following are some important parameters in word2vec training.
Training algorithm
A Word2vec model can be trained with hierarchical softmax and/or negative sampling. To approximate the conditional log-likelihood a model seeks to maximize, the hierarchical softmax method uses a Huffman tree to reduce calculation. The negative sampling method, on the other hand, approaches the maximization problem by minimizing the log-likelihood of sampled negative instances. According to the authors, hierarchical softmax works better for infrequent words while negative sampling works better for frequent words and better with low dimensional vectors.[3] As training epochs increase, hierarchical softmax stops being useful.[9]
Sub-sampling
High-frequency and low-frequency words often provide little information. Words with a frequency above a certain threshold, or below a certain threshold, may be subsampled or removed to speed up training.[10]
Dimensionality
Quality of word embedding increases with higher dimensionality. But after reaching some point, marginal gain diminishes.[1] Typically, the dimensionality of the vectors is set to be between 100 and 1,000.
Context window
The size of the context window determines how many words before and after a given word are included as context words of the given word. According to the authors' note, the recommended value is 10 for skip-gram and 5 for CBOW.[3]
Extensions
There are a variety of extensions to word2vec.
doc2vec
doc2vec, generates distributed representations of variable-length pieces of texts, such as sentences, paragraphs, or entire documents.[11][12] doc2vec has been implemented in the C, Python and Java/Scala tools (see below), with the Java and Python versions also supporting inference of document embeddings on new, unseen documents.
doc2vec estimates the distributed representations of documents much like how word2vec estimates representations of words: doc2vec utilizes either of two model architectures, both of which are allegories to the architectures used in word2vec. The first, Distributed Memory Model of Paragraph Vectors (PV-DM), is identical to CBOW other than it also provides a unique document identifier as a piece of additional context. The second architecture, Distributed Bag of Words version of Paragraph Vector (PV-DBOW), is identical to the skip-gram model except that it attempts to predict the window of surrounding context words from the paragraph identifier instead of the current word.[11]
doc2vec also has the ability to capture the semantic ‘meanings’ for additional pieces of ‘context’ around words; doc2vec can estimate the semantic embeddings for speakers or speaker attributes, groups, and periods of time. For example, doc2vec has been used to estimate the political positions of political parties in various Congresses and Parliaments in the U.S. and U.K.,[13] respectively, and various governmental institutions.[14]
top2vec
Another extension of word2vec is top2vec, which leverages both document and word embeddings to estimate distributed representations of topics.[15][16] top2vec takes document embeddings learned from a doc2vec model and reduces them into a lower dimension (typically using UMAP). The space of documents is then scanned using HDBSCAN,[17] and clusters of similar documents are found. Next, the centroid of documents identified in a cluster is considered to be that cluster's topic vector. Finally, top2vec searches the semantic space for word embeddings located near to the topic vector to ascertain the 'meaning' of the topic.[15] The word with embeddings most similar to the topic vector might be assigned as the topic's title, whereas far away word embeddings may be considered unrelated.
As opposed to other topic models such as LDA, top2vec provides canonical ‘distance’ metrics between two topics, or between a topic and another embeddings (word, document, or otherwise). Together with results from HDBSCAN, users can generate topic hierarchies, or groups of related topics and subtopics.
Furthermore, a user can use the results of top2vec to infer the topics of out-of-sample documents. After inferring the embedding for a new document, must only search the space of topics for the closest topic vector.
BioVectors
An extension of word vectors for n-grams in biological sequences (e.g. DNA, RNA, and proteins) for bioinformatics applications has been proposed by Asgari and Mofrad.[18] Named bio-vectors (BioVec) to refer to biological sequences in general with protein-vectors (ProtVec) for proteins (amino-acid sequences) and gene-vectors (GeneVec) for gene sequences, this representation can be widely used in applications of machine learning in proteomics and genomics. The results suggest that BioVectors can characterize biological sequences in terms of biochemical and biophysical interpretations of the underlying patterns.[18] A similar variant, dna2vec, has shown that there is correlation between Needleman–Wunsch similarity score and cosine similarity of dna2vec word vectors.[19]
Radiology and intelligent word embeddings (IWE)
An extension of word vectors for creating a dense vector representation of unstructured radiology reports has been proposed by Banerjee et al.[20] One of the biggest challenges with Word2vec is how to handle unknown or out-of-vocabulary (OOV) words and morphologically similar words. If the Word2vec model has not encountered a particular word before, it will be forced to use a random vector, which is generally far from its ideal representation. This can particularly be an issue in domains like medicine where synonyms and related words can be used depending on the preferred style of radiologist, and words may have been used infrequently in a large corpus.
IWE combines Word2vec with a semantic dictionary mapping technique to tackle the major challenges of information extraction from clinical texts, which include ambiguity of free text narrative style, lexical variations, use of ungrammatical and telegraphic phases, arbitrary ordering of words, and frequent appearance of abbreviations and acronyms. Of particular interest, the IWE model (trained on the one institutional dataset) successfully translated to a different institutional dataset which demonstrates good generalizability of the approach across institutions.
Analysis
The reasons for successful word embedding learning in the word2vec framework are poorly understood. Goldberg and Levy point out that the word2vec objective function causes words that occur in similar contexts to have similar embeddings (as measured by cosine similarity) and note that this is in line with J. R. Firth's distributional hypothesis. However, they note that this explanation is "very hand-wavy" and argue that a more formal explanation would be preferable.[4]
Levy et al. (2015)[21] show that much of the superior performance of word2vec or similar embeddings in downstream tasks is not a result of the models per se, but of the choice of specific hyperparameters. Transferring these hyperparameters to more 'traditional' approaches yields similar performances in downstream tasks. Arora et al. (2016)[22] explain word2vec and related algorithms as performing inference for a simple generative model for text, which involves a random walk generation process based upon loglinear topic model. They use this to explain some properties of word embeddings, including their use to solve analogies.
Preservation of semantic and syntactic relationships
The word embedding approach is able to capture multiple different degrees of similarity between words. Mikolov et al. (2013)[23] found that semantic and syntactic patterns can be reproduced using vector arithmetic. Patterns such as "Man is to Woman as Brother is to Sister" can be generated through algebraic operations on the vector representations of these words such that the vector representation of "Brother" - "Man" + "Woman" produces a result which is closest to the vector representation of "Sister" in the model. Such relationships can be generated for a range of semantic relations (such as Country–Capital) as well as syntactic relations (e.g. present tense–past tense).
This facet of word2vec has been exploited in a variety of other contexts. For example, word2vec has been used to map a vector space of words in one language to a vector space constructed from another language. Relationships between translated words in both spaces can be used to assist with machine translation of new words.[24]
Assessing the quality of a model
Mikolov et al. (2013)[1] develop an approach to assessing the quality of a word2vec model which draws on the semantic and syntactic patterns discussed above. They developed a set of 8,869 semantic relations and 10,675 syntactic relations which they use as a benchmark to test the accuracy of a model. When assessing the quality of a vector model, a user may draw on this accuracy test which is implemented in word2vec,[25] or develop their own test set which is meaningful to the corpora which make up the model. This approach offers a more challenging test than simply arguing that the words most similar to a given test word are intuitively plausible.[1]
Parameters and model quality
The use of different model parameters and different corpus sizes can greatly affect the quality of a word2vec model. Accuracy can be improved in a number of ways, including the choice of model architecture (CBOW or Skip-Gram), increasing the training data set, increasing the number of vector dimensions, and increasing the window size of words considered by the algorithm. Each of these improvements comes with the cost of increased computational complexity and therefore increased model generation time.[1]
In models using large corpora and a high number of dimensions, the skip-gram model yields the highest overall accuracy, and consistently produces the highest accuracy on semantic relationships, as well as yielding the highest syntactic accuracy in most cases. However, the CBOW is less computationally expensive and yields similar accuracy results.[1]
Overall, accuracy increases with the number of words used and the number of dimensions. Mikolov et al.[1] report that doubling the amount of training data results in an increase in computational complexity equivalent to doubling the number of vector dimensions.
Altszyler and coauthors (2017) studied Word2vec performance in two semantic tests for different corpus size.[26] They found that Word2vec has a steep learning curve, outperforming another word-embedding technique, latent semantic analysis (LSA), when it is trained with medium to large corpus size (more than 10 million words). However, with a small training corpus, LSA showed better performance. Additionally they show that the best parameter setting depends on the task and the training corpus. Nevertheless, for skip-gram models trained in medium size corpora, with 50 dimensions, a window size of 15 and 10 negative samples seems to be a good parameter setting.
See also
- Semantle
- Autoencoder
- Document-term matrix
- Feature extraction
- Feature learning
- Neural network language models
- Vector space model
- Thought vector
- fastText
- GloVe
- Normalized compression distance
References
- ↑ 1.00 1.01 1.02 1.03 1.04 1.05 1.06 1.07 1.08 1.09 1.10 "Efficient Estimation of Word Representations in Vector Space". 2013. arXiv:1301.3781 [cs.CL].
- ↑ 2.0 2.1 Mikolov, Tomas; Sutskever, Ilya; Chen, Kai; Corrado, Greg S.; Dean, Jeff (2013). "Distributed representations of words and phrases and their compositionality". Advances in Neural Information Processing Systems. Bibcode: 2013arXiv1310.4546M.
- ↑ 3.0 3.1 3.2 "Google Code Archive - Long-term storage for Google Code Project Hosting.". https://code.google.com/archive/p/word2vec/.
- ↑ 4.0 4.1 4.2 Goldberg, Yoav; Levy, Omer (2014). "word2vec Explained: Deriving Mikolov et al.'s Negative-Sampling Word-Embedding Method". arXiv:1402.3722 [cs.CL].
- ↑ Rong, Xin (2016-06-05), word2vec Parameter Learning Explained
- ↑ Mikolov, Tomáš; Karafiát, Martin; Burget, Lukáš; Černocký, Jan; Khudanpur, Sanjeev (26 September 2010). "Interspeech 2010". ISCA: ISCA. pp. 1045–1048. doi:10.21437/interspeech.2010-343.
- ↑ Mikolov, Tomas; Kai Chen & Gregory S. Corrado et al., "Computing numeric representations of words in a high-dimensional space", US patent 9037464, published 2015-05-19
- ↑ Von der Mosel, Julian; Trautsch, Alexander; Herbold, Steffen (2022). "On the validity of pre-trained transformers for natural language processing in the software engineering domain". IEEE Transactions on Software Engineering 49 (4): 1487–1507. doi:10.1109/TSE.2022.3178469. ISSN 1939-3520. https://ieeexplore.ieee.org/document/9785808.
- ↑ "Parameter (hs & negative)". https://groups.google.com/forum/#!msg/word2vec-toolkit/WUWad9fL0jU/LdbWy1jQjUIJ.
- ↑ "Visualizing Data using t-SNE". http://jmlr.csail.mit.edu/papers/volume9/vandermaaten08a/vandermaaten08a.pdf.
- ↑ 11.0 11.1 Le, Quoc; Mikolov, Tomas (May 2014). "Distributed Representations of Sentences and Documents". Proceedings of the 31st International Conference on Machine Learning.
- ↑ Rehurek, Radim. "Gensim". https://radimrehurek.com/gensim/models/doc2vec.html.
- ↑ Rheault, Ludovic; Cochrane, Christopher (3 July 2019). "Word Embeddings for the Analysis of Ideological Placement in Parliamentary Corpora". Political Analysis 28 (1). https://www.cambridge.org/core/journals/political-analysis/article/word-embeddings-for-the-analysis-of-ideological-placement-in-parliamentary-corpora/017F0CEA9B3DB6E1B94AC36A509A8A7B.
- ↑ Nay, John (21 Dec 2017). "Gov2Vec: Learning Distributed Representations of Institutions and Their Legal Text". SSRN. https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3087278.
- ↑ 15.0 15.1 Angelov, Dimo (August 2020). "Top2Vec: Distributed Representations of Topics". arXiv:2008.09470 [cs.CL].
- ↑ Angelov, Dimo (11 November 2022). "Top2Vec". https://github.com/ddangelov/Top2Vec.
- ↑ Campello, Ricardo; Moulavi, Davoud; Sander, Joerg (2013). "Density-Based Clustering Based on Hierarchical Density Estimates". Advances in Knowledge Discovery and Data Mining. Lecture Notes in Computer Science. 7819. pp. 160–172. doi:10.1007/978-3-642-37456-2_14. ISBN 978-3-642-37455-5. https://link.springer.com/chapter/10.1007/978-3-642-37456-2_14.
- ↑ 18.0 18.1 Asgari, Ehsaneddin; Mofrad, Mohammad R.K. (2015). "Continuous Distributed Representation of Biological Sequences for Deep Proteomics and Genomics". PLOS ONE 10 (11): e0141287. doi:10.1371/journal.pone.0141287. PMID 26555596. Bibcode: 2015PLoSO..1041287A.
- ↑ Ng, Patrick (2017). "dna2vec: Consistent vector representations of variable-length k-mers". arXiv:1701.06279 [q-bio.QM].
- ↑ Banerjee, Imon; Chen, Matthew C.; Lungren, Matthew P.; Rubin, Daniel L. (2018). "Radiology report annotation using intelligent word embeddings: Applied to multi-institutional chest CT cohort". Journal of Biomedical Informatics 77: 11–20. doi:10.1016/j.jbi.2017.11.012. PMID 29175548.
- ↑ Levy, Omer; Goldberg, Yoav; Dagan, Ido (2015). "Improving Distributional Similarity with Lessons Learned from Word Embeddings". Transactions of the Association for Computational Linguistics (Transactions of the Association for Computational Linguistics) 3: 211–225. doi:10.1162/tacl_a_00134. http://www.aclweb.org/anthology/Q15-1016.
- ↑ Arora, S (Summer 2016). "A Latent Variable Model Approach to PMI-based Word Embeddings". Transactions of the Association for Computational Linguistics 4: 385–399. doi:10.1162/tacl_a_00106. http://aclweb.org/anthology/Q16-1028.
- ↑ Mikolov, Tomas; Yih, Wen-tau; Zweig, Geoffrey (2013). "Linguistic Regularities in Continuous Space Word Representations.". HLT-Naacl: 746–751.
- ↑ Jansen, Stefan (9 May 2017). Word and Phrase Translation with word2vec.
- ↑ "Gensim - Deep learning with word2vec". https://radimrehurek.com/gensim/models/word2vec.html.
- ↑ Altszyler, E.; Ribeiro, S.; Sigman, M.; Fernández Slezak, D. (2017). "The interpretation of dream meaning: Resolving ambiguity using Latent Semantic Analysis in a small corpus of text". Consciousness and Cognition 56: 178–187. doi:10.1016/j.concog.2017.09.004. PMID 28943127.
External links
Implementations
![]() | Original source: https://en.wikipedia.org/wiki/Word2vec.
Read more |