본문 바로가기

Study/Introduction to ML with python - 한빛

[Book] 7. 텍스트 데이터 다루기 - (2)

Book Title : Introduction to Machine Learning with Python

- 파이썬 라이브러리를 활용한 머신러닝 -

지은이 : 안드레아스 뮐러, 세라 가이도

옮긴이 : 박해선

출판사 : 한빛미디어

코드 출처

https://github.com/rickiepark/introduction_to_ml_with_python

 

GitHub - rickiepark/introduction_to_ml_with_python: 도서 "[개정판] 파이썬 라이브러리를 활용한 머신 러닝"의

도서 "[개정판] 파이썬 라이브러리를 활용한 머신 러닝"의 주피터 노트북과 코드입니다. Contribute to rickiepark/introduction_to_ml_with_python development by creating an account on GitHub.

github.com


7.7 여러 단어로 만든 BOW(n-gram)

  • BoW 표현 방식은 단어의 순서가 완전히 무시되는 단점이 있는데 BoW 표현 방식을 사용할 때 옆에 있는 두세 개의 토큰을 함께 고려해 문맥을 고려하는 방법이 있음
  • 두 개를 바이그램, 세 개를 트라이그램, 일반적으로 연 혹 된 토큰을 n-gram이라고 함
  • CountVectorrizer와 TfidVectorizerm HashingVecotrizer는 ngram_range 매개변수에 특성으로 고려할 토큰의 범위를 지정할 수 있음
  • 기본값은 최소 길이가1이고 최대 길이가 1인 토큰마다 하나의 특성을 만듦

유니 그램 : 토큰 하나

cv = CountVectorizer(ngram_range=(1, 1)).fit(bards)
print("어휘 사전 크기", len(cv.vocabulary_))
print("어휘 사전 내용", cv.get_feature_names_out())

어휘 사전 크기 13
어휘 사전 내용 ['be' 'but' 'doth' 'fool' 'he' 'himself' 'is' 'knows' 'man' 'the' 'think'
 'to' 'wise']

바이 그램 : 토큰 두 개

cv = CountVectorizer(ngram_range=(2, 2)).fit(bards)
print("어휘 사전 크기", len(cv.vocabulary_))
print("어휘 사전 내용", cv.get_feature_names_out())

어휘 사전 크기 14
어휘 사전 내용 ['be fool' 'but the' 'doth think' 'fool doth' 'he is' 'himself to'
 'is wise' 'knows himself' 'man knows' 'the fool' 'the wise' 'think he'
 'to be' 'wise man']

유니 그램, 바이 그램, 트라이 그램 모두 사용

cv = CountVectorizer(ngram_range=(1, 3)).fit(bards)
print("어휘 사전 크기", len(cv.vocabulary_))
print("어휘 사전 내용", cv.get_feature_names_out())

어휘 사전 크기 39
어휘 사전 내용 ['be' 'be fool' 'but' 'but the' 'but the wise' 'doth' 'doth think'
 'doth think he' 'fool' 'fool doth' 'fool doth think' 'he' 'he is'
 'he is wise' 'himself' 'himself to' 'himself to be' 'is' 'is wise'
 'knows' 'knows himself' 'knows himself to' 'man' 'man knows'
 'man knows himself' 'the' 'the fool' 'the fool doth' 'the wise'
 'the wise man' 'think' 'think he' 'think he is' 'to' 'to be' 'to be fool'
 'wise' 'wise man' 'wise man knows']

 

7.8 고급 토큰화, 어간 추출, 표제어 추출

  • 단순한 벡터 라이져를 통해 특성 추출하는 것보다 뛰어난 텍스트 처리 방법이 있음
  • 표제어 추출과 어간 추출은 정규화(normalization)의 한 형태

어간 추출

  • 각 단어를 그 단어의 어간(stem)으로 표현해서 같은 어간을 가진 모든 단어를 구분
  • 일일이 어미를 찾아 제외하는 규칙 기반 방식

표제어 추출

  • 알려진 단어의 형태 사전을 사용하고 문장에서 단어의 역할을 고려하는 처리 방식
KoNLPy를 사용한 영화 리뷰 분석

Okt_tokenizer

from konlpy.tag import Okt
import pandas as pd

df = pd.read_csv('/content/ratings_train.txt', delimiter ='\t')
df_test = pd.read_csv('/content/ratings_test.txt', delimiter ='\t', keep_default_na =False)
df.head()

X_train, y_train = df['document'].values, df['label']

X_test, y_test = df_test['document'].values, df_test['label'].values

# 분류전 KoNLPy의 Okt 객체 생성
okt_tag = Okt()

def okt_tokenizer(text):
    return okt_tag.morphs(text)


okt_param_grid = {'tfidfvectorizer__min_df' : [3, 5, 7],
                  'tfidfvectorizer__ngram_range' : [(1, 1), (1, 2), (1, 3)],
                  'logisticregression__C' : [0.1, 1, 10]}

okt_pipe = make_pipeline(TfidfVectorizer(tokenizer = okt_tokenizer),
                         LogisticRegression(solver = 'liblinear'))

okt_grid = GridSearchCV(okt_pipe, okt_param_grid, cv =3 )
okt_grid.fit(X_train[0:10], y_train[0:10])


X_test_okt = okt_grid.best_estimator_.named_steps['tfidfvectorizer'].transform(X_test)

score = okt_grid.best_estimator_.named_steps['logisticregresson'].score(X_test_okt, y_test)

Mecab 태그 클래스

from konlpy.tag import Mecab

mecab = Mecab()
def mecab_tokenizer(text):
    return mecab.morphs(text)


mecab_param_grid = {'tfidfvectorizer__min_df' : [3, 5, 7],
                  'tfidfvectorizer__ngram_range' : [(1, 1), (1, 2), (1, 3)],
                  'logisticregression__C' : [0.1, 1, 10]}

mecab_pipe = make_pipeline(TfidfVectorizer(tokenizer = mecab_tokenizer),
                         LogisticRegression(solver = 'liblinear'))

mecab_grid = GridSearchCV(mecab_pipe, mecab_param_grid, cv =3 )
mecab_grid.fit(X_train[0:10], y_train[0:10])

X_test_mecab = mecab_grid.best_estimator_.named_steps['tfidfvectorizer'].transform(X_test)

score = mecab_grid.best_estimator_.named_steps['logisticregresson'].score(X_test_okt, y_test)

 

  • 결론은 Mecab을 사용했을 때가 조금 더 점수가 잘 나왔음
  • 오래 걸려서 중간에 멈춤