자연어 처리에서 프리프로세싱이란 실질적인 feature engineering이나 modelling을 하기위한 형태로 corpus를 조작하고 분해하는 등의 모든 전처리작업을 의미합니다.
corpus를 word나 sentence의 형태로 나누는 것으로,
주로 scipy나 NLTK 등 토크나이저 라이브러리를 이용합니다.
영어 모델 로딩
nlp = spacy.load('en_core_web_sm')
문장 지정
# Sample sentence.
s = "He didn't want to pay $20 for this book."
doc = nlp(s)
출력
print([t.text for t in doc])
###
['He', 'did', "n't", 'want', 'to', 'pay', '$', '20', 'for', 'this', 'book', '.']
case folding이란 대/소문자를 일치시키는 것을 의미합니다.
같은 단어이나 대/소문자가 다르면 다른 vocabulary토큰으로 인식될 수 있기 때문입니다.
이는 전체 vocabulary 수를 줄여 계산과 모델링을 용이하게 만들지만,
사람의 이름처럼 대소문자가 다를 필요가 있는 경우에, 정보 손실(information loss)가 발생하는 문제가 있습니다.
import spacy
nlp = spacy.load('en_core_web_sm')
s = "He told Dr. Lovato that he was done with the tests and would post the results shortly."
doc = nlp(s)
print([t.lower_ for t in doc])
###
['he', 'told', 'dr.', 'lovato', 'that', 'he', 'was', 'done', 'with', 'the', 'tests', 'and', 'would', 'post', 'the', 'results', 'shortly', '.']
또한 다음과 같이 문장의 첫째단어는 제하도록 조건을 줄 수도 있습니다.
print([t.lower_ if not t.is_sent_start else t for t in doc])
###
[He, 'told', 'dr.', 'lovato', 'that', 'he', 'was', 'done', 'with', 'the', 'tests', 'and', 'would', 'post', 'the', 'results', 'shortly', '.']
공백이나 구두점(마침표, 쉼표, 느낌표 등)을 제거해야할 필요가 있을 때가 있습니다.
이럴 경우는 다음과 같이 제거합니다.
[t for t in nlp(doc) if not t.is_punct and not t.is_space]
stop word란 빈번하게 등장하지만 문맥내에서 큰 의미를 가지지 않는 the, a, of, this, that, not 과 같은 단어들을 의미합니다.
이 역시 계산과 모델링의 효율성을 증진시키고 특히 topic modelling같은 태스크를 수행할때 효과적입니다.
그러나 not과 같은 stop word를 제거할 경우, sentiment analysis같은 태스크를 수행할때 좋지 못합니다.
# spaCy's default stop word list.
print(nlp.Defaults.stop_words)
print(len(nlp.Defaults.stop_words))
###
{'show', '‘ve', 'us', 'each', '’m', 'in', 'serious', 'however', 'a', '‘s', 'nevertheless', 'wherein', 'you', 'among', 'twenty', 'everywhere', 'someone', 'from', 'even', 'give', 'too', 'many', 'amongst', 'around', 'whoever', 'whole', 'may', 'enough', 'ourselves', 'herein', 'hence', 'until', 'hereafter', 'others', 'everyone', 'one', 'ever', 'also', 'hereby', 'wherever', 'down', 'n‘t', 'here', 'while', 'yourselves', 'side', 'can', 'see', 'fifty', 'together', 'are', 'of', 'than', 'few', 'therein', 'whither', 'eleven', 'most', 'then', "n't", 'become', 'does', 'being', 'their', 'after', 'first', "'re", 'would', 'fifteen', 'an', 'is', "'ll", 'off', 'done', 'has', 'part', 'sometimes', 'towards', 'cannot', 'have', 'when', 'alone', "'d", 'call', 'your', 'noone', 'became', 'him', 'me', 'beside', 'myself', 'about', 'for', '’d', '’ve', 'becomes', 'not', 'sometime', 'name', 'already', 'before', 'well', 'and', 'both', 'did', 'nine', 'yet', '‘d', 'used', 'with', 'whenever', 'over', 'n’t', 'ten', 'will', 'under', '‘ll', 'per', 'though', 'meanwhile', 'anything', 'now', 'thereupon', 'how', 'herself', 'beyond', 'must', 'sixty', 'but', 'out', 'say', 'something', 'various', 'much', 'else', 'along', 'still', 'am', 'below', 'own', 'his', 'because', 'against', '‘re', 'somehow', 'some', 'my', 'no', 'quite', 'whereby', 'another', 'itself', 'never', 'hereupon', 'all', 'them', 'five', 'eight', 'indeed', 'what', 'otherwise', 'six', 'empty', 'up', 'those', 'amount', 'they', 'whom', 'anyone', 'two', 'might', 'thru', '’ll', 'thereby', 'whereupon', 'hers', 'latterly', 'less', 'get', 'please', 'last', 'could', 'been', 'very', 'neither', 'so', 'keep', 'four', 'had', 'next', 'to', 'top', 'therefore', 'rather', 'take', 'nor', 'any', 'who', 'whence', 'onto', 'be', 'besides', 'former', 'put', 'such', 'further', 'or', 'always', 'on', 'yourself', 'upon', 'except', 'seems', 'almost', 'through', 'she', 'as', 'formerly', 'although', 'due', 'was', 'third', 'move', 'whereafter', 'beforehand', 'somewhere', 'themselves', 'nobody', 'becoming', 'seemed', 'during', 'mine', 'by', 'more', 'bottom', 'back', 'go', 'latter', 'often', 'its', 'the', 'whatever', 'ca', 'where', 'doing', 'only', "'ve", 'seem', '’s', 'either', 'which', 'moreover', 'thus', 'anyhow', 'there', 'anywhere', 'thereafter', 'throughout', "'s", 'really', 'hundred', 'via', 'front', 'same', 'seeming', 'were', 'none', 'within', 'elsewhere', 'should', 'just', 'once', '‘m', 'several', 'unless', 'perhaps', 'anyway', 'whereas', 'above', '’re', 'himself', 'namely', 'forty', 'since', 'regarding', 'every', 'everything', 'made', 'three', 'our', 'twelve', 'afterwards', 'he', 'nowhere', 'least', 'between', 'that', 'other', 'these', 'across', 'make', 'again', 'yours', 'it', 'ours', 'i', 'if', 'nothing', 'thence', 'toward', 'this', 'why', 'do', 'her', 'mostly', 'whether', 'into', 'whose', 'full', 're', 'without', 'behind', 'using', "'m", 'we', 'at'}
326
print([t for t in doc if not t.is_stop])
###
[told, Dr., Lovato, tests, post, results, shortly, .]
stemming은 엄격한 룰에 따라 단어의 suffixes(접미사)나 prefixes(접두사)를 제거하는 것입니다.
주로 영어에서는 -ing, -ed, -s, -y와 같은 것들을 칭하며
Banking, Banks와 같은 단어를 Bank라는 원형으로 일치시키기 위함입니다.
통상 Porter's algorithm으로 처리합니다.
stemming은 보통 엄격한 룰을 가지고 처리되기 때문에 간혹 사전에 없는 단어를 만들어내는 문제를 발생시킬 수 있습니다. (e.g. analysis > analysi)
혹은 overstem하여 university와 universe를 둘다 univers로 일치시켜버리거나 understem하여 alumni와 alumnus를 alumni와 alumnu로 미흡하게 처리할 수도 있습니다.
상기한 stemming의 문제 때문에 보다 정교하게 단어의 기본형(lemma)를 추출하는 lemmatization을 보통 더 선호됩니다.
stemming은 처리후 단어의 의미(meaning)가 상실되는 경우가 있는 반면 lemmatization은 단어의 의미(meaning)을 유지시킵니다.
단어의 굴절(inflexions) 형태인 Did, Done, Doing등을 원형인 Do로 만드는 것이 주요 역할입니다.
또한 verb나 adjective의 형태는 살린다는 것또 주요 장점입니다.
talkative의 경우 stemming 후에 talk라는 동사로 바뀌는데 lemmatization은 talkative로 유지합니다.
반면, 굴절 형태를 원형으로 만들기 때문에 시제가 중요한 태스크에서는 좋지 못합니다.
[(t.text, t.lemma_) for t in doc]
###
[('He', 'he'),
('told', 'tell'),
('Dr.', 'Dr.'),
('Lovato', 'Lovato'),
('that', 'that'),
('he', 'he'),
('was', 'be'),
('done', 'do'),
('with', 'with'),
('the', 'the'),
('tests', 'test'),
('and', 'and'),
('would', 'would'),
('post', 'post'),
('the', 'the'),
('results', 'result'),
('shortly', 'shortly'),
('.', '.')]
[1] nlpdemystified, https://www.nlpdemystified.org