반응형

토큰화와 클렌징을 통해 어느 정도 데이터를 분류하였다면, 정규화를 통해 전체 데이터의 수를 줄일 수 있습니다.

NLP에서 정규화를 설명할 때 가장 자주 등장하는 예시가 be 동사입니다. be동사는 is, are, am 등 사용할 때는 다양하게 나타나지만 실질적인 의미는 'be'로 볼 수 있습니다. 따라서 주어진 데이터 내에서 be동사로 표현되는 모든 단어를 개별 데이터로 보는 것이 아닌 be라는 1개의 데이터로 취급하게 되면 전체 데이터의 총량이 감소하게되며 이러한 작업을 정규화라 합니다.

본문에서는 porter알고리즘과 lancaster알고리즘을 통해 어간을 추출하는 방법을 소개합니다. 다만 어간 추출 자체가 정교한 작업은 아닙니다. 설정되어 있는 규칙에 의해 단어를 분리하기 때문에 분리된 단어는 실제로 사전에 등록되지 않은 단어로 나타날 수 있습니다. 

import nltk
nltk.download('wordnet')

from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
from nltk.stem import LancasterStemmer

2가지 어간추출 방법과 토큰화의 차이를 알아보기 위해 3가지 모듈을 import해줍니다.

wordnet 패키지가 이미 설치되어 있는 경우 처음 두줄은 생략가능합니다.

def porter_stem(tokenize_list):
    p = PorterStemmer()
    result = []

    for w in tokenize_list:
        result.append(p.stem(w))

    return result

def lancaster_stem(tokenize_list):
    l = LancasterStemmer()
    result = []

    for w in tokenize_list:
        result.append(l.stem(w))

    return result

porter 어간추출 방식을 사용하는 함수와 lancaster 어간추출 방식을 사용할 함수를 생성합니다.

def compare(origin, compare):
    
    result = []
    for i in range(len(origin)):
        if str(origin[i]) == str(compare[i]):
            pass
        else:
            result.append(compare[i])

    print('\033[1m' + str(result) + '\033[0m')

어간추출 결과와 단어 토큰화의 결과가 각각 어떤 차이를 보여주는지 비교하기 위한 함수를 생성해줍니다.

text = "The necrosis is closely related to the flow of blood. So we can make a diagnosis of tissue necrosis to observe the flow of blood."
#ref. S.H.LEE el. 2. "Development of Laser Speckle Contrast Imaging System for early diagnosing tissue necrosis.The Korea Society of Medical & Biological Engineering 2019 Oct 055"

word_tok= word_tokenize(text)

t1_p_stem = porter_stem(word_tok)

t1_l_stem = lancaster_stem(word_tok)

print("word_tokenize를 사용한 경우는 아래와 같습니다.")
print(word_tok)

print("아래는 포터알고리즘 어간추출(stemming)의 결과입니다.")
print(t1_p_stem)

print("아래는 란체스터알고리즘 어간추출(stemming)의 결과입니다.")
print(t1_l_stem)

print("아래는 일반적인 단어 토큰화를 사용한 경우와 porter 알고리즘, lancaster 알고리즘을 적용했을 때 결과의 차이입니다.")
compare(word_tok, t1_p_stem)
compare(word_tok, t1_l_stem)

word_tokenize를 사용한 경우는 아래와 같습니다.
['The', 'necrosis', 'is', 'closely', 'related', 'to', 'the', 'flow', 'of', 'blood', '.', 'So', 'we', 'can', 'make', 'a', 'diagnosis', 'of', 'tissue', 'necrosis', 'to', 'observe', 'the', 'flow', 'of', 'blood', '.']
아래는 포터알고리즘 어간추출(stemming)의 결과입니다.
['the', 'necrosi', 'is', 'close', 'relat', 'to', 'the', 'flow', 'of', 'blood', '.', 'So', 'we', 'can', 'make', 'a', 'diagnosi', 'of', 'tissu', 'necrosi', 'to', 'observ', 'the', 'flow', 'of', 'blood', '.']
아래는 란체스터알고리즘 어간추출(stemming)의 결과입니다.
['the', 'necros', 'is', 'clos', 'rel', 'to', 'the', 'flow', 'of', 'blood', '.', 'so', 'we', 'can', 'mak', 'a', 'diagnos', 'of', 'tissu', 'necros', 'to', 'observ', 'the', 'flow', 'of', 'blood', '.']
아래는 일반적인 단어 토큰화를 사용한 경우와 porter 알고리즘, lancaster 알고리즘을 적용했을 때 결과의 차이입니다.
porter : ['the', 'necrosi', 'close', 'relat', 'diagnosi', 'tissu', 'necrosi', 'observ']
lancaster : ['the', 'necros', 'clos', 'rel', 'so', 'mak', 'diagnos', 'tissu', 'necros', 'observ']
본자료는 딥 러닝을 이용한 자연어 처리 입문(Won Joon Yoo)을 참고합니다.
코드 전문은  https://github.com/Leo-bb/natural-language-processing에서 확인할 수 있습니다.


 

Leo-bb/natural-language-processing

Contribute to Leo-bb/natural-language-processing development by creating an account on GitHub.

github.com

 

반응형
복사했습니다!