Bag of Words 모델 구축

Python으로 배우는 NLP 피처 엔지니어링

Rounak Banik

Data Scientist

ML 알고리즘용 데이터 형식 요약

모든 ML 알고리즘에서,

  • 데이터는 표 형식이어야 함
  • 학습 특성은 숫자형이어야 함
Python으로 배우는 NLP 피처 엔지니어링

Bag of Words 모델

  • 단어 토큰 추출
  • 토큰 빈도 계산
  • 말뭉치의 어휘와 빈도로 단어 벡터 구성
Python으로 배우는 NLP 피처 엔지니어링

Bag of Words 모델 예시

말뭉치

"The lion is the king of the jungle"
"Lions have lifespans of a decade"
"The lion is an endangered species"
Python으로 배우는 NLP 피처 엔지니어링

Bag of Words 모델 예시

어휘집a, an, decade, endangered, have, is, jungle, king, lifespans, lion, Lions, of, species, the, The

"The lion is the king of the jungle"
[0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 2, 1]
"Lions have lifespans of a decade"
[1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0]
"The lion is an endangered species"
[0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1]
Python으로 배우는 NLP 피처 엔지니어링

텍스트 전처리

  • Lions, lionlion
  • The, thethe
  • 구두점 제거
  • 불용어 제거
  • 어휘 축소
  • 차원 수를 줄이면 성능 향상에 도움
Python으로 배우는 NLP 피처 엔지니어링

sklearn으로 Bag of Words 모델

corpus = pd.Series([
    'The lion is the king of the jungle',
    'Lions have lifespans of a decade',
    'The lion is an endangered species'
])
Python으로 배우는 NLP 피처 엔지니어링

sklearn으로 Bag of Words 모델

# Import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer

# Create CountVectorizer object vectorizer = CountVectorizer()
# Generate matrix of word vectors bow_matrix = vectorizer.fit_transform(corpus) print(bow_matrix.toarray())
array([[0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 3],
       [0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0],
       [1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1]], dtype=int64)
Python으로 배우는 NLP 피처 엔지니어링

연습해 봅시다!

Python으로 배우는 NLP 피처 엔지니어링

Preparing Video For Download...