NLP study

Word Embedding(워드 임베딩)

2로 접어듦 2023. 2. 28. 01:42

<이유>

<기법 및 종류>

 

<선제적으로 이루어져야 하는 것>

<<< 1. build vocabulary >>>

word tokenizing한 뒤 Integer Value 로 매핑해주어야한다.

torchtext.vocab.build_vocab_from_iterator가 사용된다.

 

Build Vocabulary 란?

In the context of word embedding, "building the vocabulary" or "making the vocabulary" refers to the process of creating a mapping between words in a corpus and unique integer indices, which will be used to represent the words in a numerical format that can be fed into a machine learning model.

 

왜 build vocabulary를 해야하는가?

단어를 Embedding Vector로 표기하기 위해서 Embedding matrix를 만든다. 이 Embedding matrix로부터 단어를 매칭시키기 위한 index를 구하기 위해서 building vocabulary가 필요하다.

즉, corpus 안에서 each word는 unique integer value를 가진다. 이 unique integer value는 Embedding matrix 안에서 해당하는 word에 대한 embedding vector를 추출하기 위해(look up) 사용된다.

 

We build a vocabulary before the word embedding process because word embeddings represent each word in a high-dimensional vector space,  where each dimension corresponds to a particular aspect of the word's meaning. 

The goal of building a vocabulary is to map each unique word in the corpus to a unique integer index. 

This index will be used to represent the word in the vector space.

 

Specifically, during the embedding process, each word in the corpus is first converted to its corresponding integer  index using the vocabulary. 

This integer index is then used to look up the corresponding vector in the embedding matrix. The embedding matrix contains a high-dimensional vector representation for each word in the vocabulary.

 

 

왜 Integer value로 변환해야하는가?

매핑해서 embedding vector(dense vector)로 표현해야 하니까. Word2Vec와 GloVe는 이러한 dense representation을 학습해서 연관된 단어가 vector-space 상에서 가까이 존재할 수 있도록 하니까.

 

또한, string 그 자체로 저장하는 것보다 훨-씬 메모리 효율적이며, 추가적인 operation을 손쉽게 하는 데 도움을 준다.

먼저, 100,000개의 string을 저장하는 것보다, 이를 변환한 0~99,999까지의 Integer를 저장하는 것이 효율적이게 된다.

그 다음으로는, vocabulary로부터 indexing, slicing, reshaping등의 추가적인 작업을 쉽게 할 수 있게 된다. vocab.get_stoi()와 같은 함수의 사용으로 특정 단어의 index를 뽑아낼 수도 있다.

 

torchtext.vocab.build_vocab_from_iterator

https://pytorch.org/text/stable/vocab.html#build-vocab-from-iterator

 

 

# building vocabulary testcode

import torch
import torchtext

# define the text data
text = ["the quick brown fox", "jumps over the lazy dog"]

# define the tokenizer function
def tokenize(text):
    return text.split()

# create an iterator that yields lists of tokens
token_iterator = map(tokenize, text)

# build the vocabulary from the iterator
vocab = torchtext.vocab.build_vocab_from_iterator(token_iterator)

# get the word-to-index mapping
word_to_index = vocab.get_stoi()

word_to_index = sorted(word_to_index.items(), key = lambda x: x[1])
print(word_to_index)

# output is...
# [('the', 0), ('brown', 1), ('dog', 2), ('fox', 3), ('jumps', 4), ('lazy', 5), ('over', 6), ('quick', 7)]