BoW 나이브 베이즈 분류기 구축

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

Rounak Banik

Data Scientist

스팸 필터링

message label
WINNER!! As a valued network customer you have been selected to receive a $900 prize reward! To claim call 09061701461 spam
Ah, work. I vaguely remember that. What does it feel like? ham
Python으로 배우는 NLP 피처 엔지니어링

단계

  1. 텍스트 전처리
  2. BoW(가방-단어) 모델(표현) 구축
  3. 기계 학습
Python으로 배우는 NLP 피처 엔지니어링

CountVectorizer로 텍스트 전처리

CountVectorizer 인자

  • lowercase: False, True
  • strip_accents: 'unciode', 'ascii', None
  • stop_words: 'english', list, None
  • token_pattern: regex
  • tokenizer: function
Python으로 배우는 NLP 피처 엔지니어링

BoW 모델 구축

# Import CountVectorizer
from sklearn.feature_extraction.text import CountVectorizer

# CountVectorizer 객체 생성 vectorizer = CountVectorizer(strip_accents='ascii', stop_words='english', lowercase=False)
# train_test_split 불러오기 from sklearn.model_selection import train_test_split # 학습/테스트 세트 분할 X_train, X_test, y_train, y_test = train_test_split(df['message'], df['label'], test_size=0.25)
Python으로 배우는 NLP 피처 엔지니어링

BoW 모델 구축

...
...
# 학습용 BoW 벡터 생성
X_train_bow = vectorizer.fit_transform(X_train)

# 테스트용 BoW 벡터 생성 X_test_bow = vectorizer.transform(X_test)
Python으로 배우는 NLP 피처 엔지니어링

나이브 베이즈 분류기 학습

# Import MultinomialNB
from sklearn.naive_bayes import MultinomialNB

# MultinomialNB 객체 생성 clf = MultinomialNB()
# clf 학습 clf.fit(X_train_bow, y_train)
# 테스트 정확도 계산 accuracy = clf.score(X_test_bow, y_test) print(accuracy)
0.760051
Python으로 배우는 NLP 피처 엔지니어링

연습해 봅시다!

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

Preparing Video For Download...