티스토리 뷰

딥러닝

CBOW 1

4567은 소수 2021. 1. 26. 22:35

통계 기반 기법은 단어의 동시발생 행렬을 만들고 이를 SVD에 적용합니다.

단순히 생각했을 때 (n,n) 행렬을 SVD를 계산하는데에는 O(n^3)이 걸립니다. 그러므로 큰 데이터에서는 시간이 너무 오래 걸립니다. 

 

추론 기반 기법은 신경망을 이용해 미니배치로 학습을 시킵니다. 그리고 학습 과정을 통해서 가중치를 갱신합니다. 미니배치를 이용하므로 어휘 수가 많은 경우도 처리할 수 있습니다. 

 

추론 예시 : you ? goodbye and I say hello. 라는 문장에서 ?에 어떤 말이 들어갈 지를 추측하는 것입니다. 맥락으로 ?의 앞 뒤 단어를 사용하여 이 단어들 (you, goodbye)를 어떤 모델에 넣어 나올 수 있는 단어들의 확률을 구하는 것입니다.

 

원-핫 벡터 : "you say goodbye and I say hello." 라는 문장에서 어휘는 다음과 같습니다.

{"you", "say", "goodbye", "and", "i", "hello", "." }

이에 맞춰 해당 단어만 1 나머지는 0으로 표현한 것을 원핫벡터라 합니다.

(you : [1,0,0,0,0,0,0], say : [0,1,0,0,0,0,0], ...)

 

이를 책 1권의 신경망에서와 같이 이용할 수 있습니다.

(내용 책 참고)

 

- CBOW 모델 (continuous bag-of-words)

단순한 word2vec 모델은 CBOW 모델입니다. 

 

타깃 - 중앙 단어

맥락 - 주변 단어

 

맥락에 포함시킬 단어가 N개면 입력층 N개입니다. 입력층에서 은닉층으로의 변환에 사용된 가중치는 W_in (층마다 같은 값 사용), 은닉층에서 출력층으로의 변환에 사용된 가중치는 W_out 입니다. 

 

아래 코드에서 N=2, 은닉층의 노드 수는 3개인 경우입니다. 문장은 위의 you say goodbye and i say hello 이고, 타깃은 say, 맥락은 you, goodbye입니다. (여기서는 해당 타깃에 대한 score만 기록)

import sys
sys.path.append('..')
import numpy as np
from common.layers import MatMul

c0 = np.array([[1,0,0,0,0,0,0]])
c1 = np.array([[0,0,1,0,0,0,0]])

W_in = np.random.randn(7,3)
W_out = np.random.randn(3,7)

in_layer0 = MatMul(W_in)
in_layer1 = MatMul(W_in)
out_layer = MatMul(W_out)

h0 = in_layer0.forward(c0)
h1 = in_layer1.forward(c1)
h = 0.5 * (h0 + h1)
s = out_layer.forward(h)

print(s)

 

이와 더불어 CBOW 모델은 다음과 같습니다.

import sys
sys.path.append('..')
from common.layers import MatMul, SoftmaxWithLoss
import numpy as np

class SimpleCBOW:
    def __init__(self, vocab_size, hidden_size):
        V, H = vocab_size, hidden_size
        
        W_in = 0.01 * np.random.randn(V, H).astype('f')
        W_out = 0.01 * np.random.randn(H, V).astype('f')
        
        self.in_layer0 = MatMul(W_in)
        self.in_layer1 = MatMul(W_in)
        self.out_layer = MatMul(W_out)
        self.loss_layer = SoftmaxWithLoss()
        
        layers = [self.in_layer0, self.in_layer1, self.out_layer]
        self.params, self.grads = [], []
        for layer in layers:
            self.params += layer.params
            self.grads += layer.grads
            
        self.word_vecs = W_in
        
    def forward(self, contexts, target):
        h0 = self.in_layer0.forward(contexts[:,0])
        h1 = self.in_layer1.forward(contexts[:,1])
        h = 0.5 * (h0+h1)
        score = self.out_layer.forward(h)
        loss = self.loss_layer.forward(score, target)
        
        return loss
    
    def backward(self, dout=1):
        ds = self.loss_layer.backward(dout)
        da = self.out_layer.backward(ds)
        da *= 0.5
        self.in_layer1.backward(da)
        self.in_layer0.backward(da)
        return None

 

'딥러닝' 카테고리의 다른 글

BPTT  (0) 2021.01.29
네거티브 샘플링  (0) 2021.01.27
통계 기반 기법 2  (0) 2021.01.24
통계 기반 기법 1  (0) 2021.01.23
스파이럴 데이터셋을 이용한 신경망 학습  (0) 2021.01.22
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
TAG
more
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
글 보관함