레미제라블 3D 인물 네트워크

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 3D 시각화 패키지 설치
install.packages("networkD3")
install.packages("dplyr")
 
library(networkD3)
library(dplyr)
 
# data set 소설 레미제라블 인물 관계도
# 데이터 로드
data(MisLinks, MisNodes)
head(MisNodes) # size : 몇번 언급되었는지에 대한 정보
head(MisLinks) # value : 인물끼리 몇번 만났는지 데이터 
 
# plot
D3_network_LM<-forceNetwork(Links = MisLinks, Nodes = MisNodes, 
                            Source = 'source', Target = 'target'
                            NodeID = 'name', Group = 'group',opacityNoHover = TRUE,
                            zoom = TRUE, bounded = TRUE,
                            fontSize = 15,
                            linkDistance = 75,
                            opacity = 0.9)
 
D3_network_LM
cs

 

 

허거덩 너무 신기해~!

 

 

모바일관련 소송 시각화

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# IT 회사들간 법적 소송관계도 시각화
# 데이터 로드
links = '[
  {"source": "Microsoft", "target": "Amazon", "type": "licensing"},
{"source": "Microsoft", "target": "HTC", "type": "licensing"},
{"source": "Samsung", "target": "Apple", "type": "suit"},
{"source": "Motorola", "target": "Apple", "type": "suit"},
{"source": "Nokia", "target": "Apple", "type": "resolved"},
{"source": "HTC", "target": "Apple", "type": "suit"},
{"source": "Kodak", "target": "Apple", "type": "suit"},
{"source": "Microsoft", "target": "Barnes & Noble", "type": "suit"},
{"source": "Microsoft", "target": "Foxconn", "type": "suit"},
{"source": "Oracle", "target": "Google", "type": "suit"},
{"source": "Apple", "target": "HTC", "type": "suit"},
{"source": "Microsoft", "target": "Inventec", "type": "suit"},
{"source": "Samsung", "target": "Kodak", "type": "resolved"},
{"source": "LG", "target": "Kodak", "type": "resolved"},
{"source": "RIM", "target": "Kodak", "type": "suit"},
{"source": "Sony", "target": "LG", "type": "suit"},
{"source": "Kodak", "target": "LG", "type": "resolved"},
{"source": "Apple", "target": "Nokia", "type": "resolved"},
{"source": "Qualcomm", "target": "Nokia", "type": "resolved"},
{"source": "Apple", "target": "Motorola", "type": "suit"},
{"source": "Microsoft", "target": "Motorola", "type": "suit"},
{"source": "Motorola", "target": "Microsoft", "type": "suit"},
{"source": "Huawei", "target": "ZTE", "type": "suit"},
{"source": "Ericsson", "target": "ZTE", "type": "suit"},
{"source": "Kodak", "target": "Samsung", "type": "resolved"},
{"source": "Apple", "target": "Samsung", "type": "suit"},
{"source": "Kodak", "target": "RIM", "type": "suit"},
{"source": "Nokia", "target": "Qualcomm", "type": "suit"}
]'
 
link_df = jsonlite::fromJSON(links)
# node의 index 숫자는 0부터 시작
# dplyr::row_number()가 1부터 숫자를 매기기 때문에 1씩 뺌
node_df = data.frame(node = unique(c(link_df$source, link_df$target))) %>
  mutate(idx = row_number()-1)
 
# node_df에서 index값을 가져와서 source와 target에 해당하는 index 값을 저장
link_df = link_df %>
  left_join(node_df %>% rename(source_idx = idx), by=c('source' = 'node')) %>
  left_join(node_df %>% rename(target_idx = idx), by=c('target' = 'node'))
 
# 데이터 확인
node_df
link_df
 
# 3D 시각화 패키지 설치
library(networkD3)
library(dplyr)
 
# plot
D3_network_LM<-forceNetwork(Links = link_df, 
                            Nodes = node_df, 
                            Source = 'source_idx', Target = 'target_idx'
                            NodeID = 'node', Group = 'idx',
                            opacityNoHover = TRUE, zoom = TRUE
                            bounded = TRUE,
                            fontSize = 15,
                            linkDistance = 75,
                            opacity = 0.9)
 
D3_network_LM
 
cs

 

Microsoft 깡패...

 

 

 

 

 

 

paper1.csv
0.00MB
book_hour.csv
0.00MB

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 친구를 만난 횟수 데이터 불러오기
paper <- read.csv("c:/data/paper1.csv" , header = T)
 
# 결측치 매꾸기
paper[is.na(paper)] <- 0
 
# rowname을 이름으로 바꾸기
rownames(paper) <- paper[,1]
 
# x 테이블 지우기
paper <- paper[-1]
 
# 확인 : dataframe을 matrix 형식으로 바꾸기 위한 작업들이었음
paper
 
# dataframe -> matrix
paper2 <- as.matrix(paper)
paper2
 
# 책 읽은 시간에 대한 데이터 불러오기
book <- read.csv("c:/data/book_hour.csv" , header = T)
book
 
# 시각화를 위한 라이브러리
library(sna)
 
# 빈 창 띄우기
x11()
 
# 시각화
gplot(paper2 , displaylabels = T, boxed.labels = F , vertex.cex = sqrt(book[,2]) , vertex.col = "blue" , vertex.sides = 20 ,
      edge.lwd = paper2*2 , edge.col = "green" , label.pos = 3)
 
cs

 

 

파란색 공 : 책을 읽은 정도 / 초록색 : 자주 만난 정도

 

 

building.csv
0.00MB

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# 데이터 로드 
build <- read.csv("c:/data/building.csv" , header = T)
 
# 결측치를 0으로 채움
build[is.na(build)] <- 0  
head(build)
 
# x 컬럼 삭제
build <- build[-1]
 
# arules 패키지 설치
# install.packages("arules")
library(arules) 
 
# 연관규칙 모델 생성
trans <- as.matrix(build , "Transaction")
rules1 <- apriori(trans , parameter = list(supp=0.2 , conf = 0.6 , target = "rules"))
rules1 
 
# 연관규칙 확인
inspect(sort(rules1))
 
# 신뢰도 0.7이상인 것만 추출
rules2 <- subset(rules1 , subset = lhs %pin% '보습학원' & confidence > 0.7)
inspect(sort(rules2)) 
 
rules3 <- subset(rules1 , subset = rhs %pin% '편의점' & confidence > 0.7)
inspect(sort(rules3)) 
 
# 시각화
# install.packages("sna")
# install.packages("rgl")
library(sna)
library(rgl)
 
# 희소행렬로 만듦
b2 <- t(as.matrix(build)) %*% as.matrix(build)
# 대각성분을 0으로 만듦
b2.w <- b2 - diag(diag(b2))
 
#rownames(b2.w) 
#colnames(b2.w) 
 
gplot(b2.w , displaylabel=T , vertex.cex=sqrt(diag(b2)) , vertex.col = "green" , edge.col="blue" , boxed.labels=F , arrowhead.cex = .3 , label.pos = 3 , edge.lwd = b2.w*2
 
cs

 

 

학원은 카페, 은행과 연관되어 있음을 확인

 

 

 

 

Apriori 알고리즘이란?

Apriori 알고리즘이란 연관규칙(association rule)으로, 특정 사건이 발생하였을 때 함께 (빈번하게) 발생하는 또 다른 사건의 규칙을 말한다.

 

 

Apriori 알고리즘을 사용하는 대표적인 예

1. 암 분석 시 빈번히 발생하는 DNA 패턴과 단백질 서열 검사

2. 신용카드 사기를 당했을 때 주로 결제되는 내역 패턴

3. B2C에서 구매자의 구매 상품과 비슷한 상품 추천

 

 

연관규칙에 사용하는 3가지 통계 척도

종류 설명 표기식
지지도(support) 특정 아이템이 데이터에서 발생하는 빈도 s(X) = n(X) / N

n(X) : 아이템 X의 거래건수
N : 전체거래건수
s(X,Y) = n(X∩Y) / N

n(X∩Y) : 아이템 X와 Y를 포함하는 거래건수
N : 전체거래건수
신뢰도(confidence) 두 아이템의 연관규칙이 유용한 규칙일 가능성의 척도 c(X→Y) = n(X∩Y)/n(X)

n(X∩Y) : 아이템 X와 Y를 포함하는 거래건수
n(X) : 아이템 X의 거래건수

아이템 X를 포함하는 거래 중에서 아이템 Y도 포함하는 거래비율을 말한다.
신뢰도가 높을수록 유용한 규칙일 가능성이 높다.
향상도(lift) 두 아이템의 연관규칙이 우연인지 아닌지를 나타내는 척도 lift(X→Y) = c(X→Y) / s(Y)
아이템 X가 주어지지 않았을 때의 아이템 Y 확률 대비 아이템 X가 주어졌을 때의 아이템 Y 확률 비율을 나타낸다.
향상도가 1보다 크거나(+관계) 작으면(-관계) 우연적 기회보다 우수함을 의미한다.

연산식이 교집합(∩)인지, 합집합(∪)인지에 대해서 헷갈릴 수 있겠는데

그냥 조건부 확률을 구한다고 생각하자.

 

아래의 문제를 통해 연관규칙 알고리즘을 이해해보자.

 

거래번호 거래 아이템
1 , 버터,
2 ,
3 우유, 빵
4 버터, 맥주, 오징어

 

문제 1. s(우유,시리얼) = n(X∩Y) / N = 2/4

 

          우유와 시리얼이 같이 있는 경우를 교집합(∩)으로 써야할까, 합집합(∪)으로 써야할까?

          나같은 경우는 수학적으로 생각했을 때, 교집합이 맞다고 생각해서 교집합을 썼지만 언어적으로는 합집합이

          맞는것 같다. 따라서 이것은 맥락적으로 이해하는 것이 매우 중요하다.

 

문제 2. c(우유→시리얼) = n(X∩Y) / n(X) = 2/3

 

문제 3. lift(우유→시리얼) = c(우유→시리얼) / s(우유,시리얼) = (2/3) / (2/4) = 1.333

 

 

 

 

 

 

 


 

 

 

 

 

PRUNING (가지치기)

모든 아이템들간의 관계성을 알아봐야하기 때문에, 데이터가 많아지면 지수적으로 경우의 수가 많아져 계산량이 많아진다.

따라서 우리는 이것을 효율적으로 수행해야한다.

 

거래번호 아이템 목록
1 A,B,D
2 B,C,
3 A,B,C,E
4 B,C,E

 

1. 각각의 아이템에 대한 지지도를 구한다.

(원래 지지도(s)는 구매건수 / 전체구매건수 이지만 가지치기에서는 단순히 아이템의 갯수로 처리한다.)

 

아이템 지지도
A 2
B 4
C 3
D 1
E 2

 

2. 위의 결과에서 지지도가 1보다 큰 것을 추출한다.

 

아이템 지지도
A 2
B 4
C 3
E 2

 

1-2. 아이템을 2개 조합으로 만들어 지지도를 구한다.

 

아이템 지지도
A B 2
A C 1
A E 1
B C 2
B E 1
C E 2

 

2. 위의 결과에서 지지도가 1보다 큰 것을 추출한다.

 

아이템 지지도
A B 2
B C 2
C E 2

 

1-3. 아이템을 3개 조합으로 만들어 지지도를 구한다.

 

아이템 지지도
A B C 1
A B E 1
A C E 1
B C E 2

 

2. 위의 결과에서 지지도가 1보다 큰 것을 추출한다.

 

아이템 지지도
B C E 2

 

가지치기(Pruning)를 당한 것들에 대해서는 지지도를 계산하지 않는다.

 

 

 

 

 

이외에도 효율적으로 연관성 분석을 하는 방법이 있으니, 블로그를 참고하길 바란다.

 

 

 

 

 

 

wine.csv
0.01MB

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 분류를 위한 nnet 신경망 패키지 설치
install.packages("nnet")
library(nnet)
 
# 이원교차표를 보기 위함
library(gmodels)
 
wine <- read.csv("c:/data/wine.csv",header=T,stringsAsFactors = T)
 
# 확인
head(wine)
str(wine)
 
# scale 함수를 사용한 정규화 (평균 0, 표존편차 1)
wine.scale <- cbind(wine[1], scale(wine[-1]))
summary(wine.scale)
 
size <- nrow(wine.scale) # 178
 
# shuffle
set.seed(100)
index <- c(sample(1:size, size * 0.7))
 
# train(70%) / test(30%)
train <- wine.scale[index, ]
test <- wine.scale[-index, ]
 
# 분류를 위한 신경망 모델 생성
model.nnet2 <- nnet(Type~., data = train, size = 2, decay = 5e-04, maxit = 200)
#                                         number of units in the hidden layer.
#                                                   parameter for weight decay. Default 0. (가중치 감소)
#                                                                  maximum number of iterations. Default 100 (반복)
 
# 분류결과 확인
predicted <- predict(model.nnet2, test, type = "class")
predicted
 
# 모델 평가를 위한 Confusion Matrix
# 참고 : https://yamalab.tistory.com/50
actual <- test$Type
model.confusion.matrix <- table(actual, predicted)
 
# 모델 평가
<- CrossTable(model.confusion.matrix)
x$prop.tbl[1]+x$prop.tbl[5]+x$prop.tbl[9# 0.9444444
 
cs

 

 

+ Recent posts