자연어와 단어의 분산 표현

박영욱·2025년 4월 27일

한국어와 영어 등 우리가 평소에 쓰는 말을 자연어(natural language)라고 합니다. 그러니 자연어 처리(Natural Language Processing,NLP)를 문자 그대로 해석하면 ' 자연어를 처리하는 분야' 리고 말할 수 있습니다.

분산표현이란 단어의 의미를 정확하게 파악할 수 있는 벡터 표현을 말합니다.

import numpy as np

def process(text):
    text=text.lower()
    text=text.replace('.',' .')
    words=text.split(' ')
    
    word_to_id={}
    id_to_word={}
    for word in words:
        if word not in word_to_id:
            new_id=len(word_to_id)
            word_to_id[word]=new_id
            id_to_word[new_id]=word

    corpus=np.array([word_to_id[w] for w in words])

    return corpus, word_to_id, id_to_word


text='Hello  My name is younguk'
print(process(text))


(array([0, 1, 2, 3, 4, 5]), {'hello': 0, '': 1, 'my': 2, 'name': 3, 'is': 4, 'younguk': 5}, {0: 'hello', 1: '', 2: 'my', 3: 'name', 4: 'is', 5: 'younguk'})

###동시발생 행렬에 대한 자동화 알고리즘을 구축하기 위한 코드

def create_co_matrix(corpus, vocab_size, window_size=1):
    corpus_size=len(corpus)
    co_matrix=np.zeros((vocab_size, vocab_size), dtype=np.int32)

    for idx,word_id in enumerate(corpus):
        for i in range(1, window_size+1):
            
            left_idx=idx-i
            right_idx=idx+i

            if left_idx >=0:
                left_word_id=corpus[left_idx]
                co_matrix[word_id, left_word_id]+=1

            if right_idx<corpus_size:
                right_word_id=corpus[right_idx]
                co_matrix[word_id,right_word_id]+=1
    return co_matrix

벡터 간 유사도
코사인 유사도 값은 -1에서 1사이이므로 만약 유사도에서 0.707710의 값이 나오면 유사성이 크다고 말할 수 있습니다.

def cos_similarity(x,y, eps=1e-8):
    nx=x/(np.sqrt(np.sum(x**2))+eps)
    ny=y/(np.sqrt(np.sum(y**2))+eps)
    return np.dot(nx,ny)

eps는 인수로 제로 벡터(원소가 모두 0인 벡터)가 들어오면 0으로 나누기에서 오류가 발생하므로 분모에 작은 값을 더해주어 오류를 방지하기 위함입니다.

profile
Medical AI

0개의 댓글