-
[Deep Learning] NLP - 불용어 ( Stop Words ) 처리Data Science/Machine Learning & Deep Learning 2021. 4. 15. 00:12
어떠한 데이터를 토큰화한 후 문서에 많이 사용된 단어를 보면 'I', 'and', 'of' 등의 텍스트 내에서 큰 의미를 가지지 않는 것들을 볼 수 있습니다. 이는 그다지 텍스트의 내용을 이해하는데 도움이 되지 않는 것들로 불용어(Stop words) 라고 합니다.
대부분의 NLP 라이브러리는 불용어 사전을 내장하고 있습니다.
spacy의 불용어 사전을 보겠습니다.
import spacy # load the small english model nlp = spacy.load("en_core_web_sm") print(nlp.Defaults.stop_words)
먼저 데이터를 불러와 불용어를 제거하지 않고 토큰화를 해보았습니다.
import spacy from spacy.tokenizer import Tokenizer # load the small english model nlp = spacy.load("en_core_web_sm") # Tokenizer 생성 tokenizer = Tokenizer(nlp.vocab) def tokenize(text): doc_token = [] for token in tokenizer(text): doc_token.append(token.text.lower()) return doc_token df['tokens'] = df['column_name'].apply(tokenize)
이후 토큰화 된 것을 Counter를 이용하여 카운트 한 후 많이 사용된 토큰 TOP10을 알아보겠습니다.
from collections import Counter # Counter : 리스트요소의 값과 요소의 갯수를 카운트 하여 저장 word_counts = Counter() # 토큰화된 각 리스트를 카운터 객체에 업데이트 # 카운터 객체는 .update 메소드로 계속 업데이트 가능 df['tokens'].apply(lambda x: word_counts.update(x)) # 가장 많은 단어 순으로 10개 나열 word_counts.most_common(10)
결과를 보면 to, you, I 등과 같은 불용어가 전부인 것을 볼 수 있습니다.
불용어는 분석에 불필요하고 도움이 되지 않는 경우가 많으므로 불용어를 처리하는 방법입니다.
tokens = [] # 토큰에서 불용어 제거, 소문자화 하여 업데이트 for doc in tokenizer.pipe(df['column_name']): doc_tokens = [] for token in doc: # 토큰이 불용어가 아니면 저장 if (token.is_stop == False): doc_tokens.append(token.text.lower()) tokens.append(doc_tokens) df['tokens'] = tokens
라이브러리에 기본으로 불용어 사전에 기본적으로 불용어를 담고 있지만, 여기에 원하는 불용어를 추가할 수도 있습니다.
우리가 사용할 데이터에 공통적으로 많이 포함이 되어 있다거나 하는 분석시 불필요한 단어를 토큰화 과정에 없애주고자 한다면
불용어 사전에 해당 단어를 추가하는 불용어 확장 후 토큰화하여 사용할 수 있습니다.
리스트 안에 원하는 수 만큼 원하는 단어를 불용어 사전에 추가하면 됩니다.
STOP_WORDS = nlp.Defaults.stop_words.union(['word1','word2', 'word3'])
print(STOP_WORDS)
print해보면 불용어 사전에 담긴 기본 불용어에 추가한 불용어가 더해진 것을 확인할 수 있습니다.
이제 확장한 불용어를 토큰화 과정에서 제거할 수 있습니다.
tokens = [] for doc in tokenizer.pipe(df['column_name']): doc_tokens = [] for token in doc: if token.text.lower() not in STOP_WORDS: doc_tokens.append(token.text.lower()) tokens.append(doc_tokens) df['tokens'] = tokens
'Data Science > Machine Learning & Deep Learning' 카테고리의 다른 글
[Deep Learning] NLP - 어간추출(stemming) & 표제어추출(lemmatization) (0) 2021.04.16 [Deep Learning] NLP - 통계적 트리밍(Trimming) (0) 2021.04.15 [Deep Learning] NLP - 텍스트 토큰화 ( Tokenization ) (0) 2021.04.13 [Deep Learning] 손실함수(Loss Function) (0) 2021.04.13 [Deep Learning] 역전파 ( Back Propagation ) (0) 2021.04.11