import torch
torch.manual_seed(8)
def get_unique_tokens(sentence):
return set(sentence.split())
def get_int_encoding(tokens):
token_list = ["<unk>", "<pad>"] + list(tokens)
return { token: i for i, token in enumerate(token_list) }
test_sentence = "how do you do"
unique_tokens = get_unique_tokens(test_sentence)
int_encoding = get_int_encoding(unique_tokens) # {'<unk>': 0, '<pad>': 1, 'how': 2, 'do': 3, 'you': 4}
lookup_table = [[ 0.35876983, -2.2124066 , 0.9306893 ], # <unk>
[ 0. , 0. , 0. ], # <pad>, 패딩이기 때문에 0
[ 0.43745077, 0.732288 , -1.7055405 ], # how
[-0.05768548, 0.4197516 , -0.6325408 ], # do
[ 1.2649128 , 4.234565 , -0.7701444 ]] # you
1.
위의 예시에서 "how do you do"를 벡터화 한다면,
[[ 0.43745077, 0.732288 , -1.7055405 ],
[-0.05768548, 0.4197516 , -0.6325408 ],
[ 1.2649128 , 4.234565 , -0.7701444 ],
[-0.05768548, 0.4197516 , -0.6325408 ]]
가 되는 것이다. (1, 3 index의 값이 같음을 확인하자)
2.
앞서 "how do you do"를 벡터화해보았지만,
torch.nn.Embedding도 torch.nn.Module을 상속하는 신경망 층이다.
즉, 훈련이 되며 값이 변한다는 것.
다만, 언제 훈련이 되는 걸까?
3.
예시의 lookup_table은 실제로 torch.nn.Embedding 레이어를 생성하고,
weight 값을 받아온 것이다. random seed는 8
https://pytorch.org/tutorials/beginner/nlp/word_embeddings_tutorial.html
Word Embeddings: Encoding Lexical Semantics — PyTorch Tutorials 2.2.0+cu121 documentation
Note Click here to download the full example code Word Embeddings: Encoding Lexical Semantics Word embeddings are dense vectors of real numbers, one per word in your vocabulary. In NLP, it is almost always the case that your features are words! But how sho
pytorch.org
https://discuss.pytorch.org/t/how-does-nn-embedding-work/88518/21
How does nn.Embedding work?
hello chris, i had tried embedding layer but instead of one hot vector instead it gives me a vector of real numbers ,how these values are learned or it was just some random vectors based on the vocabulary if they are random vecors will that get trained dur
discuss.pytorch.org
12-09 파이토치(PyTorch)의 nn.Embedding()
파이토치에서는 임베딩 벡터를 사용하는 방법이 크게 두 가지가 있습니다. 바로 임베딩 층(embedding layer)을 만들어 훈련 데이터로부터 처음부터 임베딩 벡터를 학습하는 …
wikidocs.net
'미분류' 카테고리의 다른 글
[인생전략] 비전공 개발자 포기, 그 이후로는? (0) | 2024.02.14 |
---|---|
[개똥철학] 실패자, 그리고 까뮈를 생각하다 (1) | 2024.02.14 |
[Transformer] Positional Encoding (작성중) (0) | 2024.01.06 |
2024년 1월 2일 pytorch tutorial (0) | 2024.01.02 |
Word Embedding이란? (0) | 2023.12.29 |