본문 바로가기
R

28. 정형 데이터마이닝 - 연관성 분석#2 (Association Analysis)

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

안녕하세요. 오랜만입니다..

오늘은 연관성 분석의 2번째 파트, 순차연관성 분석에 대해서 공부해 볼게여


install.packages("arulesSequences")
library(arulesSequences)
data(zaki)

# arulesSequences라는 패키지를 이용하고 zaki라는 데이터를 사용합니다.

arulesSequences가 무슨 패키지일까 쳐봤는데,

Add-on for arules to handle and mine frequent sequences. Provides interfaces to the C++ implementation

of cSPADE by Mohammed J. Zaki. 라고 나와있네요.


#빈번한 순서를 좀더 잘 다루기 위한 arules의 추가기능이면서, C++의 원활한 환경을 지원하는 건데, 

 cSPADE의 Mohammed J.Zaki.에 의해서 만들어졌나 봐요.

 그래서 데이터도 Zaki인가 봅니다.


#그렇다면 Zaki데이터는 뭘까요

The data set contains the sequential database described in the paper by M. J. Zaki for illustration of the concepts  of sequence  mining. sequenceID and eventID denote the sequence and event (time) identifiers of the transactions.


#시퀀스 마이닝을위해 자키에 의해 만들어진 순서적인? 데이터셋이라고 하네요.

sequenceID와 eventID는 이벤트(시간) 식별요인의 상호작용과 순서를 알려주는거래요.

(못난이 영어..)


str(zaki)


Formal class 'transactions' [package "arules"] with 3 slots
  ..@ data       :Formal class 'ngCMatrix' [package "Matrix"] with 5 slots
  .. .. ..@ i       : int [1:27] 2 3 0 1 2 0 1 5 0 2 ...
  .. .. ..@ p       : int [1:11] 0 2 5 8 12 15 16 19 22 24 ...
  .. .. ..@ Dim     : int [1:2] 8 10
  .. .. ..@ Dimnames:List of 2
  .. .. .. ..$ : NULL
  .. .. .. ..$ : NULL
  .. .. ..@ factors : list()
  ..@ itemInfo   :'data.frame': 8 obs. of  1 variable:
  .. ..$ labels: chr [1:8] "A" "B" "C" "D" ...
  ..@ itemsetInfo:'data.frame': 10 obs. of  3 variables:
  .. ..$ sequenceID: int [1:10] 1 1 1 1 2 2 3 4 4 4
  .. ..$ eventID   : int [1:10] 10 15 20 25 15 20 10 10 20 25
  .. ..$ SIZE      : int [1:10] 2 3 3 4 3 1 3 3 2 3
 

#zaki는 저런식으로 되어있고. 뭔가 차원이 주어져있나봅니다. (Dim) ? 좀 더 탐색해볼까요??


summary(zaki)


transactions as itemMatrix in sparse format with
 10 rows (elements/itemsets/transactions) and
 8 columns (items) and a density of 0.3375

most frequent items:
      A       B       F       C       D (Other) 
      6       5       5       3       3       5

element (itemset/transaction) length distribution:
sizes
1 2 3 4 
1 2 6 1

   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
   1.00    2.25    3.00    2.70    3.00    4.00

includes extended item information - examples:
  labels
1      A
2      B
3      C

includes extended transaction information - examples:
  sequenceID eventID SIZE
1          1      10    2
2          1      15    3
3          1      20    3


# 음 뭔가 알거 같기도 하고? 앞서 연관성분석에서 사용했던 inspect를 사용해볼까요?


inspect(head(zaki))


  items     sequenceID eventID SIZE
1 {C,D}            1           10      2   
2 {A,B,C}         1           15      3   
3 {A,B,F}         1          20      3   
4 {A,C,D,F}       1          25      4   
5 {A,B,F}         2          15      3   
6 {E}              2          20      1


#이렇게 보니까 아이템의 조합과 sequenceID, eventID, SIZE가 나오네요,^^

  어떤 판매물건들의 조합과 그런 것들의 정보로서 이제 조금씩 와닿기 시작합니다..


#이 zaki를 dataframe 형태로 나타내보죠..


as(zaki, "data.frame")


       items sequenceID eventID SIZE
1      {C,D}           1         10      2
2    {A,B,C}          1         15      3
3    {A,B,F}          1         20     3
4  {A,C,D,F}          1         25     4
5    {A,B,F}          2         15     3
6        {E}           2         20     1
7    {A,B,F}          3         10     3
8    {D,G,H}          4         10     3
9      {B,F}           4         20     2
10   {A,G,H}          4         25     3


# 이제 cspade function을 이용하여 순차연관규칙을 도출해봅니다. 보니까 cSPADE의 Mohammed Zaki랬죠? 그래서 cspade function인가봐요.

  자키 씨가 만든 기능인가봐요~

# 여기서 parameter는 명명된 구성요소에 따른 어떠한 값을 갖는 목적물, 즉 support = 0.4에 해당하는 값을 뽑는가봐요.

   verbose=TRUE? 는 장황하게 해달라나 봅니다.


z_arules_Seq <- cspade(zaki, parameter = list(support = 0.4), control = list(verbose=TRUE)



parameter specification:
support : 0.4
maxsize :  10
maxlen  :  10

algorithmic control:
bfstype  : FALSE
verbose  :  TRUE
summary  : FALSE
tidLists : FALSE

preprocessing ... 1 partition(s), 0 MB [0.2s]
mining transactions ... 0 MB [0.1s]
reading sequences ... [0s]

total elapsed time: 0.3s


#요렇게 하니까 먼가가 실행되는 컴퓨터의 소리와 함께.. 지지도 0.4에 최대사이즈 10, 최대길이 10, 알고리즈믹 컨트롤에서는 verbose = TRUE라고 했었죠.

 쭉 뭔가 실행되고, 0.3s가 걸렸대요. 그럼 결과물을 한 번 볼까요


str(z_arules_Seq)


Formal class 'sequences' [package "arulesSequences"] with 6 slots
  ..@ elements    :Formal class 'itemsets' [package "arules"] with 4 slots
  .. .. ..@ items   :Formal class 'itemMatrix' [package "arules"] with 3 slots
  .. .. .. .. ..@ data       :Formal class 'ngCMatrix' [package "Matrix"] with 5 slots
  .. .. .. .. .. .. ..@ i       : int [1:13] 0 1 2 3 0 3 1 3 0 1 ...
  .. .. .. .. .. .. ..@ p       : int [1:9] 0 1 2 3 4 6 8 11 13
  .. .. .. .. .. .. ..@ Dim     : int [1:2] 4 8
  .. .. .. .. .. .. ..@ Dimnames:List of 2
  .. .. .. .. .. .. .. ..$ : NULL
  .. .. .. .. .. .. .. ..$ : NULL
  .. .. .. .. .. .. ..@ factors : list()
  .. .. .. .. ..@ itemInfo   :'data.frame':     4 obs. of  1 variable:
  .. .. .. .. .. ..$ labels: chr [1:4] "A" "B" "D" "F"
  .. .. .. .. ..@ itemsetInfo:'data.frame':     0 obs. of  0 variables
  .. .. ..@ tidLists: NULL
  .. .. ..@ quality :'data.frame':      8 obs. of  1 variable:
  .. .. .. ..$ support: num [1:8] 1 1 0.5 1 0.75 1 0.75 0.75
  .. .. ..@ info    : list()
  ..@ data        :Formal class 'sgCMatrix' [package "arulesSequences"] with 5 slots
  .. .. ..@ p       : int [1:19] 0 1 2 3 4 5 6 8 10 11 ...
  .. .. ..@ i       : int [1:31] 0 1 2 3 4 5 2 3 2 5 ...
  .. .. ..@ Dim     : int [1:2] 8 18
  .. .. ..@ Dimnames:List of 2
  .. .. .. ..$ : NULL
  .. .. .. ..$ : NULL
  .. .. ..@ factors : list()
  ..@ sequenceInfo:'data.frame':        0 obs. of  0 variables
  ..@ tidLists    : NULL
  ..@ quality     :'data.frame':        18 obs. of  1 variable:
  .. ..$ support: num [1:18] 1 1 0.5 1 0.75 1 0.5 0.5 0.75 0.75 ...
  ..@ info        :List of 4
  .. ..$ data         : symbol zaki
  .. ..$ ntransactions: int 10
  .. ..$ nsequences   : int 4
  .. ..$ support      : num 0.4


# 정말 뭔가 가득합니다. 머리아파요. 빨리 inspect? 마법의 inspect를 쓰고 싶지만 책에서는 아직 안쓰고 있어요. 정말 설명 한줄 없이

  줄줄줄줄줄줄 써놓기만.;; 제가 이래서 통계분석에 관심은 있어도 수학에 관심은 없나봅니다.


summary(z_aules_Seq)


set of 18 sequences with

most frequent items:
      A       B       F       D (Other) 
     11      10      10       8      28

most frequent elements:
    {A}     {D}     {B}     {F}   {B,F} (Other) 
      8       8       4       4       4       3

element (sequence) size distribution:
sizes
1 2 3 
8 7 3

sequence length distribution:
lengths
1 2 3 4 
4 8 5 1

summary of quality measures:
    support      
 Min.   :0.5000  
 1st Qu.:0.5000  
 Median :0.5000  
 Mean   :0.6528  
 3rd Qu.:0.7500  
 Max.   :1.0000 

includes transaction ID lists: FALSE

mining info:
 data ntransactions nsequences support
 zaki            10          4             0.4


# 가장 빈번한 아이템, 요소 들이 나오고 distribution이 나오네요. zaki내의 상호작용은 10가지, 순서는 4가지 ? 지지도는 0.4로 지정한 값에서 나온 값들이에요.


as(z_arules_Seq, "data.frame")


          sequence support
1            <{A}>    1.00
2            <{B}>    1.00
3            <{D}>    0.50
4            <{F}>    1.00
5          <{A,F}>    0.75
6          <{B,F}>    1.00
7        <{D},{F}>    0.50
8      <{D},{B,F}>    0.50
9        <{A,B,F}>    0.75
10         <{A,B}>    0.75
11       <{D},{B}>    0.50
12       <{B},{A}>    0.50
13       <{D},{A}>    0.50
14       <{F},{A}>    0.50
15   <{D},{F},{A}>    0.50
16     <{B,F},{A}>    0.50
17 <{D},{B,F},{A}>    0.50
18   <{D},{B},{A}>    0.50


inspect(zaki)


   items     sequenceID eventID SIZE
1  {C,D}      1              10      2   
2  {A,B,C}   1              15      3   
3  {A,B,F}   1              20      3   
4  {A,C,D,F} 1             25      4   
5  {A,B,F}   2             15      3   
6  {E}        2             20      1   
7  {A,B,F}   3             10      3   
8  {D,G,H}   4             10      3   
9  {B,F}     4             20      2   
10 {A,G,H}   4             25      3   


#이렇게 아까처럼 해보니까 나옵니다. 요소들의 조합이요.

  자 이제 해석을 해보면, sequenceID는 고객, eventID는 일정기간의 거래 수입니다.

  즉, 아까 나왔듯이 nsequence = 4 즉, 4명의 고객(Sequence ID)에 대해 일정 기간 동안의 10건(ntranceaction, eventID)의 거래를 분석한 겁니다.

  지지도를 0.4로 지정하였으므로 support가 0.4보다 큰 basket만 남게 됩니다.

  A의 support = 4명(SequenceID 1,2,3,4) / 4명 = 1.00 : 0.4보다 크므로 rules에 포함되었습니다.

  B의 support = 동일

  C의 support = 1명(SequenceID 1) / 4명 = 0.25 : 0.4보다 작으므로 미포함

  이런식으로 쭉 가다가

  A, F 의 support = 3명(Sequence ID 1,2,3) / 4명 = 0.75 : 0.4보다 크므로 포함

  무슨 말인지 이해되죠?  A,F조합이 들어간 것을 산 고객이 1,2,3 이 있는데 총 4명으로 나누는 겁니다@!!

  조금 복잡스럽기도 합니다.. ㅠㅠㅠ 저도 완벽하게 이해는 못하겠어요. 설명이 워낙 부실하다보니. 좀 더 좋은 의견, 해석을 가지신 분이 나타나길..

 

  요런 것들을 활용하는 방안은 기준 이상의 support를 만족하는 순차연관규칙에 대해 순차적으로 구매 증진을 위한 할인 쿠폰 등을 발행하는 겁니다!.


# 이제 arulesViz 패키지를 이용해 시각화를 해볼께요.


install.packages("arulesViz")
library(arulesViz)
data(Groceries)
G_arulesViz <- apriori(Groceries, parameter=list(support = 0.005, confidence=0.3))


Apriori

Parameter specification:
 confidence minval smax arem  aval originalSupport support minlen maxlen
        0.3       0.1    1    none FALSE            TRUE    0.005      1     10
 target   ext
  rules FALSE

Algorithmic control:
 filter tree heap memopt load sort verbose
    0.1 TRUE TRUE  FALSE TRUE    2    TRUE

Absolute minimum support count: 49

set item appearances ...[0 item(s)] done [0.00s].
set transactions ...[169 item(s), 9835 transaction(s)] done [0.00s].
sorting and recoding items ... [120 item(s)] done [0.00s].
creating transaction tree ... done [0.01s].
checking subsets of size 1 2 3 4 done [0.00s].
writing ... [482 rule(s)] done [0.00s].
creating S4 object  ... done [0.00s].


 inspect(head(G_arulesViz, by="confidence"))

         lhs                     rhs              support confidence     lift
1 {tropical fruit,                                                    
   root vegetables,                                                   
   yogurt}             => {whole milk}   0.005693950  0.7000000 2.739554
2 {pip fruit,                                                         
   root vegetables,                                                   
   other vegetables}   => {whole milk} 0.005490595  0.6750000 2.641713
3 {butter,                                                            
   whipped/sour cream} => {whole milk} 0.006710727  0.6600000 2.583008
4 {pip fruit,                                                         
   whipped/sour cream} => {whole milk} 0.005998983  0.6483516 2.537421
5 {butter,                                                            
   yogurt}             => {whole milk} 0.009354347  0.6388889 2.500387
6 {root vegetables,                                                   
   butter}             => {whole milk} 0.008235892  0.6377953 2.496107


# 오호 이렇게 상품조합별로 신뢰도 지지도 향상도가 나옵니다.

   이것을 plot해봅니다.


plot(G_arulesViz)



# 지지도와 신뢰도를 두고 저렇게 플랏으로 보기 쉽~게나오죠 리프트는 색깔로 구분되고요!

  482개의 규칙들을 다 찍어내서 보기 쉽~게보여줍니다.


# interactive Mode와 축 바꾸기

 plot(G_arulesViz, interactive=TRUE)



 

Interactive mode.
Select a region with two clicks!


# 자 이제 이렇게 나왔는데요~ 하단의 목록을 좀 더 알아보겠습니다.


inspect   :  화면에서 두 번 클릭으로 박스를 만들고 inspect를 클릭하면, 박스 내 존재하는 observation의 list를 보여줍니다 (우와..)

filter      : 그래프의 우측 shading으로 표시된 항목(lift) 에 대해 filter 적용. filter를 클릭한 후, lift의 filter 대상을 클릭하면

              그 값의 이상에 해당하는 항목만 보여줌

zoom in   : 그래프 내의 observation에 대해 두 번 클릭으로 박스를 지정하고, zoom in을 클릭하면 해당 부분만을 나타내도록 zoom in

zoom out : zoom in 혹은 filter를 적용하기 바로 전 단계로 zoom out

ent         : interactive 그래프 모드의 종료


# 정말 신기방기하죠...ㅠㅠ 눈물날지경


# 참고 : 모델 subset :

G_arulesViz_sub1 <- G_arulesViz[quality(G_arulesViz)$confidence > 0.5 ]

G_arulesViz_sub1

## set of 113 rules


# 모델 시각화 1 : 규칙의 matrix화, lift만을 measure로 하여 시각화

  - 도출되 규칙에 대해 성과의 측면이 아닌, item 측면에서 어느 item이 효과가 있는지를 시각화함.


plot(G_arulesViz_sub1, method="matrix", measure="lift")




# 모델 시각화 2 : 규칙의 matrix화, lift와 confidence를 measure로 하여 시각화


plot(G_arulesViz_sub1, method="matrix", measure=c("lift", "confidence"))




# 요렇게도 나오는데, 이건 조금 보기 힘든 감이 없지않아 큽니다....(저는요.)


# 모델시각화 3 : 규칙의 3차원 matrix화, lift를 한 축으로 하여 시각화

plot(G_arulesViz_sub1, method="matrix3D", measure="lift")




# 모델시각화 4 :  모델시각화 그룹옵션으로 시각화

plot(G_arulesViz_sub1, method="grouped")





# 모델시각화 5 : lift 상위 10개에 대해 그래프 옵션으로 시각화

G_arulesViz_sub2 <- head(sort(G_arulesViz, by= "lift") , 10)

plot(G_arulesViz_sub2, method="graph", control = list(type="items"))



# 이게 좀 더 선명하게 줄이 나와야 하는데, 이 그래픽이 뭔가 다른 패키지가 필요할거에요..아마도.? 전 잘 모르겟네요..  

 

연관성분석+파트2.R

기억이 희미해져서..

# 근데 정말 다양한방법들이 있죠? 그래픽 시각화도 정말 어떻게 나타내느냐에 따라 보기 좋고 안좋고가 명확하게 갈리는거 같아요.

# 오늘 포스팅은 넘나 길었네요. ㅋㅋ 벌서 12시야..ㅠㅠ;;

다음 시간에는 비정형 데이터마이닝에대해 알아볼게요. 저도 오늘 한 연관성분석 파트는 더 많이 봐야할 것 가타요!

여러분들 한 번씩 해보시라고 R코드도 파일로 넣어놨어요. 헤 ㅋ 굿밤

반응형