돌맹이
[NLP] Feature Vectorization, 피처 벡터화 본문
NLP에서 텍스트 분석을 할 때, feature vectorization은 크게 2가지로 구분된다.
Count기반 벡터화 / TF-IDF기반 벡터화
Count기반 벡터화는 문서에 해당 단어가 나타난 횟수를 집계하는 방식으로, 많이 등장하는 단어의 count가 높게 측정된다.
언어의 특성상 실제로 중요하지 않은 'is'나 'the'와 같은 관사, be동사 단어들의 점수가 높게 측정된다는 단점이 있다.
# Count기반 Vectorization
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'apple is red',
'banana is yellow',
'what color is melon?',
'i love yellow color'
]
vector = CountVectorizer()
countvect_df_1 = pd.DataFrame(vector.fit_transform(corpus).toarray(), columns = sorted(vector.vocabulary_))
print(countvect_df_1) # 각각의 단어가 문장에서 몇번 등장했는지 count한 dataframe
Count기반 벡터화의 단점을 보완하기 위해 TF-IDF기반 벡터화는 개별문서에서 자주 나타나는 단어에 높은 점수를 주되, 모든 문서에서 전반적으로 등장하는 단어에는 패널티를 주는 방식으로 점수를 집계한다.
# TF-IDF기반 Vectorization
import nltk
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = [
'apple is red',
'banana is yellow',
'what color is melon?',
'i love yellow color'
]
vector = TfidfVectorizer()
countvect_df_2 = pd.DataFrame(vector.fit_transform(corpus).toarray(), columns = sorted(vector.vocabulary_))
print(countvect_df_2) # 각각의 단어별로 tf-idf값을 계산한 dataframe