본문 바로가기

Project/DACON 청와대 청원 분류

Colab에서 soynlp로 토큰화(tokenizing)하고 konlpy와 비교

Konlpy의 okt, mecab을 이용해서 형태소분석을 한 후 쉽고 간편하게 토큰화를 할 수 있다. 더 좋은 토크나이저를 찾아 다니다가 유툽에서 soynlp를 발견 Colab에서 적용해보았다. 사용법은 soynlp 깃헙레포에 자세히 나와있다.

 

 

lovit/soynlp

한국어 자연어처리를 위한 파이썬 라이브러리입니다. 단어 추출/ 토크나이저 / 품사판별/ 전처리의 기능을 제공합니다. - lovit/soynlp

github.com

soynlp로 토큰화(tokenizing)하기

Tokenizer 정의

명사분석기의 noun score과 cohesion score를 함께 이용해서, L part의 단어 분석을 하면, 나머지 부분은 자연스레 R part가 된다. ex) '밥을' → '밥'(L part), '을'(R part)

input은 말뭉치를 넣어주면 된다. list형태로 넣어주면 된다. 나는 DataFrame 에서 text부분만 떼어와서 list로 변환해서 넣었다. input예시는 아래와 같다. ex) sentences = ['안녕 나는 대천재야', '점심시간 왜이렇게 안오냐']

넣어준 말뭉치를 토대로 tokenizer가 정의되게 된다.

 

from soynlp.noun import LRNounExtractor
from soynlp.word import WordExtractor
from soynlp.tokenizer import LTokenizer

noun_extractor = LRNounExtractor()
nouns = noun_extractor.train_extract(list(train['clear_text'])) # list of str like


word_extractor = WordExtractor(
    min_frequency=50, # example
    min_cohesion_forward=0.05,
    min_right_branching_entropy=0.0
)

word_extractor.train(list(train['clear_text']))
words = word_extractor.extract()

cohesion_score = {word:score.cohesion_forward for word, score in words.items()}

noun_scores = {noun:score.score for noun, score in nouns.items()}
combined_scores = {noun:score + cohesion_score.get(noun, 0)
    for noun, score in noun_scores.items()}
combined_scores.update(
    {subword:cohesion for subword, cohesion in cohesion_score.items()
    if not (subword in combined_scores)}
)

tokenizer = LTokenizer(scores=combined_scores)

 

결과창

Tokenizing 하기

tokenizer가 생성되었다면, 이를 이용해서 tokenizing을 할 수 있다. 여기서는 input으로 한 문장만 넣어줘야한다. list형식으로 되어있던 input중 첫번째 문장만 골라서 tokenizing을 해봤다. str형태로 넣어줘야 분석이 되기 때문에 str을 씌워줬다.

 

train_list=list(train['clear_text'])
print(str(train_list[0]))
print(tokenizer.tokenize(str(train_list[0])))

 

결과창

soynlp 토큰화 vs Konlpy okt 토큰화

konlpy에 있는 okt를 통해 형태소 분석 후 tokenizing한 것과 비교를 해봤다. 더 좋아졌으면 하고 soynlp를 사용했는데 okt가 좀 더 그럴듯하게 나오는 모습을 보였다.

 

 

원래 문장 중 일부

 

신혼부부위한 주택정책 보다 보육시설 늘려주세요 국민세금으로 일부를 위한 정책펴지

 

soynlp로 tokenizing

 

'신혼', '부부위한', '주택', '정책', '보다', '보육시설', '늘려주세요', '국민', '세금으로', '일부', '를', '위한', '정책', '펴지'

 

konlp okt로 tokenizing

 

'신혼부부', '위', '주택', '정책', '보다', '보육', '시설', '늘리다', '국민', '세금', '일부', '위', '정책','펴다'

 

 

이외에도 빙상연맹을 sonlp는 '빙상연' '맹' / okt는 '빙상' '연맹'으로 분석하는 것을 확인했다. 일단 나는 okt, mecab을 통해서 분석을 진행하는 것으로 했다. 초심자라 아직 잘 쓸 줄 몰라서 그런 걸지도? 좀 더 공부해봐야겠다.

 

(+ konlpy okt를 이용해서 tokenizing하기)

 

train = train.dropna(how = 'any')
train['data'] = train['data'].str.replace("[^ㄱ-ㅎㅏ-ㅣ가-힣 ]","")
test['data'] = test['data'].str.replace("[^ㄱ-ㅎㅏ-ㅣ가-힣 ]","")
stopwords = ['의','가','이','은','들','는','좀','잘','걍','과','도','를','으로','자','에','와','한','하다','을']

for sentence,i in zip(train['data'],tqdm(range(len(train['data'])))) :
      temp_X = []
      temp_X = okt.morphs(sentence, stem=True)
      temp_X = [word for word in temp_X if not word in stopwords]
      X_train.append(temp_X)

for sentence in test['data']:
      temp_X = []
      temp_X = okt.morphs(sentence, stem=True)
      temp_X = [word for word in temp_X if not word in stopwords]
      X_test.append(temp_X)

'Project > DACON 청와대 청원 분류' 카테고리의 다른 글

Colab에서 konlpy와 mecab 설치하기  (8) 2021.02.03