Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
29 30
Tags
more
Archives
Today
Total
관리 메뉴

what i learned

[ML] Text Classification(1) - 텍스트 전처리 본문

Artificial Intelligence/Machine Learning

[ML] Text Classification(1) - 텍스트 전처리

햄식이111 2023. 10. 11. 07:19

텍스트를 분석하기 위해 텍스트 토큰화 작업을 수행하고 feature를 추출한다.

텍스트 분석 수행 프로세스

  1. 텍스트 전처리
  2. 피처 벡터화/추출
  3. ML 모델 수립 및 학습/예측/평가

이번 글은 전처리만 정리하고 벡터화 이후는 다음 글에 작성하겠다.

 

텍스트 토큰화

  • 문장 토큰화
  • 단어 토큰화

일반적으로 문장 토큰화는 각 문장이 가지는 시멘틱적인 의미가 중요할 때 사용하며
단어 토큰화는 구분자를 사용하여 단어를 토큰화할 수 있어서 BOW(Bag Of Words)와 같은 단어의 순서가 중요하지 않은 경우에 사용된다.

 

아래의 문장에 대해 토큰화 작업을 수행해보자.

💡 nltk 데이터 사용시 nltk.download()를 통해 데이터를 다운받을 수 있으며 최초 1번만 다운받는다. 자세한 정보는 nltk공식문서

import nltk
nltk.download('punkt')

text_sample = 'The Matrix is everywhere its all around us, here even in this room. \
               You can see it out your window or on your television. \
               You feel it when you go to work, or go to church or pay your taxes.'

문장 토큰화

from nltk import sent_tokenize

sentences = sent_tokenize(text=text_sample)
print(sentences)
# ['The Matrix is everywhere its all around us, here even in this room.', 'You can see it out your window or on your television.', 'You feel it when you go to work, or go to church or pay your taxes.']

sent_tokenize() 함수를 통해 문장 토큰화를 진행하고 sentences를 찍어보면 아래와 같이 문장별로 나뉘어진 것을 볼 수 있다.

 

단어 토큰화

from nltk import word_tokenize

sentence = "The Matrix is everywhere its all around us, here even in this room."
words = word_tokenize(sentence)

print(words)
# ['The', 'Matrix', 'is', 'everywhere', 'its', 'all', 'around', 'us', ',', 'here', 'even', 'in', 'this', 'room', '.']

word_tokenize() 함수를 통해 단어 토큰화를 진행하고 문장에서 단어 별로 나뉘어 출력된 것을 확인할 수 있다.

 

 

의미 없는 단어 제거(Stop Word)

텍스트 분석에 큰 의미를 갖고 있지 않은 단어를 제거해주는 작업이다.

해당하는 단어들을 확인해보자.

nltk.download('stopwords')

print('영어 stop words 갯수:',len(nltk.corpus.stopwords.words('english')))
# 영어 stop words 갯수: 179
print(nltk.corpus.stopwords.words('english')[:20])
# ['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his']

text_sample에서 stop words를 제거하여 토큰화를 진행하면

from nltk import word_tokenize, sent_tokenize

#여러개의 문장으로 된 입력 데이터를 문장별로 단어 토큰화 만드는 함수
def tokenize_text(text):
    # 문장별로 분리 토큰
    sentences = sent_tokenize(text)
    # 분리된 문장별 단어 토큰화
    word_tokens = [word_tokenize(sentence) for sentence in sentences]
    return word_tokens

#여러 문장들에 대해 문장별 단어 토큰화 수행
word_tokens = tokenize_text(text_sample)
print(word_tokens)
# [['The', 'Matrix', 'is', 'everywhere', 'its', 'all', 'around', 'us', ',', 'here', 'even', 'in', 'this', 'room', '.'], ['You', 'can', 'see', 'it', 'out', 'your', 'window', 'or', 'on', 'your', 'television', '.'], ['You', 'feel', 'it', 'when', 'you', 'go', 'to', 'work', ',', 'or', 'go', 'to', 'church', 'or', 'pay', 'your', 'taxes', '.']]


import nltk
stopwords = nltk.corpus.stopwords.words('english')
all_tokens = []
# word_tokens list 에 대해 stop word 제거 Loop
for sentence in word_tokens:
    filtered_words=[]
    # 개별 문장별로 tokenize된 sentence list에 대해 stop word 제거 Loop
    for word in sentence:
        #소문자로 모두 변환
        word = word.lower()
        # tokenize 된 개별 word가 stop words 들의 단어에 포함되지 않으면 word_tokens에 추가
        if word not in stopwords:
            filtered_words.append(word)
    all_tokens.append(filtered_words)
    
print(all_tokens)
# [['matrix', 'everywhere', 'around', 'us', ',', 'even', 'room', '.'], ['see', 'window', 'television', '.'], ['feel', 'go', 'work', ',', 'go', 'church', 'pay', 'taxes', '.']]

 

 

Stemming & Lemmatization

단어의 원형을 찾는 작업이다.

예를 들어 amusing, aumused, amuses 들은 원형 amuse에서 파생된 단어들이므로 원형을 찾는 작업을 하는 것이다.

Stemming과 Lemmatization은 원형을 찾을 때 의미를 가진 원형을 찾아내는지를 기준으로 다르게 작동하는데,

Stemming의 경우 의미를 가진 원형을 찾아내는 것이 아닌 단어의 공통적인 부분을 찾아내는 반면

Lemmatization은 의미를 가진 정확한 원형을 찾아낸다는 차이가 있다.

그렇기 때문에 Lemmatization 방법이 Stemming 방법보다 속도가 다소 느리다는 단점이 있다.

 

Stemming

from nltk.stem import LancasterStemmer
stemmer = LancasterStemmer()

print(stemmer.stem('working'),stemmer.stem('works'),stemmer.stem('worked'))
print(stemmer.stem('amusing'),stemmer.stem('amuses'),stemmer.stem('amused'))
print(stemmer.stem('happier'),stemmer.stem('happiest'))
print(stemmer.stem('fancier'),stemmer.stem('fanciest'))
'''
work work work
amus amus amus
happy happiest
fant fanciest
'''

Lemmatization

from nltk.stem import WordNetLemmatizer
import nltk
nltk.download('wordnet')

lemma = WordNetLemmatizer()
print(lemma.lemmatize('amusing','v'),lemma.lemmatize('amuses','v'),lemma.lemmatize('amused','v'))
print(lemma.lemmatize('happier','a'),lemma.lemmatize('happiest','a'))
print(lemma.lemmatize('fancier','a'),lemma.lemmatize('fanciest','a'))
'''
amuse amuse amuse
happy happy
fancy fancy
'''

Lemmatization은 amuse라는 정확한 원형을 찾지만 Stemming은 단순히 공통적인 부분만 찾아 amus를 출력하게 된다.

 

 

 

[ML] Text Classification(2) - Feature Vectorization

[ML] Text Classification(1) - 텍스트 전처리 "파이썬 머신러닝 완벽 가이드(권철민 저)" 텍스트를 분석하기 위해 텍스트 토큰화 작업을 수행하고 feature를 추출한다. 텍스트 분석 수행 프로세스 텍스트

enddl3224.tistory.com

해당 깃헙링크 ➡️ github.com/enddl3224

 

 

 

"파이썬 머신러닝 완벽 가이드"를 학습하여 기록한 글입니다.


공부한 내용을 기록하는 공간입니다.

잘못된 정보가 있을 경우 댓글로 피드백 주세요.

올바른 지식을 알려주셔서 감사합니다:)