본문 바로가기
R

29. 비정형 데이터마이닝 - 텍스트마이닝

by #Glacier 2018. 11. 21.
반응형

안녕하셍요. 오늘은 비정형 데이터마이닝을 공부해보도록 하겠습니다.


# 참고.

빅데이터 중 비정형 데이터인 로그성 데이터는 - R의 parsing 기능을 이용하여 입수가 가능하며, 

기업의 내부 서술형 데이터나 소셜 미디어 등에서 입수하는 텍스트 형식의 정보를 분석하는 데는 텍스트마이닝이 필요하다. 

또 다른 비정형 형태인 소셜 미디어나 기타 관계로 표현되는 데이터는 소셜 네트워크 분석을 통해 수행할 수 있다. (SNA분석)


<텍스트마이닝>


- 텍스트 데이터에서의 단어 패턴을 이용해서 내용을 파악하거나 분류 및 핵심단어 주제를 추출하는 경우 

  연관된 단어나 빈번하게 나오는 단어와, 부정/긍정 단어에 따른 기업이나 제품, 브랜드를 평가하는데 활용한다. 

  텍스트 마이닝에서는 분석 가능한 document term matrix를 만들기 전에

  불필요하거나 빈도가 매우 낮은 데이터를 전처리 하는 과정이 필요하다.


1. 기능


문서 요약(Document Summarization), 문서 분류(Document Classification), 문서 군집화(Document Clustering), 문서 특성 추출(Feature Extraction)


2. 개념

(1) Corpus(Corpora) : 문자를 포함한 문서들의 class(S3 class)

(2) VCorpus(Volatile Corpora) : 문서를 Corpus class로 만들어 주는 함수로서 결과는 메모리에 저장되어, 현재 구동 중인 R object에만 영향을 미친다.

(3) PCorpus(Permanent Corpora) : Vcorpus와 달리 문서를 Corpus class로 만들어 database화 해주는 함수.


3. tm패키지를 이용한 분석 사례


1) tm 패키지 내의 Data Set

-(1) acq : Reuters-21578 data set으로부터 추출된 기업 인수 관련 기사 50개

-(2) crude : Reuters-21578 data set으로부터 추출된 원유 관련 기사 20개


2) VCorpus로 문서 읽기


-(1) 문서 위치 지정


install.packages("tm")
library(tm)

install.packages("XML")
library(XML)
reut21578 <- system.file("texts", "crude", package="tm")
reut21578


[1] "C:/Users/user/Documents/R/win-library/3.3/tm/texts/crude"


#이렇게 C드라이브 내에 무언가가 생겼습니다.


-(2) 문서 읽기


# VCorpus 함수를 이용해 문서를 읽고, 이를 crudeCorp에 저장. 첫 번째 읽은 문서를 보는 방법은 crudeCorp[[1]]와 inspect(crudeCorp[1])이 있다.

   후자는 Metadata를 포함하고 있으며, 파일 reut-00001.xml을 읽은 결과


crudeCorp<- VCorpus(DirSource(reut21578), readerControl=list(reader = readReut21578XMLasPlain))

crudeCorp


<<VCorpus>>
Metadata:  corpus specific: 0, document level (indexed): 0
Content:  documents: 20


crudeCorp[[1]]


<<PlainTextDocument>>
Metadata:  16
Content:  chars: 527


inspect(crudeCorp[1])


<<VCorpus>>
Metadata:  corpus specific: 0, document level (indexed): 0
Content:  documents: 1

[[1]]
<<PlainTextDocument>>
Metadata:  16
Content:  chars: 527


-(3) 문서 변형 - 1단계 : 공백지우기


#중복된 공백 지우기(Eliminating Extra Whitespace) : 문서의 중간에 2개 이상의 공백을 하나의 공백으로 바꾸는 함수.


crudeCorp <- tm_map(crudeCorp, stripWhitespace)


<<VCorpus>>
Metadata:  corpus specific: 0, document level (indexed): 0
Content:  documents: 1

[[1]]
<<PlainTextDocument>>
Metadata:  16
Content:  chars: 514


# 이렇게 중복된 공백을 지우게 되면, 문서의 줄 바꾸기 등 큰 공백들이 다 좁혀집니다.


-(3) 문서변형 - 2단계 : 소문자로 변형하기(Convert to Lower Case) : 문서의 모든 글자를 소문자화


crudeCorp<-tm_map(crudeCorp, tolower)

inspect(crudeCorp[1])


<<VCorpus>>
Metadata:  corpus specific: 0, document level (indexed): 0
Content:  documents: 1

[[1]]
[1] diamond shamrock corp said that effective today it had cut its contract prices for crude oil by 1.50 dlrs a barrel. the reduction brings its posted price for west texas intermediate to 16.00 dlrs a barrel, the copany said. "the price reduction today was made in the light of falling oil product prices and a weak crude oil market," a company spokeswoman said. diamond is the latest in a line of u.s. oil companies that have cut its contract, or posted, prices over the last two days citing weak oil markets. reuter


# 자 이렇게 모든 글자가 소문자화 되었고, 공백도 다 줄어들은 모습을 볼 수 있죠?


-(3) 문서변형 - 3단계 : 기능어 제거 (Remove Stopwards)

crudeCorp<-tm_map(crudeCorp, removeWords, stopwords("english"))

inspect(crudeCorp[1])


<<VCorpus>>
Metadata:  corpus specific: 0, document level (indexed): 0
Content:  documents: 1

[[1]]
[1] diamond shamrock corp said  effective today   cut  contract prices  crude oil  1.50 dlrs  barrel.  reduction brings  posted price  west texas intermediate  16.00 dlrs  barrel,  copany said. " price reduction today  made   light  falling oil product prices   weak crude oil market,"  company spokeswoman said. diamond   latest   line  u.s. oil companies   cut  contract,  posted, prices   last two days citing weak oil markets. reuter


# 기능어가 제거되었습니다.


-(4) 단어-문서 행렬 생성(Creating Term-Document Matrices)

 # 텍스트마이닝의 일반적인 접근 방법 : 각 문서에 단어들이 얼마나 많이 쓰였는지를 단어-문서행렬로 구조화

 # TermDocumentMatrix와 DocumentTermMatrix를 이용해 생성. 둘의 차이는 행과 열에 어느 것을 놓을지에 따라 달라짐.

crudeDtm <- TermDocumentMatrix(crudeCorp, control=list(removePunctuation=T))

<<TermDocumentMatrix (terms: 1068, documents: 20)>>
Non-/sparse entries: 2070/19290
Sparsity           : 90%
Maximal term length: 16
Weighting          : term frequency (tf)


#crudeDtm 을 쳐보면 단어-문서행렬로 생성된 것을 볼 수 있습니다. 너무 길어서 여기엔 안쓸게요..ㅎㅎ;


-(5) 단어-문서 행렬에 대한 조작

 # 문서에서 10회 이상의 언급된 단어를 찾기 위한 함수 : findFreqTerms() : findFreqTerms(crudeDtm, 10)

 # 특정 단어와 상관도가 0.8 이상인 단어를 찾아주는 함수 : findAssocs() : findAssocs(crudeDtm, "opec", 0.8)

 # 비어 있는 정도(Sparsity)가 40% 이상인 단어를 없애 주는 함수 : removeSparseTerms() : inspect(removeSparseTerms(crudeDtm, 0.5))


findFreqTerms(crudeDtm, 10)


 [1] "about"      "and"        "are"        "barrel"     "barrels"   
 [6] "bpd"        "but"        "crude"      "dlrs"       "for"       
[11] "from"       "government" "has"        "industry"   "its"       
[16] "kuwait"     "last"       "market"     "meeting"    "minister"  
[21] "mln"        "new"        "not"        "official"   "oil"       
[26] "one"        "opec"       "pct"        "price"      "prices"    
[31] "production" "reuter"     "said"       "saudi"      "sheikh"    
[36] "that"       "the"        "they"       "this"       "was"       
[41] "were"       "will"       "with"       "world"      "would" 


findAssocs(crudeDtm, "opec", 0.8)

$opec
       158   analysts     buyers  emergency        oil       they    meeting 
      0.88       0.87       0.87       0.87       0.87       0.84       0.83 
production      named 
      0.82       0.81


inspect(removeSparseTerms(crudeDtm, 0.5))


<<TermDocumentMatrix (terms: 13, documents: 20)>>
Non-/sparse entries: 203/57
Sparsity           : 22%
Maximal term length: 6
Weighting          : term frequency (tf)

        Docs
Terms    127 144 191 194 211 236 237 242 246 248 273 349 352 353 368 489 502
  and      1   9   0   1   2   7  11   3   9   6   5   2   3   1   1   5   6
  dlrs     2   0   1   2   2   2   1   0   0   4   2   0   0   0   0   1   1
  for      2   5   2   2   2   4   4   1   6   2   4   0   0   2   0   4   5
  its      3   6   1   1   1   8   3   0   3   2   0   0   2   2   1   2   2
  last     1   1   1   1   0   4   3   0   2   1   7   1   1   1   0   0   0
  oil      5  12   2   1   1   7   3   3   5   9   5   4   5   4   3   4   5
  one      0   1   0   1   0   1   1   1   0   1   1   0   0   1   0   2   2
  prices   3   5   0   0   0   5   1   2   1   9   5   1   5   2   0   2   2
  reuter   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1
  said     3  11   1   1   3  10   1   3   5   7   8   1   2   1   3   2   2
  that     2  10   0   0   2   4   1   0   2   2   0   0   0   3   0   1   1
  the      6  19   4   4   8  15  30   6  18  27  21   5   7   4  11   8  13
  was      1   1   0   1   0   7   2   1   2   4   1   0   1   3   2   0   0
        Docs
Terms    543 704 708
  and      0   5   0
  dlrs     5   0   0
  for      3   4   0
  its      2   1   0
  last     0   0   0
  oil      3   3   1
  one      1   4   0
  prices   2   3   0
  reuter   1   1   1
  said     4   4   1
  that     0   3   0
  the      5  21   0
  was      1   0   1
 

#요런 식으로 할 수 있습니다.


-(6) 단어 사전 (Dictionary)

# 단어 사전은 텍스트 마이닝의 목적에 맞게 만들어진 단어들의 모임. 이는 DocumentTerm-Matrix()함수에 argument로 투입되어 문서에 언급된 전체 단어 대신,

   사전에 주어진 단어로 문서-단어 행렬(Term-Document Matrix)을 만들도록

비정형데이터마이닝-텍스트마이닝.R

할 수 있음. 이를 통해 불필요한 단어에 대한 행렬 수를 줄여 문서-단어 행렬을

   상당히 가볍게 만들 수 있습니다.


crudeDctnry = c("prices", "crude", "oil")

inspect(DocumentTermMatrix(crudeCorp, list(dictionary=crudeDctnry)))


<<DocumentTermMatrix (documents: 20, terms: 3)>>
Non-/sparse entries: 41/19
Sparsity           : 32%
Maximal term length: 6
Weighting          : term frequency (tf)

     Terms
Docs  crude oil prices
  127     2   5      3
  144     0  11      3
  191     2   2      0
  194     3   1      0
  211     0   1      0
  236     1   7      2
  237     0   3      0
  242     0   3      1
  246     0   4      0
  248     0   9      7
  273     5   5      4
  349     2   3      0
  352     0   5      4
  353     2   4      1
  368     0   3      0
  489     0   4      2
  502     0   4      2
  543     2   2      2
  704     0   3      2
  708     1   1      0


# 요런 식으로 가능하죠.


# 오늘은 일단 텍스트마이닝을 하기 위한 데이터 정제과정을 알아봤는데요. 

  이 과정이 중요합니다. 예를들어서, 데이터를 수집할 때. 통일이란 단어를 가지고 긍정과 부정의 인식을 끌어온다고 한다면. 

  천하통일, 세계통일, 통일교 이런 것들은 거르고 수집해야 한다는 것입니다. 그리고 이러한 데이터를 수집해 왔다면, 

  엄청나게 많은 글자들이 모입니다. 그렇다면 이러한 많은 글자들의 집합을 가볍게 만들고 정확하게 만들기 위해

  점(.)을 지우고, 공백을 지우고, 필요없는 의성어 같은 것을 지우는 과정들이 필요한 것입니다. 

  이러한 과정들을 간단하게 공부해봤구여. 오늘도 코드첨부할꼐요.

반응형