rueki
카운트 기반 단어 표현 - Bag of Words(Bow) 본문
728x90
반응형
단어의 순서는 고려하지 않고, 출현 빈도에만 집중하는 텍스트 데이터 수치화 표현 방법이다.
Bow를 만드는 과정
1) 각 단어에 고유 인덱스 부여
2) 각 인덱스의 위치에 단어 토큰의 등장 횟수를 기록한 벡터(Vector)
Bow를 한번 만들어보자
from konlpy.tag import Okt
import re
okt = Okt()
token = re.sub("(\.)","","정부가 발표하는 물가상승률과 소비자가 느끼는 물가상승률은 다르다.")
token = okt.morphs(token)
token
['정부', '가', '발표', '하는', '물가상승률', '과', '소비자', '가', '느끼는', '물가상승률', '은', '다르다']
토큰화 진ㅌ
word2index = {}
bow = []
for voca in token:
if voca not in word2index.keys():
word2index[voca] = len(word2index)
# token을 읽으면서, word2index에 없는 (not in) 단어는 새로 추가하고, 이미 있는 단어는 넘깁니다.
bow.insert(len(word2index)-1,1)# BoW 전체에 전부 기본값 1을 넣어줍니다. 단어의 개수는 최소 1개 이상이기 때문입니다.
else:
index = word2index.get(voca) # 재등장하는 단어의 인덱스를 받아옵니다.
bow[index] = bow[index]+1# 재등장한 단어는 해당하는 인덱스의 위치에 1을 더해줍니다. (단어의 개수를 세는 것입니다.)
print(word2index)
{'정부': 0, '가': 1, '발표': 2, '하는': 3, '물가상승률': 4, '과': 5, '소비자': 6, '느끼는': 7, '은': 8, '다르다': 9}
토큰화 결과 고유 인덱스 부여
bow
[1, 2, 1, 1, 2, 1, 1, 1, 1, 1]
예시를 가지고 토큰화를 진행해서 각 토큰들이 얼만큼 나오는지 수치화를 해보았다.
Bow의 경우에는 인덱스의 순서가 바뀌어도 전혀 상관이 없다.
Sklearn에서는 단어의 빈도를 count해서 벡터화하는 CountVectorizer를 지원한다.
from sklearn.feature_extraction.text import CountVectorizer
corpus = ['you know I want your love. because I love you.']
vector = CountVectorizer()
print(vector.fit_transform(corpus).toarray())
print(vector.vocabulary_)
[[1 1 2 1 2 1]]
{'you': 4, 'know': 1, 'want': 3, 'your': 5, 'love': 2, 'because': 0}
수치화 된 결과와 인덱스한 결과를 알 수 있지만,
CountVectorizer은 띄어쓰기만을 기준으로 토큰화가 진행되기 때문에 한국어에서는 제대로 적용할 수가 없다.
그리고 빈도 수를 수치화하는 목적은 주된 단어가 얼마나 쓰였는지를 알기 위해서인데,
불용어가 수치화 된다면, 쓸모없는 데이터만 늘어날 뿐이다.
from sklearn.feature_extraction.text import CountVectorizer
text = ["Family is not an important thing. It's everything."]
vect = CountVectorizer(stop_words='english')
print(vect.fit_transform(text).toarray())
print(vect.vocabulary_)
[[1 1 1]]
{'family': 0, 'important': 1, 'thing': 2}
CountVectorizer에서 제공하는 기본 불용어 셋으로 제거를 해보았다.
from sklearn.feature_extraction.text import CountVectorizer
from nltk.corpus import stopwords
sw = stopwords.words("english") # nltk서 제공하는 불용어
text = ["Family is not an important thing. It's everything."]
vect = CountVectorizer(stop_words=sw)
print(vect.fit_transform(text).toarray())
print(vect.vocabulary_)
[[1 1 1 1]]
{'family': 1, 'important': 2, 'thing': 3, 'everything': 0}
nltk에서 제공하는 불용어 사용
728x90
반응형
'DL > NLP' 카테고리의 다른 글
카운트 기반 단어 표현 - TF-IDF (0) | 2019.07.02 |
---|---|
카운트 기반 단어 표현 - 문서 단어 행렬(Document-Term Matrix, DTM) (0) | 2019.07.02 |
단어의 표현 (0) | 2019.07.02 |
언어 모델 - 조건부 확률 (0) | 2019.07.02 |
언어 모델 - 한국어 (0) | 2019.07.02 |
Comments