Models that assign probabilities to upcoming words, or sequences of words in general, are called language models (LMs).

  • Predicting upcoming words turns out that the large language models that revolutionised modern NLP are trained just by predicting words.

Why does it matter what the probability of a sentence is or how probable the next word is?

  • In many NLP applications, we can use the probability as a way to choose a better sentence or word over a less-appropriate one.

Language models can also help in augmentative and alternative communication (AAC) systems.

  • People often use such AAC devices if they are physically unable to speak or sign but can instead use eye gaze or other specific movements to select words from a menu.
  • Word prediction can be used to suggest likely words for the menu.

N-gram language model

  • An n-gram is a sequence of n words:
    • A 2-gram (bigram) is a two-word sequence of words like "please turn", "turn your", or "your homework".
    • A 3-gram (trigram) is a three word sequence of words like "please turn your", or "turn your homework".
  • The word 'n-gram' is also used to mean a probabilistic model that can estimate the probability of a word given the n-1 previous words, and thereby also to assign probabilities to entire sequences.

Suppose the history h is "its water is so transparent that" and we want to know the probability that the next word is "the":

P(the | its water is so transparent that)

One way to estimate this probability is from relative frequency counts:

  • Take a very large corpus, count the number of times we see "its water is so transparent that", and count the number of times this is followed by "the'.

Out of the times we saw the history h, how many times was it followed by the word w, as follows:

P(the | its water is so transparent that) = C(its water is so transparent that the) / C(its water is so transparent that)

 

To represent the probability of a particular random variable

$$ X_i $$

taking on the value "the" or

$$ P(X_i="the") $$

we will use the simplication

$$ P(the) $$

To compute probabilities of entire sequences like

$$ P(X_n|X_{1:n-1}) $$

One things we can do is decompose this probability using the chain rule of probability:

$$ P(X_1...X_n)=P(X_1)P(X_2|X_1)P(X_3|X_{1:2})...P(X_n|X_{1:n-1}) $$

$$ = \prod_{k=1}^{n}P(X_k|X_{1:k-1}) $$

Applying the chain rule to words, we get:

$$ P(w_{1:n})=P(w_1)P(w_2|w_1)P(w_3|w_{1:2})...P(w_n|w_{1:n-1}) $$

$$ =\prod_{k=1}^{n}P(w_k|w_{1:k-1}) $$

The chain rule shows the linke between computing the joint probability of a sequence and computing the conditional probability of a word given previous words.

  • We could estimate the joint probability of an entire sequence of words by multiplying together a number of conditional probabilities.

We can't just estimate by counting the number of times every word occurs following every long string, because language is creative and any particular context might have never occurred before.

 

The intuition of the n-gram model is that instead of computing the probability of a word given its entire history, we can approximate the history by just the last few words.

  • For example, the bigram model approximates the probability of a word given all the previous words by using only the conditional probability of the preceding word.
    • Instead of computing the probability P(the | Walden Pond's water is so transparent that),
      we approximate it with the probability P(the | that)
  • When we use a bigram model to predict the conditional probability of the next word, we are thus making the following approximation:

$$ P(w_n|w_{1:n-1})\approx P(w_n|w_{n-1}) $$

 

The assumption that the probability of a word depends only on the previous word is called a Markov assumption.

  • Markov models are the class of probabilistic models that assume we can predict the probability of some future unit without looking too far into the past.

A general equation for a n-gram approximation to the conditional probability of the next word in a sequence:

$$ P(w_n|w_{1:n-1})\approx P(w_n|w_{n-N+1:n-1}) $$

※ N means the n-gram size (N=2 means bigrams and N=3 means trigrams)

 

An intuitive way to estimate probabilities is called maximum likelihood estimation (MLE).

  • We get the MLE estimate for the parameters of an n-gram model by getting counts from a corpus, and normalising the counts so that they lie between 0 and 1.

To compute a particular bigram probability of a word

$$ w_n $$

given a previous word

$$ w_{n-1} $$

we'll compute the count of the bigram

$$ C(w_{n-1}w_n) $$

and normalise by the sum of all the bigrams that share the same first word

$$ w_{n-1} $$

The computation is:

$$ P(w_n|w_{n-1})=\frac{C(w_{n-1}w_n)}{\sum _wC(w_{n-1}w)} $$

The sum of all bigram counts that start with a given word

$$ W_{n-1} $$

must be equal to the unigram for that word, so the simplified equation is as follows:

$$ P(w_n|w_{n-1})=\frac{C(w_{n-1}w_n)}{C(w_{n-1})} $$

 

Language model probabilities are always represented and computed in log format as log probabilities.

  • Since probabilities are less than or equal to 1, the more probabilities we multiply together, the smaller the product becomes.

By using log probabilities instead of raw probabilities, we get numbers that are not as small.

  • Adding in log space is equivalent to multiply in linear space, so we combine log probabilities by adding them.

$$ P_1\times P_2\times P_3\times P_4=exp(log{P_1}+log{P_2}+log{P_3}+log{P_4}) $$

The result of doing all computation and storage in log space is that we only need to convert back into probabilities if we need to report them at the end; then we can just take the exp of the logprob!

 

Evaluating language models

  • Extrinsic evaluation is the end-to-end evaluation (often very expensive!)
  • Intrinsic evaluation measures the quality of a model independent of any application
    • Perplexity (sometimes abbreviated as PP or PPL): the standard intrinsic metric for measuring language model performance, both for simple n-gram language models and for the more sophisticated neutral large language models.

In order to evaluate any machine learning model, at least three distinct data sets are needed:

  1. Training set is used to learn the parameters of the model
  2. Development test set (or devset) is used to see how good the model is by testing on the test
  3. Test set is used to evaluate the model → held-out set of data, not overlapping with the training set

Given two probabilistic models, the better model is the one that has a tighter fit to the test data or that better predicts the details of the test data, and hence will assign a higher probability to the test data.


The perplexity of a language model on a test set is the inverse probability of the test set (one over the probability of the test set), normalised by the nubmer of words. For this reason, it's sometimes called the per-word perplexity.

For a test set

$$ W=w_1w_2...w_N $$

$$ perplexity(W)=P(w_1w_2...w_N)^{-\frac{1}{N}} $$

$$ =\sqrt[N]{\frac{1}{P(w_1w_2...w_N)}} $$

Or we can use the chain rule to expand the probability of W:

$$ \sqrt[N]{\prod_{i=1}^{N}\frac{1}{P(w_i|w_1...w_{i-1})}} $$

  • Because of the inverse, the higher the probability of the word sequence, the lower the perplexity.
    → Thus the lower the perplexity of a model on the data, the better the model, and minimising perplexity is equivalent to maximising the test set probability according to the language model.

Perplexity can also be thought of as the weighted average branching factor of a language.

  • The branching factor of a language is the number of possible next words that can follow any word.

If we have an artificial deterministic language of integer numbers whose vocabulary consists of the 10 digits, in which any digit can follow any other digit, then the branching factor of that language is 10.

 

Suppose that each of the 10 digits with exactly equal probability:

$$ P=\frac{1}{10} $$

Imagine a test string of digits of length N, and again, assume that in the training set all the digits occurred with equal probability. The perplexity will be

$$ perplexity(W)=P(w_1w_2...w_N)^{-\frac{1}{N}}=(\frac{1}{10}^N)^{-\frac{1}{N}}=\frac{1}{10}^{-1}=10 $$

'NaturalLanguageProcessing > Concept' 카테고리의 다른 글

(w08) Vector semantics and embeddings  (0) 2024.05.27
(w07) Lexical semantics  (0) 2024.05.22
(w04) Regular expression  (0) 2024.04.30
(w03) Text processing fundamentals  (0) 2024.04.24
(w02) NLP evaluation -basic  (0) 2024.04.17

헵 규칙 (Hebb rule) 은 최초의 신경망 학습 규칙 중 하나로, 1949년 도널드 헵 (Donald O. Hebb) 이 뇌의 시냅스 변형 메커니즘으로 제안한 이후로 인공 신경망 훈련에 사용되고 있다.

 

당시 헵이 집필한 'The Organization of Behavior' 책에는 헵 학습으로 알려진 가정 (공리) 이 있다.

세포 A의 축삭이 세포 B를 자극하기에 충분히 가깝고 B를 발화하는 데 반복적 또는 지속적으로 참여할 때, 한쪽 또는 양쪽 세포에 일종의 성장 과정이나 신진대사의 변화가 일어남으로써 B를 발화하는 세포 중 하나로서 A의 효율이 올라간다.

헵 학습 규칙은 다양한 신경망 구조와 결합해서 사용할 수 있다. 예를 들어 선형 연상 메모리 (linear associator) 가 있다.

이는 연상 메모리 (associative memory) 라고 하는 신경망 종류의 한 예로, 연상 메모리의 작업은 프로토타입 입력/출력 벡터의 Q개 쌍을 학습하는 것이다.

$$ \{p_1,t_1\}, \{p_2,t_2\}, ... , \{p_Q,t_Q\} $$

네트워크가 입력 p를 받으면 출력 t를 생성해야 하는데, 입력이 바뀌면 출력도 약간 바뀌어야 한다.

 

시냅스 양쪽에 있는 두 뉴런이 동시에 활성화되면 시냅스의 강도는 증가하게 될 것이다.

  • 위 그림에서 입력 p와 출력 a의 연결 (시냅스) 은 가중치 w이다.

헵의 가정은 양의 p가 양의 a를 생성한다면 w가 증가해야 한다는 것을 의미한다. 수학적 해석은 아래와 같다.

  • p는 q번째 입력 벡터의 j번째 요소
  • a는 q번째 입력 벡터가 네트워크에 제시될 때 네트워크 출력의 i번째 요소
  • 알파는 양의 상수이며, 학습률 (learning rate) 이라고 부름

이 식은 가중치 w의 변화가 시냅스 양쪽의 활성 함수의 곱에 비례한다는 사실을 말해준다.

 

참고로 이 식에 정의된 헵 규칙은 비지도 학습 (unsupervised learning) 규칙이므로, 목표 출력에 관련된 정보가 필요 없다. 지도 (supervised) 헵 규칙에서는 실제 출력을 목표 출력으로 대체할 수 있다.

이 방법은 알고리즘에게 '네트워크가 현재 하고 있는 것'이 아닌 '네트워크가 해야만 하는 것'을 알려준다.

  • t는 q번째 목표 벡터 t의 i번째 요소
  • 학습률은 1로 설정

벡터 표기법은 아래와 같다.

$$ W^N=W^O+t_qp_q^T $$

 

가중치 행렬을 0으로 초기화하고 Q개의 입력/출력 쌍을 한번에 적용하면 아래와 같이 작성할 수 있다.

$$ W=t_1p_1^T+t_2p_2^T+ ... +t_QP_Q^T=\sum_{q=1}^{Q}t_qp_q^T $$

이 식은 행렬 방식으로 표현될 수 있다.

$$ W=\begin{bmatrix}
t_1 & t_2 & ... & t_Q \\
\end{bmatrix}\begin{bmatrix}
p_1^T \\ p_2^T \\ ... \\ p_Q^T
\end{bmatrix}=TP^T $$

여기서

$$ T=\begin{bmatrix}
t_1 & t_2 & ... & t_Q \\
\end{bmatrix}, P=\begin{bmatrix}
p_1 & p_2 & ... & p_Q \\
\end{bmatrix} $$

 

선형 연상 메모리에 대한 헵 학습의 성능 분석 시 프로토타입 벡터 (p_q) 가 직교하면서 단위 길이를 갖는 정규직교 (orthonormal) 인 경우와 단위 길이를 갖지만 직교하지 않는 경우를 나눠서 살펴볼 수 있다.

  1. 정규직교인 경우:
    p_k 가 네트워크 입력이면 네트워크 출력은 다음과 같이 계산된다.
    $$ a=Wp_k=(\sum_{q=1}^{Q}t_qp_q^T)p_k=\sum_{q=1}^{Q}t_q(p_q^Tp_k) $$
    p_q 가 정규직교이기 때문에 다음과 같이 된다.
    $$ (p_q^Tp_k)=1, q=k $$
    $$ (p_q^Tp_k)=0, q!=k $$
    Identity matrix 가 되기 때문에 네트워크 출력은 다음과 같이 간단하게 작성될 수 있다.
    $$ a=Wp_k=t_k $$
  2. 단위 길이이지만, 직교가 아닌 경우:
    벡터가 직교하지 않기 때문에 네트워크는 정확한 출력을 생성하지 않을 것이며, 오차의 크기는 프로토타입 입력 패턴 사이에 상관 관계의 크기에 따라 달라진다.
    $$ a=Wp_k=t_k+\sum_{q!=k}^{}t_q(p_q^Tp_k) $$
    우항의 시그마는 오차를 나타낸다.

 

예제 1) 입력 벡터가 정규직교일 때

$$ p_1=\begin{bmatrix}
0.5 \\ -0.5 \\ 0.5 \\ -0.5
\end{bmatrix}, t_1=\begin{bmatrix}
1 \\ -1
\end{bmatrix}  $$

$$ p_2=\begin{bmatrix}
0.5 \\ 0.5 \\ -0.5 \\ -0.5
\end{bmatrix}, t_2=\begin{bmatrix}
1 \\ 1
\end{bmatrix} $$

가중치 행렬:

$$ W=TP^T=\begin{bmatrix}
1 & 1 \\
-1 & 1 \\
\end{bmatrix}\begin{bmatrix}
0.5 & -0.5 & 0.5 & -0.5 \\
0.5 & 0.5 & -0.5 & -0.5 \\
\end{bmatrix}=\begin{bmatrix}
1 & 0 & 0 & -1 \\
0 & 1 & -1 & 0 \\
\end{bmatrix} $$

각각의 프로토타입 입력에 대한 가중치 행렬 테스트 결과:

$$ Wp_1=\begin{bmatrix}
1 & 0 & 0 & -1 \\
0 & 1 & -1 & 0 \\
\end{bmatrix}\begin{bmatrix}
0.5 \\ -0.5 \\ 0.5 \\ -0.5 \\
\end{bmatrix} =\begin{bmatrix}
1 \\ -1
\end{bmatrix} $$

$$ Wp_2=\begin{bmatrix}
1 & 0 & 0 & -1 \\
0 & 1 & -1 & 0 \\
\end{bmatrix}\begin{bmatrix}
0.5 \\ 0.5 \\ -0.5 \\ -0.5 \\
\end{bmatrix}=\begin{bmatrix}
1 \\ 1
\end{bmatrix} $$

네트워크 출력이 목표와 동일하다는 것을 알 수 있다.

 

 

예제 2) 입력 벡터가 직교하지 않을 때

$$ p_1=\begin{bmatrix}
1 \\ -1 \\ -1
\end{bmatrix},
p_2=\begin{bmatrix}
1 \\ 1 \\ -1
\end{bmatrix} $$

두 프로토타입 입력을 정규화하고 희망 출력을 -1과 1로 각각 선택하면 다음과 같다.

$$ p_1=\begin{bmatrix}
0.5774 \\ -0.5774 \\ -0.5774
\end{bmatrix}, t_1=\begin{bmatrix}
-1
\end{bmatrix} $$

$$ p_2=\begin{bmatrix}
0.5774 \\ 0.5774 \\ -0.5774
\end{bmatrix}, t_2=\begin{bmatrix}
1
\end{bmatrix} $$

가중치 행렬:

$$ W=TP^T=\begin{bmatrix}
-1 & 1
\end{bmatrix}\begin{bmatrix}
0.5774 & -0.5774 & -0.5774 \\
0.5774 & 0.5774 & -0.5774 \\
\end{bmatrix}=\begin{bmatrix}
1 & 1.1548 & 0
\end{bmatrix} $$

두 프로토타입 패턴을 가중치 행렬과 곱하면 다음과 같다.

$$ Wp_1=\begin{bmatrix}
0 & 1.1548 & 0
\end{bmatrix}\begin{bmatrix}
0.5774 \\ -0.5774 \\ -0.5774
\end{bmatrix} =\begin{bmatrix}
-0.6668
\end{bmatrix} $$

$$ Wp_2=\begin{bmatrix}
0 & 1.1548 & 0
\end{bmatrix}\begin{bmatrix}
0.5774 \\ 0.5774 \\ -0.5774
\end{bmatrix} =\begin{bmatrix}
0.6668
\end{bmatrix} $$

출력이 목표 출력과 일치하지 않는다.

'ArtificialIntelligence > NeuralNetworkDesign' 카테고리의 다른 글

Key terms in deep neural networks  (0) 2023.11.07
Learning Rule  (0) 2023.10.24
Neuron Network Model  (0) 2023.07.13

단일 입력 뉴런 (Single input neuron)

입력이 1개인 뉴런

a = f(w * p + b)
  • a: 뉴런 출력 (축삭 신호)
  • p: 입력 (Scala or Matrix)
  • bias: 또 다른 입력의 편향
  • weight: 가중치 (시냅스 강도)
  • f: 전달/활성 함수

예를 들어 weight = 3, p = 2, b = -1.5 일 때, a = f(3 * 2 - 1.5) = f(4.5) 로 출력된다.

 

다중 입력 뉴런 (Multiple input neuron)

입력이 2개 이상인 뉴런

a = f(W * p + b)
  • Weight: 가중치 행렬

개별 입력 p1, p2,... 에 대응하는 각각의 가중치 w 존재

일 때 

 

로 표현할 수 있다.

 

 

계층

  • 출력 계층 (output layer)
  • 은닉 계층 (hidden layer)

1~2번째 은닉계층과 3번째 출력계층으로 이뤄진 네트워크

  • 순환 계층 (recurrent layer)

순환망 (recurrent network) 은 피드백이 있는 네트워크이므로, 피드포워드 (feedforward) 네트워크보다 강력하며 시간적 행동을 보여줄 수 있다.

 

전달함수 종류

 

1. 하드 리밋 (Hard Limit)

2. 대칭 하드 리밋 (Symmetrical Hard Limit)

3. 선형 (Linear)

4. 포화 선형 (Saturating Linear)

5. 대칭 포화 선형 (Symmetric Saturating Linear)

6. 로그-시그모이드 (Log-Sigmoid)

7. 하이퍼볼릭 탄젠트 시그모이드 (Hyperbolic Tangent Sigmoid)

8. 양의 선형 (Positive Linear)

9. 경쟁 (Competitive)

 

입력 2개의 뉴런 파라미터가 $$ b=1.2, W=\begin{bmatrix}
3 & 2 \\
\end{bmatrix}, p=\begin{bmatrix}
-5 & 6 \\
\end{bmatrix}^T $$ 인 경우 네트 입력은 $$ n=Wp+b=\begin{bmatrix}
3 & 2 \\
\end{bmatrix}\begin{bmatrix}
-5 \\ 6
\end{bmatrix}+(1.2)=-1.8 $$ 로 계산되고, 뉴런 출력은

  • 대칭 하드 리밋 전달 함수: $$ a=hardlims(-1.8)=-1 $$
  • 포화 선형 전달 함수: $$ a=satlin(-1.8)=0 $$
  • 하이퍼볼릭 탄젠트 시그모이드 전달 함수: $$ a=tansig(-1.8)=-0.9468 $$

등으로 구할 수 있다.

 

피드포워드 네트워크의 이진 패턴 인식에는 경계 값에 따라 분류를 하는 과정에서 애매한 경우 정확도가 떨어질 수 있는 문제가 있다. 이를 보완한 것이 해밍 (hamming) 네트워크와 홉필드 (hopfield) 네트워크이다.

 

해밍 네트워크는 피드포워드 계층과 순환 계층을 모두 이용한다.

피드포워드 계층에서는 프로토타입 벡터와 입력 벡터의 닮음 정도 (내적) 에 편향 벡터를 더해 값이 절대 음수가 되지 않게 함으로써 순환 계층이 적절히 작동하도록 한다. 순환 계층은 경쟁 계층으로, 피드포워드 계층 출력에 가중 행렬을 곱하는 과정을 반복한다. 가중 행렬은 아래와 같은 형태를 갖는다.

$$ W^2=\begin{bmatrix}
1 & -\varepsilon  \\
-\varepsilon  & 1 \\
\end{bmatrix} $$ 

Epsilon은 1/(S-1)보다 작은 숫자이며, S는 순환 계층에서 뉴런의 수다.

그림과 같이 포드피워드 계층 출력과 가중 행렬의 내적을 구하게 되면, 각 요소는 다른 요소의 동일 비율만큼 감소하게 된다.

  • 큰 요소는 작게 감소하고 작은 요소는 크게 감소함으로써 큰 요소와 작은 요소 간의 차이가 커질 것이다.

순환 계층의 효과는 가장 큰 값 (입력과 해밍 거리가 가장 가까운 프로토타입 패턴에 해당) 을 갖는 뉴런을 제외하고 모든 뉴런은 0을 출력한다.

 

해밍 네트워크는 선택한 프로토타입 패턴을 출력이 0이 아닌 뉴런으로 나타내는 반면, 홉필드 네트워크는 선택한 프로토타입 패턴을 출력한다.

홉필드 네트워크는 입력 벡터로 뉴런을 초기화하며 출력이 수렴될 때까지 반복한다. 해밍 네트워크는 피드포워드 계층의 가중치가 프로토타입 패턴이었던 반면, 홉필드 네트워크는 가중치 형렬과 편향 벡터를 설계해야 하기 때문에 비교적 복잡하게 느껴진다.

'ArtificialIntelligence > NeuralNetworkDesign' 카테고리의 다른 글

Key terms in deep neural networks  (0) 2023.11.07
Hebb Rule 헵 규칙  (1) 2023.10.24
Learning Rule  (0) 2023.10.24

+ Recent posts