모델링을 위한 텍스트 준비

R로 배우는 자연어 처리 입문

Kasey Jones

Research Data Scientist

R의 지도학습: 분류

R로 배우는 자연어 처리 입문

분류 모델링

  • 지도학습 접근
  • 관측치를 범주로 분류
    • 승/패
    • 위험, 친근, 무관심
  • 다양한 기법 사용 가능:
    • 로지스틱 회귀
    • 의사결정나무/랜덤 포레스트/XGBoost
    • 신경망
R로 배우는 자연어 처리 입문

모델링 기본 단계

  1. 데이터 정제/준비
  2. 학습/테스트 데이터셋 생성
  3. 학습 데이터로 모델 학습
  4. 테스트 데이터 정확도 보고
R로 배우는 자연어 처리 입문

등장인물 인식

Napoloeon Napoleon

Boxer Boxer

1 https://comicvine.gamespot.com/napoleon/4005-141035/ 2 https://hero.fandom.com/wiki/Boxer_(Animal_Farm)
R로 배우는 자연어 처리 입문

동물 문장

# 문장 만들기
sentences <- animal_farm %>%
  unnest_tokens(output = "sentence", token = "sentences", input = text_column)
# 동물별로 문장 라벨링
sentences$boxer <- grepl('boxer', sentences$sentence)
sentences$napoleon <- grepl('napoleon', sentences$sentence)
# 동물 이름 치환
sentences$sentence <- gsub("boxer", "animal X", sentences$sentence)
sentences$sentence <- gsub("napoleon", "animal X", sentences$sentence)
animal_sentences <- sentences[sentences$boxer + sentences$napoleon == 1, ]
R로 배우는 자연어 처리 입문

문장 계속

animal_sentences$Name <-
    as.factor(ifelse(animal_sentences$boxer, "boxer", "napoleon"))
# 각 75개
animal_sentences <- 
  rbind(animal_sentences[animal_sentences$Name == "boxer", ][c(1:75), ],
        animal_sentences[animal_sentences$Name == "napoleon", ][c(1:75), ])
animal_sentences$sentence_id <- c(1:dim(animal_sentences)[1])
R로 배우는 자연어 처리 입문

데이터 준비

library(tm); library(tidytext)
library(dplyr); library(SnowballC)
animal_tokens <- animal_sentences %>%
  unnest_tokens(output = "word", token = "words", input = sentence) %>%
  anti_join(stop_words) %>%
  mutate(word = wordStem(word))
R로 배우는 자연어 처리 입문

준비 계속

animal_matrix <- animal_tokens %>%
  count(sentence_id, word) %>%
  cast_dtm(document = sentence_id, term = word,
           value = n, weighting = tm::weightTfIdf)
animal_matrix
<<DocumentTermMatrix (documents: 150, terms: 694)>>
Non-/sparse entries: 1235/102865
Sparsity           : 99%
Maximal term length: 17
Weighting          : term frequency - inverse document frequency
R로 배우는 자연어 처리 입문

희소 용어 제거

  • 비공백(1,235) + 공백(102,865)
  • 행렬 크기 150 × 694
  • 희소도: 102,865 / 104,100 (99%)

해결: removeSparseTerms()

R로 배우는 자연어 처리 입문

얼마나 희소하면 너무 희소한가?

removeSparseTerms(animal_matrix, sparse = .90)
<<DocumentTermMatrix (documents: 150, terms: 4)>>
Non-/sparse entries: 207/393
Sparsity           : 66%
removeSparseTerms(animal_matrix, sparse = .99)
removeSparseTerms(animal_matrix, sparse = .99)
<<DocumentTermMatrix (documents: 150, terms: 172)>>
Non-/sparse entries: 713/25087
Sparsity           : 97%
R로 배우는 자연어 처리 입문

Ayo berlatih!

R로 배우는 자연어 처리 입문

Preparing Video For Download...