Distributed Representations of Words and Phrases and their Compositionality
Mikolov, Tomas, et al. "Distributed representations of words and phrases and their compositionality."Advances in neural information processing systems26 (2013).
Abstract (Eng.)
The recently introduced continuous Skip-gram model is an efficient method for learning high-quality distributed vector representations that capture a large number of precise syntactic and semantic word relationships. In this paper we present several extensions that improve both the quality of the vectors and the training speed. By subsampling of the frequent words we obtain significant speedup and also learn more regular word representations. We also describe a simple alternative to the hierarchical softmax called negative sampling. An inherent limitation of word representations is their indifference to word order and their inability to represent idiomatic phrases. For example, the meanings of โCanadaโ and โAirโ cannot be easily combined to obtain โAir Canadaโ. Motivated by this example, we present a simple method for finding phrases in text, and show that learning good vector representations for millions of phrases is possible.
Efficient Estimation of Word Representations in Vector Space
Mikolov, Tomas, et al. "Efficient estimation of word representations in vector space."arXiv preprint arXiv:1301.3781(2013).
Abstract (Eng.)
We propose two novel model architectures for computing continuous vector representations of words from very large data sets. The quality of these representations is measured in a word similarity task, and the results are compared to the previously best performing techniques based on different types of neural networks. We observe large improvements in accuracy at much lower computational cost, i.e. it takes less than a day to learn high quality word vectors from a 1.6 billion words data set. Furthermore, we show that these vectors provide state-of-the-art performance on our test set for measuring syntactic and semantic word similarities.
""" CBOW """## using pytorchimport torch
import torch.nn as nn
EMBEDDING_DIM = 128
EPOCHS = 100
example_sentence = """
Chang Choi is currently an Assistant Professor in the Department of Computer Engineering at Gachon University, Seongnam, Korea, Since 2020.
He received B.S., M.S. and Ph.D. degrees in Computer Engineering from Chosun University in 2005, 2007, and 2012, respectively.
he was a research professor at the same university.
He was awarded the academic awards from the graduate school of Chosun University in 2012.
""".split()
#(1) ์ ๋ ฅ๋ฐ์ ๋ฌธ์ฅ์ ๋จ์ด๋ก ์ชผ๊ฐ๊ณ , ์ค๋ณต์ ์ ๊ฑฐํด์ค๋๋ค.
vocab = set(example_sentence)
vocab_size = len(example_sentence)
#(2) ๋จ์ด : ์ธ๋ฑ์ค, ์ธ๋ฑ์ค : ๋จ์ด๋ฅผ ๊ฐ์ง๋ ๋์ ๋๋ฆฌ๋ฅผ ์ ์ธํด ์ค๋๋ค.
word_to_index = {word:index for index, word inenumerate(vocab)}
index_to_word = {index:word for index, word inenumerate(vocab)}
#3) ํ์ต์ ์ํ ๋ฐ์ดํฐ๋ฅผ ์์ฑํด ์ค๋๋ค.# convert context to index vectordefmake_context_vector(context, word_to_ix):
idxs = [word_to_ix[w] for w in context] #choi chang is currently ๋ฃ์ผ๋ฉด ์ธ๋ฑ์ค๊ฐ์ผ๋ก [n,n,n,n](n=์ ์)ํ์์ผ๋กreturn torch.tensor(idxs, dtype=torch.long)
# make dataset functiondefmake_data(sentence):
data = []
for i inrange(2, len(example_sentence) - 2):
context = [example_sentence[i - 2],
example_sentence[i - 1],
example_sentence[i + 1],
example_sentence[i + 2]
]
target = example_sentence[i]
data.append((context, target))
return data
data = make_data(example_sentence)
#(4) CBOW ๋ชจ๋ธ์ ์ ์ํด ์ค๋๋ค.classCBOW(nn.Module):
def__init__(self, vocab_size, embedding_dim):
super(CBOW, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embedding_dim)
self.layer1 = nn.Linear(embedding_dim, 64)
self.activation1 = nn.ReLU()
self.layer2 = nn.Linear(64, vocab_size)
self.activation2 = nn.LogSoftmax(dim = -1)
defforward(self, inputs):
embeded_vector = sum(self.embeddings(inputs)).view(1,-1) #(1,128)
output = self.activation1(self.layer1(embeded_vector))
output = self.activation2(self.layer2(output))
return output
#(5) ๋ชจ๋ธ์ ์ ์ธํด์ฃผ๊ณ , loss function, optimizer๋ฑ์ ์ ์ธํด์ค๋๋ค.
model = CBOW(vocab_size, EMBEDDING_DIM)
loss_function = nn.NLLLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
#(6) ํ์ต์ ์งํํฉ๋๋ค.for epoch inrange(EPOCHS):
total_loss = 0for context, target in data:
context_vector = make_context_vector(context, word_to_index)
log_probs = model(context_vector)
total_loss += loss_function(log_probs, torch.tensor([word_to_index[target]]))
print('epoch = ',epoch, ', loss = ',total_loss)
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
#(7) testํ๊ณ ์ถ์ ๋ฌธ์ฅ์ ๋ฝ๊ณ , test๋ฅผ ์งํํฉ๋๋ค.
test_data = ['Chang', 'Choi', 'currently', 'an']
test_vector = make_context_vector(test_data, word_to_index)
result = model(test_vector)
print(f"Input : {test_data}")
print('Prediction : ', index_to_word[torch.argmax(result[0]).item()])
"""
Skip-gram
Skip-gram์ CBOW์ ์ถ๋ ฅ์ ๋ฐ๋.
1๊ฐ๋ฅผ ์ฃผ์์ ๋ 4๊ฐ์ ์์ํ์ ์ฐพ์์ผํจ
"""import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable #์๋๋ฏธ๋ถ
torch.manual_seed(1)
embedding_dim = 10
raw_text = """
Chang Choi is currently an Assistant Professor in the Department of Computer Engineering at Gachon University, Seongnam, Korea, Since 2020.
He received B.S., M.S. and Ph.D. degrees in Computer Engineering from Chosun University in 2005, 2007, and 2012, respectively.
he was a research professor at the same university.
He was awarded the academic awards from the graduate school of Chosun University in 2012.
""".split()
defmake_context_vector(context, word_to_idx): #ํ ์๋ก ๋ณํ
idxs = [word_to_idx[w] for w in context]
return torch.tensor(idxs, dtype=torch.long)
vocab = set(raw_text) #๋ฆฌ์คํธํ์ > ๋์ ๋๋ฆฌ ํ์์ผ๋ก ๋ง๋ฌ
vocab_size = len(vocab) #47๊ฐ ์์.#๋์ ๋๋ฆฌ ํํ๋ก ๋ง๋ค๊ธฐ
word_to_idx = {word: i for i, word inenumerate(vocab)}
idx_to_word = {i: word for i, word inenumerate(vocab)}
data = []
for i inrange(2, len(raw_text) - 2):
target = [raw_text[i - 2], raw_text[i - 1],
raw_text[i + 1], raw_text[i + 2]]
context = raw_text[i]
data.append((context, target)) #data์๋ค๊ฐ ์ ์ฅ.#ex> data = (['Chang', 'Choi', 'currently', 'an'], 'is') ...classSkipGram(nn.Module):
def__init__(self, vocab_size, embedding_dim):
super(SkipGram, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embedding_dim) #์๋ฒ ๋ฉ์ฐจ์ ์ค์
self.proj = nn.Linear(embedding_dim, 128)
self.output = nn.Linear(128, vocab_size)
defforward(self, inputs):
out = sum(self.embeddings(inputs)).view(1, -1) #๋จ์ด ์ฌ์ด์ฆ๋ฃ์ผ๋ฉด [,,,,,,,] ํ์์ผ๋ก ๋ฃ์
out = F.relu(self.proj(out))
out = self.output(out)
out = F.log_softmax(out, dim=-1)
return out
model = SkipGram(vocab_size, embedding_dim)
optimizer = optim.SGD(model.parameters(), lr=0.001)
losses = []
loss_function = nn.NLLLoss()
loss_function1 = nn.CrossEntropyLoss()
for epoch inrange(100):
total_loss = 0for context, target in data:
model.zero_grad()
input = make_context_vector(context, word_to_idx) # torchํ์์ผ๋ก ๋ง๋ค๊ธฐ > tensor[n,n,n,n]
output = model(input)
loss = loss_function(output, Variable(torch.tensor([word_to_idx[target]])))
loss.backward()
optimizer.step()
total_loss += loss.item()
losses.append(total_loss)
print(losses)
print("*************************************************************************")
context = ['Chang', 'Choi', 'currently', 'an']
context_vector = make_context_vector(context, word_to_idx)
a = model(context_vector).data.numpy()
print('Raw text: {}\n'.format(' '.join(raw_text)))
print('Test Context: {}\n'.format(context))
max_idx = np.argmax(a)
print('Prediction: {}'.format(idx_to_word[max_idx]))
https://comlini8-8.tistory.com/6 Distributed Representations of Words and Phrases and their Compositionality Efficient_Estimation_of_Word_Representations_in_Vector_Space https://everyday-log.tistory.com/entry/๋จ์ด-์๋ฒ ๋ฉ-2-Iteration-based-methods
Distributed Representations of Words and Phrases and their Compositionality
Mikolov, Tomas, et al. "Distributed representations of words and phrases and their compositionality."Advances in neural information processing systems26 (2013).
Abstract (Eng.)
The recently introduced continuous Skip-gram model is an efficient method for learning high-quality distributed vector representations that capture a large number of precise syntactic and semantic word relationships. In this paper we present several extensions that improve both the quality of the vectors and the training speed. By subsampling of the frequent words we obtain significant speedup and also learn more regular word representations. We also describe a simple alternative to the hierarchical softmax called negative sampling. An inherent limitation of word representations is their indifference to word order and their inability to represent idiomatic phrases. For example, the meanings of โCanadaโ and โAirโ cannot be easily combined to obtain โAir Canadaโ. Motivated by this example, we present a simple method for finding phrases in text, and show that learning good vector representations for millions of phrases is possible.
Efficient Estimation of Word Representations in Vector Space
Mikolov, Tomas, et al. "Efficient estimation of word representations in vector space."arXiv preprint arXiv:1301.3781(2013).
Abstract (Eng.)
We propose two novel model architectures for computing continuous vector representations of words from very large data sets. The quality of these representations is measured in a word similarity task, and the results are compared to the previously best performing techniques based on different types of neural networks. We observe large improvements in accuracy at much lower computational cost, i.e. it takes less than a day to learn high quality word vectors from a 1.6 billion words data set. Furthermore, we show that these vectors provide state-of-the-art performance on our test set for measuring syntactic and semantic word similarities.
""" CBOW """## using pytorchimport torch
import torch.nn as nn
EMBEDDING_DIM = 128
EPOCHS = 100
example_sentence = """
Chang Choi is currently an Assistant Professor in the Department of Computer Engineering at Gachon University, Seongnam, Korea, Since 2020.
He received B.S., M.S. and Ph.D. degrees in Computer Engineering from Chosun University in 2005, 2007, and 2012, respectively.
he was a research professor at the same university.
He was awarded the academic awards from the graduate school of Chosun University in 2012.
""".split()
#(1) ์ ๋ ฅ๋ฐ์ ๋ฌธ์ฅ์ ๋จ์ด๋ก ์ชผ๊ฐ๊ณ , ์ค๋ณต์ ์ ๊ฑฐํด์ค๋๋ค.
vocab = set(example_sentence)
vocab_size = len(example_sentence)
#(2) ๋จ์ด : ์ธ๋ฑ์ค, ์ธ๋ฑ์ค : ๋จ์ด๋ฅผ ๊ฐ์ง๋ ๋์ ๋๋ฆฌ๋ฅผ ์ ์ธํด ์ค๋๋ค.
word_to_index = {word:index for index, word inenumerate(vocab)}
index_to_word = {index:word for index, word inenumerate(vocab)}
#3) ํ์ต์ ์ํ ๋ฐ์ดํฐ๋ฅผ ์์ฑํด ์ค๋๋ค.# convert context to index vectordefmake_context_vector(context, word_to_ix):
idxs = [word_to_ix[w] for w in context] #choi chang is currently ๋ฃ์ผ๋ฉด ์ธ๋ฑ์ค๊ฐ์ผ๋ก [n,n,n,n](n=์ ์)ํ์์ผ๋กreturn torch.tensor(idxs, dtype=torch.long)
# make dataset functiondefmake_data(sentence):
data = []
for i inrange(2, len(example_sentence) - 2):
context = [example_sentence[i - 2],
example_sentence[i - 1],
example_sentence[i + 1],
example_sentence[i + 2]
]
target = example_sentence[i]
data.append((context, target))
return data
data = make_data(example_sentence)
#(4) CBOW ๋ชจ๋ธ์ ์ ์ํด ์ค๋๋ค.classCBOW(nn.Module):
def__init__(self, vocab_size, embedding_dim):
super(CBOW, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embedding_dim)
self.layer1 = nn.Linear(embedding_dim, 64)
self.activation1 = nn.ReLU()
self.layer2 = nn.Linear(64, vocab_size)
self.activation2 = nn.LogSoftmax(dim = -1)
defforward(self, inputs):
embeded_vector = sum(self.embeddings(inputs)).view(1,-1) #(1,128)
output = self.activation1(self.layer1(embeded_vector))
output = self.activation2(self.layer2(output))
return output
#(5) ๋ชจ๋ธ์ ์ ์ธํด์ฃผ๊ณ , loss function, optimizer๋ฑ์ ์ ์ธํด์ค๋๋ค.
model = CBOW(vocab_size, EMBEDDING_DIM)
loss_function = nn.NLLLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001)
#(6) ํ์ต์ ์งํํฉ๋๋ค.for epoch inrange(EPOCHS):
total_loss = 0for context, target in data:
context_vector = make_context_vector(context, word_to_index)
log_probs = model(context_vector)
total_loss += loss_function(log_probs, torch.tensor([word_to_index[target]]))
print('epoch = ',epoch, ', loss = ',total_loss)
optimizer.zero_grad()
total_loss.backward()
optimizer.step()
#(7) testํ๊ณ ์ถ์ ๋ฌธ์ฅ์ ๋ฝ๊ณ , test๋ฅผ ์งํํฉ๋๋ค.
test_data = ['Chang', 'Choi', 'currently', 'an']
test_vector = make_context_vector(test_data, word_to_index)
result = model(test_vector)
print(f"Input : {test_data}")
print('Prediction : ', index_to_word[torch.argmax(result[0]).item()])
"""
Skip-gram
Skip-gram์ CBOW์ ์ถ๋ ฅ์ ๋ฐ๋.
1๊ฐ๋ฅผ ์ฃผ์์ ๋ 4๊ฐ์ ์์ํ์ ์ฐพ์์ผํจ
"""import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable #์๋๋ฏธ๋ถ
torch.manual_seed(1)
embedding_dim = 10
raw_text = """
Chang Choi is currently an Assistant Professor in the Department of Computer Engineering at Gachon University, Seongnam, Korea, Since 2020.
He received B.S., M.S. and Ph.D. degrees in Computer Engineering from Chosun University in 2005, 2007, and 2012, respectively.
he was a research professor at the same university.
He was awarded the academic awards from the graduate school of Chosun University in 2012.
""".split()
defmake_context_vector(context, word_to_idx): #ํ ์๋ก ๋ณํ
idxs = [word_to_idx[w] for w in context]
return torch.tensor(idxs, dtype=torch.long)
vocab = set(raw_text) #๋ฆฌ์คํธํ์ > ๋์ ๋๋ฆฌ ํ์์ผ๋ก ๋ง๋ฌ
vocab_size = len(vocab) #47๊ฐ ์์.#๋์ ๋๋ฆฌ ํํ๋ก ๋ง๋ค๊ธฐ
word_to_idx = {word: i for i, word inenumerate(vocab)}
idx_to_word = {i: word for i, word inenumerate(vocab)}
data = []
for i inrange(2, len(raw_text) - 2):
target = [raw_text[i - 2], raw_text[i - 1],
raw_text[i + 1], raw_text[i + 2]]
context = raw_text[i]
data.append((context, target)) #data์๋ค๊ฐ ์ ์ฅ.#ex> data = (['Chang', 'Choi', 'currently', 'an'], 'is') ...classSkipGram(nn.Module):
def__init__(self, vocab_size, embedding_dim):
super(SkipGram, self).__init__()
self.embeddings = nn.Embedding(vocab_size, embedding_dim) #์๋ฒ ๋ฉ์ฐจ์ ์ค์
self.proj = nn.Linear(embedding_dim, 128)
self.output = nn.Linear(128, vocab_size)
defforward(self, inputs):
out = sum(self.embeddings(inputs)).view(1, -1) #๋จ์ด ์ฌ์ด์ฆ๋ฃ์ผ๋ฉด [,,,,,,,] ํ์์ผ๋ก ๋ฃ์
out = F.relu(self.proj(out))
out = self.output(out)
out = F.log_softmax(out, dim=-1)
return out
model = SkipGram(vocab_size, embedding_dim)
optimizer = optim.SGD(model.parameters(), lr=0.001)
losses = []
loss_function = nn.NLLLoss()
loss_function1 = nn.CrossEntropyLoss()
for epoch inrange(100):
total_loss = 0for context, target in data:
model.zero_grad()
input = make_context_vector(context, word_to_idx) # torchํ์์ผ๋ก ๋ง๋ค๊ธฐ > tensor[n,n,n,n]
output = model(input)
loss = loss_function(output, Variable(torch.tensor([word_to_idx[target]])))
loss.backward()
optimizer.step()
total_loss += loss.item()
losses.append(total_loss)
print(losses)
print("*************************************************************************")
context = ['Chang', 'Choi', 'currently', 'an']
context_vector = make_context_vector(context, word_to_idx)
a = model(context_vector).data.numpy()
print('Raw text: {}\n'.format(' '.join(raw_text)))
print('Test Context: {}\n'.format(context))
max_idx = np.argmax(a)
print('Prediction: {}'.format(idx_to_word[max_idx]))
https://comlini8-8.tistory.com/6 Distributed Representations of Words and Phrases and their Compositionality Efficient_Estimation_of_Word_Representations_in_Vector_Space https://everyday-log.tistory.com/entry/๋จ์ด-์๋ฒ ๋ฉ-2-Iteration-based-methods