-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathuser-2015.Rmd
1451 lines (1038 loc) · 27.4 KB
/
user-2015.Rmd
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Statistical Analysis of Network Data"
author: "Gábor Csárdi"
date: "`r Sys.Date()`"
output:
ioslides_presentation:
css: tweaks.css
highlight: pygments
keep_md: yes
vignette: >
%\VignetteIndexEntry{Statistical Analysis of Network Data}
\usepackage[utf8]{inputenc}
%\VignetteEngine{knitr::docco_classic}
---
```{r, setup, echo = FALSE, message = FALSE}
library(knitr)
library(igraph)
opts_chunk$set(
prompt = FALSE,
comment = "#>",
tidy = FALSE)
options(width = 73)
igraph_options(graph.margin = 0, margin = 0)
```
## How to follow this tutorial
Go to https://github.com/igraph/netuser15
You will need at least `igraph` version `1.0.0` and `igraphdata` version
`1.0.0`. You will also need the `DiagrammeR` package. To install them
from within R, type:
```r
install.packages("igraph")
install.packages("igraphdata")
install.packages("DiagrammeR")
```
## Outline
* Introduction
* Manipulate network data
* Questions
### BREAK
* Classic graph theory: paths
* Social network concepts: centrality, groups
* Visualization
* Questions
## Why networks?
Sometimes connections are important, even more important than
(the properties of) the things they connect.
## Example 1: Königsberg Bridges

-- Bogdan Giuşcă, CC BY-SA 3.0, Wikipedia
## Example 2: Page Rank
<img src="images/ILLUSTRATION3.PNG.png" width="80%">
http://computationalculture.net/article/what_is_in_pagerank
## Example 3: Matching Twitter to Facebook

http://morganlinton.com/wp-content/uploads/2013/12/twitter-facebook-branding2.png
## Example 4: Detection of groups

https://en.wikipedia.org/wiki/Community_structure#/
media/File:Network_Community_Structure.svg
<!-- ## Example 5: Detection of unusual activity -->
<!-- Detection of dense parts of the network, that were not dense before. -->
## About igraph
* Network analysis library, written mostly in C/C++.
* Interface to R and Python
* https://github.com/igraph
* http://igraph.org
* Mailing list, stack overflow help.
* Open GitHub issues for bugs
# Creating and manipulating networks in R/igraph.
## What is a network or graph?
```{r echo = FALSE, results = "hide", message = FALSE}
set.seed(42)
library(igraph)
library(igraphdata)
data(karate)
par(mar=c(0,0,0,0))
plot(karate, margin = 0)
```
## More formally:
* `V`: set of vertices
* `E`: subset of ordered or unordered pairs of vertices. Multiset, really.
## Creating toy networks with `make_graph`
```{r message = FALSE}
library(igraph)
```
```{r}
toy1 <- make_graph(~ A - B, B - C - D, D - E:F:A, A:B - G:H)
toy1
```
----
```{r}
par(mar = c(0,0,0,0)); plot(toy1)
```
----
```{r}
toy2 <- make_graph(~ A -+ B, B -+ C -+ D +- A:B)
toy2
```
----
```{r}
par(mar = c(0,0,0,0)); plot(toy2)
```
## Printout of a graph
```{r}
toy2
```
`IGRAPH` means this is a graph object. Next, comes a four letter
code:
* `U` or `D` for undirected or directed
* `N` if the graph is named, always use named graphs for real data sets.
* `W` if the graph is weighted (has a `weight` edge attribute).
* `B` if the graph is bipartite (has a `type` vertex attribute).
## Attributes
```{r}
make_ring(5)
```
* Some graphs have a name (`name` graph attribute), that comes after
the two dashes.
* Then the various attributes are listed. Attributes
are metadata that is attached to the vertices, edges, or the graph
itself.
* `(v/c)` means that `name` is a vertex attribute, and it is
character.
* `(e/.)` means an edge attribute, `(g/.)` means a graph attribute
-----
```{r}
make_ring(5)
```
* Attribute types: `c` for character, `n` for numeric, `l` for
logical and `x` (complex) for anything else.
* igraph treats some attributes specially. Always start your non-special
attributes with an uppercase letter.
## Real network data
## Adjacency matrices
```{r}
A <- matrix(sample(0:1, 100, replace = TRUE), nrow = 10)
A
```
-----
```{r}
graph_from_adjacency_matrix(A)
```
## List of edges
```{r}
L <- matrix(sample(1:10, 20, replace = TRUE), ncol = 2)
L
```
-----
```{r}
graph_from_edgelist(L)
```
## Two tables, one for vertices, one for edges
```{r}
edges <- data.frame(
stringsAsFactors = FALSE,
from = c("BOS", "JFK", "LAX"),
to = c("JFK", "LAX", "JFK"),
Carrier = c("United", "Jetblue", "Virgin America"),
Departures = c(30, 60, 121)
)
vertices <- data.frame(
stringsAsFactors = FALSE,
name = c("BOS", "JFK", "LAX"),
City = c("Boston, MA", "New York City, NY",
"Los Angeles, CA")
)
```
-----
```{r}
edges
```
-----
```{r}
vertices
```
-----
```{r}
toy_air <- graph_from_data_frame(edges, vertices = vertices)
toy_air
```
----
The real US airports data set is in the `igraphdata` package:
```{r}
library(igraphdata)
data(USairports)
USairports
```
----
Converting it back to tables
```{r}
as_data_frame(toy_air, what = "edges")
```
-----
```{r}
as_data_frame(toy_air, what = "vertices")
```
-----
Long data frames
```{r}
as_long_data_frame(toy_air)
```
-----
Quickly look at the metadata, without conversion:
```{r}
V(USairports)[[1:5]]
```
----
```{r}
E(USairports)[[1:5]]
```
## Weighted graphs
Numbers (usually real) assigned to edges. E.g. number of departures,
or number of passengers.

http://web.cecs.pdx.edu/~sheard/course/Cs163/Doc/Graphs.html
## Multigraphs
They have multiple (directed) edges between the
same pair of vertices. A graph that has no multiple edges
and no loop edges is a simple graph.

https://en.wikipedia.org/wiki/Multigraph
Multi-graphs are nasty. Always check if your graph is a multi-graph.
-----
```{r}
is_simple(USairports)
sum(which_multiple(USairports))
sum(which_loop(USairports))
```
-----
`simplify()` creates a simple graph from a multigraph, in a flexible
way: you can specify what it should do with the edge attributes.
```{r}
air <- simplify(USairports, edge.attr.comb =
list(Departures = "sum", Seats = "sum", Passengers = "sum", "ignore"))
is_simple(air)
summary(air)
```
## Querying and manipulating networks: the `[` and `[[` operators
The `[` operator treats the graph as an adjacency matrix.
```
BOS JFK ANC EWR . . .
BOS . 1 . 1
JFK 1 . 1 .
ANC . 1 . .
EWR 1 . 1 .
. . .
```
-----
The `[[` operator treats the graph as an adjacency list.
```{r eval = FALSE}
BOS: JFK, LAX, EWR, MKE, PVD
JFK: BGR, BOS, SFO, BNA, BUF, SRQ, RIC RDU, MSP
LAX: DTW, MSY, LAS, FLL, STL,
. . .
```
## Queries
Does an edge exist?
```{r}
air["BOS", "JFK"]
air["BOS", "ANC"]
```
-----
Convert the graph to an adjacency matrix, or just a part of it:
```{r}
air[c("BOS", "JFK", "ANC"), c("BOS", "JFK", "ANC")]
```
For weighted graphs, query the edge weight:
```{r}
E(air)$weight <- E(air)$Passengers
air["BOS", "JFK"]
```
----
All adjacent vertices of a vertex:
```{r}
air[["BOS"]]
```
----
```{r}
air[[, "BOS"]]
```
## Manipulation
Add an edge (and potentially set its weight):
```{r}
air["BOS", "ANC"] <- TRUE
air["BOS", "ANC"]
```
Remove an edge:
```{r}
air["BOS", "ANC"] <- FALSE
air["BOS", "ANC"]
```
----
Note that you can use all allowed indexing modes, e.g.
```{r}
g <- make_empty_graph(10)
g[-1, 1] <- TRUE
g
```
creates a star graph.
----
Add vertices to a graph:
```{r}
g <- make_ring(10) + 2
par(mar = c(0,0,0,0)); plot(g)
```
----
Add vertices with attributes:
```{r}
g <- make_(ring(10), with_vertex_(color = "grey")) +
vertices(2, color = "red")
par(mar = c(0,0,0,0)); plot(g)
```
----
Add an edge
```{r}
g <- make_(star(10), with_edge_(color = "grey")) +
edge(5, 6, color = "red")
par(mar = c(0,0,0,0)); plot(g)
```
----
Add a chain of edges
```{r}
g <- make_(empty_graph(5)) + path(1,2,3,4,5,1)
g2 <- make_(empty_graph(5)) + path(1:5, 1)
g
g2
```
## Exercise
Create the wheel graph.
```{r echo = FALSE}
par(mar=c(0,0,0,0))
plot(make_star(11, center = 11, mode = "undirected") + path(1:10, 1))
```
## (A) solution
```{r}
make_star(11, center = 11, mode = "undirected") + path(1:10, 1)
```
## Vertex sequences
They are the key objects to manipulate graphs. Vertex sequences
can be created in various ways. Most frequently used ones:
|expression |result |
|:--------------------------|:---------------------------------|
|`V(air)` |All vertices. |
|`V(air)[1,2:5]` |Vertices in these positions |
|`V(air)[degree(air) < 2]` |Vertices satisfying condition |
|`V(air)[nei('BOS')]` |Neighbors of a vertex |
|`V(air)['BOS', 'JFK']` |Select given vertices |
## Edge sequences
The same for edges:
|expresssion |result |
|:--------------------------|:--------------------------------------------|
|`E(air)` |All edges. |
|`E(air)[FL %--% CA]` |Edges between two vertex sets |
|`E(air)[FL %->% CA]` |Edges between two vertex sets, directionally |
|`E(air, path = P)` |Edges along a path |
|`E(air)[to('BOS')]` |Incoming edges of a vertex |
|`E(air)[from('BOS')]` |Outgoing edges of a vertex |
## Manipulate attributes via vertex and edge sequences
```{r}
FL <- V(air)[grepl("FL$", City)]
CA <- V(air)[grepl("CA$", City)]
V(air)$color <- "grey"
V(air)[FL]$color <- "blue"
V(air)[CA]$color <- "blue"
```
----
```{r}
E(air)[FL %--% CA]
E(air)$color <- "grey"
E(air)[FL %--% CA]$color <- "red"
```
## Quick look at metadata
```{r}
V(air)[[1:5]]
```
----
```{r}
E(air)[[1:5]]
```
# BREAK
## Paths
```{r echo = FALSE}
set.seed(42)
g <- sample_gnp(12, 0.25)
l <- layout_nicely(g)
par(mar=c(0,0,0,0))
plot(g, margin = 0, layout = l)
```
## Paths
```{r echo = FALSE}
pa <- V(g)[11, 2, 12, 8]
V(g)[pa]$color <- 'green'
E(g)$color <- 'grey'
E(g, path = pa)$color <- 'red'
E(g, path = pa)$width <- 3
par(mar=c(0,0,0,0))
plot(g, margin = 0, layout = l)
```
## Define a path in igraph
```{r}
set.seed(42)
g <- sample_gnp(12, 0.25)
pa <- V(g)[11, 2, 12, 8]
V(g)[pa]$color <- 'green'
E(g)$color <- 'grey'
E(g, path = pa)$color <- 'red'
E(g, path = pa)$width <- 3
```
----
```{r}
par(mar=c(0,0,0,0))
plot(g, margin = 0, layout = layout_nicely)
```
## Shortest paths
```{r echo = FALSE}
set.seed(42)
g <- sample_gnp(12, 0.25)
pa <- V(g)[11, 2, 12, 8]
V(g)[pa]$color <- 'green'
E(g)$color <- 'grey'
E(g, path = pa)$color <- 'red'
E(g, path = pa)$width <- 3
par(mar=c(0,0,0,0))
plot(g, margin = 0, layout = layout_nicely)
```
----
Length of the shortest path: distance.
How many planes to get from `PBI` to `BDL`?
```{r}
air <- delete_edge_attr(air, "weight")
distances(air, 'PBI', 'ANC')
```
----
```{r}
sp <- shortest_paths(air, 'PBI', 'ANC', output = "both")
sp
air[[ sp$epath[[1]] ]]
```
----
```{r}
all_shortest_paths(air, 'PBI', 'ANC')$res
```
## Weighted paths
```{r}
wair <- simplify(USairports, edge.attr.comb =
list(Departures = "sum", Seats = "sum", Passangers = "sum",
Distance = "first", "ignore"))
E(wair)$weight <- E(wair)$Distance
```
## Weighted (shortest) paths
```{r}
distances(wair, c('BOS', 'JFK', 'PBI', 'AZO'),
c('BOS', 'JFK', 'PBI', 'AZO'))
```
----
```{r}
shortest_paths(wair, from = 'BOS', to = 'AZO')$vpath
all_shortest_paths(wair, from = 'BOS', to = 'AZO')$res
```
## Mean path length
```{r}
mean_distance(air)
air_dist_hist <- distance_table(air)
air_dist_hist
```
----
```{r}
barplot(air_dist_hist$res, names.arg = seq_along(air_dist_hist$res))
```
## Components
<img src="images/Pseudoforest.png" with="65%">
David Eppstein, public domain
## Strongly connected components
<img src="images/scc.jpg" width="65%">
http://www.greatandlittle.com/studios/
----
```{r}
co <- components(air, mode = "weak")
co$csize
groups(co)[[2]]
```
----
```{r}
co <- components(air, mode = "strong")
co$csize
```
## Bow-tie structure of a directed graph
<img src="images/bowtie-page.png" width="65%">
http://webdatacommons.org/hyperlinkgraph/2012-08/topology.html
## Exercise
1. Extract the large (strongly) connected component from the
airport graph, as a separate graph.
Hint: `components()`, `induced_subgraph()`.
How many airports are not in this component?
1. In the large connected component, which airport is better
connected, `LAX` or `BOS`? I.e. what is the mean number of
plane changes that are required if traveling to a uniformly
randomly picked airport?
1. Which airport is the best connected one? Which one is the
worst (within the strongly connected component)?
## Solution
```{r}
largest_component <- function(graph) {
comps <- components(graph, mode = "strong")
gr <- groups(comps)
sizes <- vapply(gr, length, 1L)
induced_subgraph(graph, gr[[ which.max(sizes) ]])
}
sc_air <- largest_component(air)
```
----
```{r}
table(distances(sc_air, "BOS"))
table(distances(sc_air, "LAX"))
```
----
```{r}
mean(as.vector(distances(sc_air, "BOS")))
mean(as.vector(distances(sc_air, "LAX")))
```
----
```{r}
D <- distances(sc_air)
sort(rowMeans(D))[1:10]
```
----
```{r}
sort(rowMeans(D), decreasing = TRUE)[1:10]
```
----
```{r}
V(sc_air)[[names(sort(rowMeans(D), decreasing = TRUE)[1:10])]]
```
## Centrality
Finding important vertices in the network (family of concepts)
```{r echo = FALSE}
par(mar=c(0,0,0,0))
plot(make_star(11))
```
## Centrality
```{r echo = FALSE}
data(kite)
par(mar=c(0,0,0,0))
plot(kite)
```
## Classic centrality measures: degree
```{r}
V(kite)$label.cex <- 2
V(kite)$color <- V(kite)$frame.color <- "grey"
V(kite)$size <- 30
par(mar=c(0,0,0,0)) ; plot(kite)
```
-------
```{r}
d <- degree(kite)
par(mar = c(0,0,0,0))
plot(kite, vertex.size = 10 * d, vertex.label =
paste0(V(kite)$name, ":", d))
```
## Classic centrality measures: closeness
1 / How many steps do you need to get there?
```{r}
cl <- closeness(kite)
```
-----
```{r}
par(mar=c(0,0,0,0)); plot(kite, vertex.size = 500 * cl)
```
## Classic centrality measures: betweenness
How many shortest paths goes through me
```{r}
btw <- betweenness(kite)
btw
```
-----
```{r}
par(mar=c(0,0,0,0)); plot(kite, vertex.size = 3 * btw)
```
## Eigenvector centrality
Typically for directed. Central vertex: it is cited by central vertices.
```{r}
ec <- eigen_centrality(kite)$vector
ec
cor(ec, d)
```
-----
```{r}
par(mar=c(0,0,0,0)); plot(kite, vertex.size = 20 * ec)
```
## Page Rank
Fixes the practical problems with eigenvector centrality
```{r}
page_rank(kite)$vector
```
## Exercise
Create a table that contains the top 10 most central
airports according to all these centrality measures.
# Clusters
## Why finding groups
Finding groups in networks. Dimensionality reduction. Community detection.
We want to find dense groups.
-----
<img src="images/communities1.png" width="70%">
## Clusters by hand
```{r}
graph <- make_graph( ~ A-B-C-D-A, E-A:B:C:D,
F-G-H-I-F, J-F:G:H:I,
K-L-M-N-K, O-K:L:M:N,
P-Q-R-S-P, T-P:Q:R:S,
B-F, E-J, C-I, L-T, O-T, M-S,
C-P, C-L, I-L, I-P)
```
----
```{r}
par(mar=c(0,0,0,0)); plot(graph)
```
----
```{r}
flat_clustering <- make_clusters(
graph,
c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4))
```
-----
```{r}
flat_clustering
```
-----
```{r}
flat_clustering[[1]]
length(flat_clustering)
sizes(flat_clustering)
```
-----
```{r}
induced_subgraph(graph, flat_clustering[[1]])
```
## Hierarchical community structure
Typically produced by top-down or bottom-up clustering algorithms.
The outcome can be represented as a *dendrogram*,
a tree-like diagram that illustrates the order in which the clusters
are merged (in the bottom-up case) or split (in the top-down case).
-----
<img src="images/communities2.png" width="100%">
## Clustering quality measures
- External quality measures: require ground truth
- Internal quality measures: require assumption about *good*
clusters.
## External quality measures
Measure | Type | Range | igraph name
------------------------------|------------|------------|----------------
Rand index | similarity | 0 to 1 | `rand`
Adjusted Rand index | similarity | -0.5 to 1 | `adjusted.rand`
Split-join distance | distance | 0 to 2n | `split.join`
Variation of information | distance | 0 to log n | `vi` |
Normalized mutual information | similarity | 0 to 1 | `nmi`
## External quality measures
```{r}
data(karate)
karate
karate <- delete_edge_attr(karate, "weight")
```
-----
```{r}
ground_truth <- make_clusters(karate, V(karate)$Faction)
length(ground_truth)
ground_truth
```
## Exercise
Write a naive clustering method that classifies vertices
into two groups, based on two center vertices. Put the two
centers in separate clusters, and other vertices in the
cluster whose center is closer to it.
```{r}
cluster_naive2 <- function(graph, center1, center2) {
# ...
}
```
## Solution
```{r}
cluster_naive2 <- function(graph, center1, center2) {
dist <- distances(graph, c(center1, center2))
cl <- apply(dist, 2, which.min)
make_clusters(graph, cl)
}
dist_memb <- cluster_naive2(karate, 'John A', 'Mr Hi')
```
----
```{r}
dist_memb
```
## Rand index
Check if pairs of vertices are classified correctly
```{r}
rand_index <- compare(ground_truth, dist_memb, method = "rand")
rand_index
```
## Rand index
Random clusterings
```{r}
random_partition <- function(n, k = 2) { sample(k, n, replace = TRUE) }
total <- numeric(100)
for (i in seq_len(100)) {
c1 <- random_partition(100)
c2 <- random_partition(100)
total[i] <- compare(c1, c2, method = "rand")
}
mean(total)
```
## Adjusted Rand index
```{r}