Learning Word Embeddings

[Neural language model]

빈 칸에 들어갈 말은?

$o_{index} \cdot E = e_{index}$ 형식으로 모든 단어에 대해서 300차원 embedding vector를 구함

 

입력 차원이 1800 (300차원 x 6개 단어) 인 신경망 레이어에 입력, softmax 통해 "juice" 출력하는 모델 학습

 

혹은 'fixed historicla window' 통해서 빈 칸 앞 네 개의 단어(이 단어의 개수 또한 파라미터)만 보도록 설정할 수 있음 - 아무리 긴 문장 입력하더라도 입력 길이가 정해져 있으므로 ok

이 경우 입력 차원은 1200 (300차원 x 4개 단어)

 

여기까지 보았을 때 파라미터는

- $E$ : 물론 모든 단어에 대해 동일한 행렬 $E$를 적용하므로 하나만 구하면 됨

- $W^{[1]}$, $b^{[1]}$, $W^{[2]}$, $b^{[2]}$ : 레이어의 weights

 

해당 알고리즘, word embedding을 나쁘지 않게 학습함

- orange juice, apple juice 예시에서 봤듯, the reason is in the algorithm's incentive to learn pretty similar word embeddings for orange and apple because doing so allows it to fit the training set better - it's going to see orange juice sometimes or see apple juice sometimes, and so if you have only a 300 dimensional feature vector to represent all of these words, the algorithm will find that it fits the training set best. 

 

위 알고리즘을 보다 generalize 해보기

 

[other context/target pairs]

I want a glass of orange juice to go along with my cereal

- juice : target

- (window=4일 경우) a glass of orange : context 

 

만약 language model 을 설계하려고 한다면 target 직전 단어들로 context 를 꾸리는 게 맞음

하지만 꼭 그런 목적이 아니라면 다른 단어들을 context 로 설정해도 됨

 

- 양쪽으로 4단어씩? a glass of orange ____ to go along with

- 앞 단어 하나? orange ____

- 근처에 있는 단어 하나? glass .... ____

---> 모두 word embedding 학습을 위해 사용될 수 있음

---> 여기까지 오니 매우 단순해진 context

 

 

Word2Vec

[Skip-grams]

I want a glass of orange juice to go along with my cereal

 

- context 와 그에 상응하는 target 설정

- context에 해당하는 단어를 random 하게 선정, 그리고 일정 window 안에서 random하게 선택한 단어로 target 선정

- context 단어가 주어졌을 때, random하게 선정된 단어는 무엇인가? - supervised learning 형식으로

 

이 과정은 supervised learning 을 잘하기 위함이 아니라, 이 learning problem을 활용해서 word embedding을 학습하기 위함임

 

[Model]

vocab size = 10000

$$Context\ c\longrightarrow Target\ t$$

$$x \longrightarrow y$$

- 이때 c 가 "orange" 이고, t가 "juice"라고 해보자.

- orange는 6257번째 단어, juice는 4834번째 단어다.

 

overall model

- 지난번과 같은 방식으로: $o_{c} \cdot E = e_{c}$

- 그리고 이 $e_{c}$를 softmax unit에 입력한다 -> 이 softmax는 $\hat{y}$를 출력한다

 

softmax 가 계산하는 것을 좀더 자세히 보자면,

$$P(t|c) = \frac{e^{\theta_{t}^{T}e_{c}}}{\sum_{j=1}^{10000}e^{\theta_{j}^{T}e_{c}}}$$

- $\theta_{t}$ : label output $t$와 연계된 파라미터

 

loss function

$$L(\hat{y}, y) =- \sum_{i=1}^{10000} y_{i} log \hat{y}_{i}$$

- 여기서는 $\hat{y}$, $y$ 를 one-hot representation으로 나타냄 - 10000차원의 벡터 (전체 10000개 타겟 후보 단어들에 대한 probability)

 

- matrix $E$는 많은 파라미터를 가지고 있을 것임 - corresponding to $e_{c}$

- softmax 파라미터 - $\theta_{t}$

- 이 모든 파라미터들에 대해 loss function을 최적화하면 --> embedding vectors

"Skip-gram model"

ㄴ context 단어로부터 몇 개 단어 건너 뛰고 target 단어 맞혀야 하므로

 

[Problems with softmax classification]

- computational speed

 

vocab의 10000개 단어 전부를 더해야 함 (vocab은 그 이상이 될 수 있음)

 

--> Hierarchical softmax classifier

한번에 10000개로 분류하지 말고, 

첫 5000개 단어에 있는가? 나머지 5000개 단어에 있는가?  (binary 문제로 접근)

그 다음 첫 2500개 단어에 있는가? 혹은 나머지 2500개에 있는가? 

반복 ...

이 경우 계산량은 linear하지 않고 $log |v|$ 이다

 

- 완벽하게 balanced(symmetric)한 트리를 사용하지는 않음

자주 쓰는 단어일수록 상위 계층에 위치시키는 방법이 있음 (잘 안 쓰는 단어는 much deeper in the tree)

 

How to sample the context $c$?

- target은 앞뒤 10단어 윈도우 이내에서 선정된다고 하자

- uniformly random하게 고르면 'the, of, a, and, to..'가 굉장히 많이 나온다

-> 이 불균형을 맞출 수 있는 휴리스틱한 샘플링 방식이 있음

 

 

Negative Sampling

efficient learning algorithm

 

[Defining a new learning problem]

"I want a glass of orange juice to go along with my cereal"

 

context | word | target? 

-----------------------

orange | juice  |      1

orange |  king  |      0

orange | book  |      0

orange |  the   |      0

orange |  of     |      0

 

orange-juice 쌍은 posivie example (target 라벨이 1)

ㄴ 이 쌍을 찾는 건 위에서 본 내용과 동일

ㄴ 이 positive 예시가 데이터 테이블의 첫번째 row 가 됨

 

orange-king 쌍은 negative example (target 라벨이 0)

ㄴ 주어진 문장에서 orange 고르고, vocab에서 아무 단어나 선택

 

orange-of 쌍

ㄴ 주어진 문장에서 orange 바로 옆에 나타나는 단어지만 라벨이 0이라는 점에 주목

 

--> 첫번째 row는 positive example을 두고, 나머지 k개 쌍에 대해서 vocab에서 임의로 단어를 선발하여 라벨 0으로 지정

ㄴ 데이터셋 크기가 작으면 k는 5~20 사이가 적당, 데이터셋 크기가 크면 2-5 사이가 적당 (데이터셋 크기가 클수록 k값 작음)

ㄴ 위 테이블은 k=4

 

이렇게 생성된 데이터 테이블을 가지고 모델을 학습한다

입력 x: context 단어 - 선택된 단어 쌍

예측 y: target인지 아닌지

 

 

[Model]

context 단어는 $c$, possible target 단어는 $t$, target 여부 라벨은 $y$ 라고 부르기로 함

 

-> logistic regression model 정의함

 

$$P(y=1|c, t) = \sigma(\theta_{t}^{T}e_{c})$$

- $\theta_{t}^{T}$ : parameter vector $\theta$ for each possible target word

- $e_{c}$ : embedding vector for each possible context word

 

주어진 예시에서 비율을 따지면 $k:1 = neg : pos$

 

훈련되는 모델

- 오렌지의 embedding vector $e_{6257}$ 을 구한 다음, 10000개 possible logistic regression classification problem 으로 이어짐

     - 10000개 중 하나는 "target word가 juice인가, 아닌가?" 를 분류

     - 10000개 중 하나는 "target word가 king인가, 아닌가?" 를 분류  ....

---> 10000 binary logistic regression classifiers 가 있음

- 이때 매 iteration마다 10000개를 모두 학습하는 것이 아니라, 위에서 선정한 (k+1)개에 대해서만 학습할 것

(on every iteration, you choose four different random negative words with which to train your algorithm on)

- 하나의 거대한 10000-way softmax 대신에, 10000개 binary classification 을 쓰며 iteration마다 그 중에서 5개만 훈련 시킴

- computational cost가 훨씬 절약됨

 

--> "negative sampling" 이라고 부르는 과정

 

[selecting negative exmaples]

 

k개의 negative example 은 어떻게 선정할까? 

- empirical frequency 를 기준으로 선정할 수 있음 : 이렇게 할 경우 the, of, and, ... 와 같은 단어를 선택할 가능성이 높음

- $\frac{1}{|v|}$로 uniformly random 하게 선정할 수 있음 : 이 또한 단어들의 non-representative 한 분포임

- 저자들이 쓰는 것은

 

$$P(w_{i}) = \frac{f(w_{i})^{\frac{3}{4}}}{\sum_{j=1}^{10000}f(w_{j})^{\frac{3}{4}}}$$

 

- $f(w_{i})$는 단어의 frequency (단어의 frequency의 $\frac{3}{4}$에 비례해서 선정)

ㄴ uniform distribution과 empirical frequency 사이

 

 

GloVe Word Vectors

[GloVe - global vectors for word representation]

 

"I want a glass of orange juice to go along with my cereal"

 

$x_{ij}$ : 단어 $j$가 context $i$에 등장하는 횟수

- $i$, $j$ : 각각 $c$, $t$의 역할을 함

 

context, target 단어의 정의에 따라, $x_{ij} = x_{ji}$일 수도 있다

- 만약에 $\pm 10$개 이내에 출현하는 단어로 정의한다면 symmetric relationship이 된다

 

인접한 곳에서(in close proximity) 두 단어가 출현하는지를 기준으로 context, target 정의하기로 함

 

[Model]

 

$$minimize \sum_{i=1}^{10000} \sum_{j=1}^{10000} f(X_{ij})(\theta_{i}^{T} e_{j} + b_{i} + b_{j}' - log X_{ij})^{2}$$

 

- 여기서 $i$가 $t$, $j$가 $c$ 역할을 한다고 보면 됨. 따라서 $\theta_{i}^{T} e_{j}$를 보면 $\theta_{t}^{T} e_cC}$가 생각나야 함

- "how related are those two words i and j as measured by how often they occur with each other?" 

- Sum을 최소화하기 위해 gradient descent 를 쓰고 파라미터 $\theta$를 solve 한다 - "You just want to learn vectors"

- 만약 $X_{ij}= 0$ 이면, $ log X_{ij}$는 negative infinity

--> weighting term $f(X_{ij})$를 추가한다

     - $X_{ij}= 0$ 이면 $f(X_{ij})=0$ 이다 ($0 log 0 = 0$)

     - 즉 $X_{ij}= 0$ 이면 해당 쌍에 대해서 sum을 구할 필요가 없다

     - "sum only over the pairs of words that have co-occurred at least once in that context-target relationship"

     - 영어에 자주 등장하는 단어들( this, is, a, of, ... )이 있고, 잘 등장하지 않는 단어들(durian)이 있다

     - 이때 weighting term은 durian처럼 잘 등장하지 않는 단어에도 유의미한 양의 계산을 부여해주고, this, is, of, a와 같이 자주 등장하는 단어에 '적당히' 가중치를 주는 기능을 한다

- 이 식에서 $\theta$와 $e$는 완전히 symmetric하다

--> 알고리즘 학습할 때, $\theta$와 $e$를 uniformly random하게 initialize 하고 목적함수를 최소화하기 위해 gradient descent 수행한다. 모든 단어에 대해서 계산이 끝나면, 평균을 낸다

 

$$e_{w}^{(final)} = \frac{e_{w}+e_{w}}{2}$$

 

 

[A note on the featurization view of word embeddings]

embeddings의 각 요소를 gender, royal, age, food로 해석해놨는데...

지금까지 본 알고리즘 중 하나로 word embedding을 학습시켰을 때, embeddings의 각 요소들이 꼭 해석 가능한 것은 아니다

하나의 요소가 여러 의미를 복합적으로 내포하고 있을 수도 있음

"you can't guarantee that the axis used to represent the features will be well-aligned with what might be easily humanly interpretable axis"

 

- 가역행렬 A 가 있을 때 

$$(A\theta_{i})^{T} (A^{-T}e_{j}) = \theta_{i}^{T}  \cdot A^{T}A^{-T}  \cdot e_{j}$$

 

- analogy still works!

복사했습니다!