Processing math: 100%
본문 바로가기

Data Science

텍스트 데이터 전처리 (Text Preprocessing)

전처리(Preprocessing)의 핵심

 

당연하게도, 주어진 Task에 맞게 전처리 해야한다.

ex) 감성분석 : 이모티콘을 함부로 지우면 안된다. (😀, ❤️ : 긍정적 신호일 수 있음)

ex) 음성인식 : 대본 같은 경우, 괄호 안의 설명문 등은 제거 필요 [ ex) 그물을 (조심스럽게) 건져올린다. ]

 

 

 

Corpus (코퍼스)

 

◎ 사전적 정의 : 말뭉치

 의미 : NLP 모델의 학습 대상이 되는 단어 또는 문장들의 집합

 Parallel Corpuss : 서로 다른 언어가 대응되는 말뭉치 (Bi-lingual, Multi-lingual)

 

ex) Korean-English Bi-lingual Corpus

Korean English
나는 아직 배고프다. I am still hungry.
내가 만든 쿠키. Cookie I made.

 

 

 

Tokenization (토큰화)

 

주어진 코퍼스(corpus)를 토큰(token) 단위로 나누는 작업

단어(vocab)의 갯수와 희소성(sparsity)을 줄이기 위한 작업

→ Corpus의 문장을 사전에 그대로 넣는 것은 굉장히 비효율적

→ 공개된 자연어처리 Library들을 활용해서 토큰화 작업 진행 (주어진 task 및 language에 적합한 library 활용)

→ Pos Tagging(형태소 분석)도 적용 가능

 

 

◎ Token 평균 길이

 

길이가 짧을수록, 길이가 길수록,
OOV (Out-Of-Vocab) 가능성 낮아짐 OOV 가능성 높아짐
Sparsity 감소 Sparsity 증가
모델 입력 Sequence 길이 길어짐 모델 입력 Sequence 길이 짧아짐

 

→  효율적인 압축 알고리즘 필요 (정보 이론과 관계 있음) (ex. BPE)

 

 

활용 가능 라이브러리(Library)들

◎ NLTK

from nltk.tokenize import word_tokenize
from nltk.tokenize import WordPuncTokenizer
from nltk.tokenize import TweetTokenizer

 

 

 

Cleaning (정제)

 

◎ 정제 : 텍스트에 존재하는 각종 노이즈들을 제거하는 작업

 

정확도작업 시간 간 Trade-off 관계

→ 적절한 합의점을 찾는 것이 중요하다.

 

 

불필요한 문자 제거

 

◎ 불필요하다고 생각되는 문자들을 제거할 수 있다.

ex) [ .,"!? ] / [ \n ] / 각종 이모티콘 등

 

◎ 하지만 불필요하다고 생각한 문자들이, 의미 형성에 관여하는 경우들이 있다.

ex) 감성분석 → 😊 이모티콘은 positive를 의미

 

 

대소문자 통합

 

대문자와 소문자를 둘 중 하나로 통일시키는 방법

ex) [ Shopping/shopping/SHOPPING/... ] → shopping or SHOPPING

→ 이렇게 해서 단어 사전의 크기를 줄일 수 있다.

 

 발생할 수 있는 문제점

ex) [ '미국'을 뜻하는 US / '우리'를 뜻하는 us] → 두 단어를 서로 같은 단어로 인식하게 된다.

ex) [ '사람 이름' Bush / '수풀'을 뜻하는 bush ]

 

 

길이가 짧은 단어 제거 (한글에는 적용하기 어려움)

 

◎ 영어의 경우 길이가 1~2인 단어를 삭제하는 것이, 의미없는 단어들을 제거하는 효과가 있다.

ex) [ in/on/a/an/by/... ]

 

◎ 하지만 한글은 글자 하나하나가 의미를 포함하는 경우가 많기 때문에, 이 방법을 적용하기 어렵다.

 

 

불필요하게 반복되는 철자들 제거

 

◎ SNS 글 등의 경우, 불필요하게 반복해서 넣는 철자들이 있다.

ex) yeaaaaaaah, craaaaaazy, ...

 

이런 철자들을 최대 길이 2개로 바꿔줄 수 있다.

ex) coooooooolcool

 

◎ 2개까지 허용해주는 이유는, 1개로 바꾸면 단어의 의미가 변할 수 있기 때문이다.

ex) bee : 벌 / be : be동사

 

 

 

Normalization (정규화)

 

◎ 정규화 : 의미는 같지만 표현 방법이 다른 단어들을 하나의 단어로 만들어주는 작업

→ 필요한 이유 : 같은 의미를 갖는 단어들을 통합하고, 사전의 크기를 줄일 수 있다.

ex) [ catching/caught/catch/... ] → catch

 

 

Stemming (어간 추출)

 

 어간(stem)을 추출하는 작업

 표제어 추출에 비해 섬세하지 않음

ex) have  hav

 

 활용 가능 라이브러리(Library)들

from nltk.stem import PorterStemmer
from nltk.stem import LancasterStemmer

 

 

Lemmatization (표제어 추출)

 

표제어 (Lemma) : 기본 사전형 단어

ex) [ am/is/are ] ⊂ be

ex) [ stemming/stemmed ] stem

 

활용 가능 라이브러리(Library)들

from nltk.stem import WordNetLemmatizer  # nltk.tag의 pos_tag와 함께 사용

 

 

 

 

Stopwords (불용어) 제거

 

불용어 (Stopwords) : 자주 등장하지만, 의미 분석에는 크게 도움되지 않는 단어들

ex) nltk 패키지의 영어 stopwords (nltk==3.8.1)

from nltk.corpus import stopwords
stopws = stopwords.words('english')
for i in range(0, len(stopws), 20):
    print(stopws[i:i+20])
    
# 총 179개의 단어
['i', 'me', 'my', 'myself', 'we', 'our', 'ours', 'ourselves', 'you', "you're", "you've", "you'll", "you'd", 'your', 'yours', 'yourself', 'yourselves', 'he', 'him', 'his']
['himself', 'she', "she's", 'her', 'hers', 'herself', 'it', "it's", 'its', 'itself', 'they', 'them', 'their', 'theirs', 'themselves', 'what', 'which', 'who', 'whom', 'this']
['that', "that'll", 'these', 'those', 'am', 'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'having', 'do', 'does', 'did', 'doing']
['a', 'an', 'the', 'and', 'but', 'if', 'or', 'because', 'as', 'until', 'while', 'of', 'at', 'by', 'for', 'with', 'about', 'against', 'between', 'into']
['through', 'during', 'before', 'after', 'above', 'below', 'to', 'from', 'up', 'down', 'in', 'out', 'on', 'off', 'over', 'under', 'again', 'further', 'then', 'once']
['here', 'there', 'when', 'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only']
['own', 'same', 'so', 'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', "don't", 'should', "should've", 'now', 'd', 'll', 'm', 'o']
['re', 've', 'y', 'ain', 'aren', "aren't", 'couldn', "couldn't", 'didn', "didn't", 'doesn', "doesn't", 'hadn', "hadn't", 'hasn', "hasn't", 'haven', "haven't", 'isn', "isn't"]
['ma', 'mightn', "mightn't", 'mustn', "mustn't", 'needn', "needn't", 'shan', "shan't", 'shouldn', "shouldn't", 'wasn', "wasn't", 'weren', "weren't", 'won', "won't", 'wouldn', "wouldn't"]

 

◎ 불용어 제거 전 주의할 점

ex) 감성분석 : [ couldnt/didnt/... ] 등의 "not" 이 negative의 의미를 가질 수 있다.

 

 

 

 


 

 References

 

< wikidocs, Text Preprocessing >

 

'Data Science' 카테고리의 다른 글

Word2Vec  (0) 2023.10.06
TF-IDF  (0) 2023.10.02
Central Limit Theorem (중심극한정리)  (0) 2023.07.16
Mean Squared Error (MSE)  (0) 2023.06.16
Mutual Information  (0) 2023.06.13