Моя презентация по кластеризации графов, прочитанная на курсах newprolab в Digital October весной 2015 года. Назначение: ликбез по основным подходам, метрикам и алгоритмам. Также приведено кое-что из наших наработок в DCA.
2. Что такое сообщество?
• Сообщество — интуитивное понятие, нет единого определения
• Глобальный взгляд: «такое скопление не может быть случайно»
• Модулярность: сравнение со случайным графом (почти Эрдёша-Ренью)
• Локальный взгляд: «внутри больше связей, чем снаружи рядом»
• В слабом смысле: internal degree > external degree
• В сильном смысле: internal degree > external degree для каждой
вершины
• Совсем локальный взгляд: скопление «похожих» вершин
• Мера Жаккарда:
j belong to the same cluster. Another way of looking at it is that an edge that is a
part of many triangles is probably in a dense region i.e. a cluster. We use the Jaccard
measure to quantify the overlap between adjacency lists. Let Adj(i) be the adjacency
list of i, and Adj(j) be the adjacency list of j. For simplicity, we will refer to the
similarity between Adj(i) and Adj(j) as the similarity between i and j itself.
Sim(i, j) =
|Adj(i) ∩ Adj(j)|
|Adj(i) ∪ Adj(j)|
(5.1)
Global Sparsification
3. Почему это важно?
1. Сегменты DMP
2. Товарные рекомендации
3. Центральность внутри
сообществ: реальные потоки
информации
4. Сравнение с номинальными
сообществами (общежития,
группы vk)
5. Компрессия и визуализация
4. Как искать сообщества?
• Graph partitioning: оптимальное разбиение на
заранее заданное количество подграфов k.
как хорошо выбрать это k?
• Community finding: нахождение отдельных скоплений
k не контролируется напрямую
не обязательно полное покрытие сообществами
сообщества могут перекрываться
5. Как оценить успех?
• Целевые функции
• Оптимизация на графе целиком — только приближенные
эвристики
• Сравнение результатов разных алгоритмов
• Выбор наилучшего k для graph partitioning’a
• Если есть ground truth — использовать стандартные
метрики для задач классификации
• часто WTF — самая лучшая метрика — смотреть глазами
7. Клики
• Просто клика: полный подграф
• Все знают всех
• Иногда требуют еще
максимальность: нельзя никого
добавить
• Алгоритм Брона-Кербоша (1973):
n — число вершин, d_max —
максимальная степень
O(n · 3dmax/3)
8. Недостатки клик
• Слишком строгая предпосылка:
• Большие клики почти не встречаются
• Маленькие клики часто встречаются
даже в графе Эрдёша-Ренью
• Исчезновение одного ребра уничтожает
клику
• Нет центра и окраины сообщества
• Симметрия: нет смысла в центральности
9. Обобщения
• n-clique: максимальный подграф, где путь
между любыми вершинами не длиннее n.
• При n =1 вырождается в просто клику
• Внутри n-clique может быть даже несвязна!
• n-club: n-clique с диаметром n. Всегда связна.
• k-core: максимальный подграф, где у каждой
вершины не менее k внутренних соседей.
• p-clique: у каждой вершины доля внутренних
соседей не меньше p (от 0 до 1)
10. Алгоритм нахождения k-
cores
• Алгоритм Batagelj and Zaversnik (2003): O(m)
m — число ребер
• Вход: граф G(V,E)
• Выход: значение k для каждой вершины
12. Модулярность
• Пусть — степень вершины i,
• m — число ребер, A — матрица смежности
• Перемешаем все ребра, сохраняя распределение степеней
• Вероятность того, что i и j будут соединены (грубая
оценка!):
• Модулярность: мера «неслучайности» сообщества:
ki
kikj
2m
Q =
1
2m
i,j
Aij −
kikj
2m
I ci = cj
13. Свойства модулярности
• m_s — число ребер в сообществе s, d_s —
суммарная степень вершин в s
• Максимальное значение: при S
разъединенных кликах Q = 1-1/S
• Максимум для связного графа: при S
равных подграфах, соединенных одним
ребром
• В этом случае Q = 1 - 1/S - S/m
Q ≡
s
ms
m
−
ds
2m
2
14. Недостатки модулярности
• Предел разрешения (resolution
limit)!
• Сообщества c
сливаются в одно
• Если на рисунке клики имеют
размер n_s, то они сливаются
при
• Смещение размера кластера
в сторону выравнивания
ms <
√
2m
ns(ns − 1) + 1 < S
15. WCC
• Пусть S — сообщество (его вершины)
• V — все вершины
• — число треугольников внутри S, в которых участвует вершина x
• — число вершин из S, образующих хотя бы один треугольник с вершиной x
• Weighted Community Clustering для одной вершины:
• Для всего сообщества просто усредняем:
WCC(S) =
1
|S|
x∈S
WCC(x, S)
16. WCC
• Произведение двух компонент
• Треугольник = «компашка»
• Слева: какая доля компашек с участием x находится внутри
его «домашнего» сообщества?
• Справа в числителе: сколько всего людей участвует в
компашках вместе с x?
• Справа в знаменателе: сколько людей участвовало бы в
компашках с x, если бы S был кликой?
19. Newman-Girvan
• Иерархический divisive алгоритм
• По очереди удаляем ребро с самым большим betweenness
• Останавливаемся при выполнении критерия (например,
получили k связных компонент)
• O(n*m) на вычисление кратчайших путей
• O(n+m) на пересчет связных компонент
• Весь алгоритм — не меньше O(n^3)
• Не используется на графах крупнее нескольких сотен
узлов
20. k-medoids
• k-means: требуется нормированное пространство
• В графе расстояние определено только между
вершинами (например, 1 - Jaccard) => k-means не
годится
• k-medoids: в качестве центроидов выступают только
имеющиеся точки
• Нужно задавать k заранее (graph partitioning)
• Самый известный вариант называется PAM
21. k-medoids: PAM
1.Явным образом задаем k — количество кластеров.
2.Инициализируем: выбираем k случайных узлов в качестве медоидов.
3.Для каждой точки находим ближайший медоид, формируя исходное разбиение на кластеры.
4.minCost = функция потерь от исходной конфигурации
5.Для каждого медоида m:
5.1. Для каждой вершины v != m внутри кластера с центром в m:
5.1.1. Перемещаем медоид в v
5.1.2. Перераспределяем все вершины между новыми медоидами
5.1.3. cost = функция потерь по всему графу
5.1.4. Если cost < minCost:
5.1.4.1. Запоминаем медоиды
5.1.4.2. minCost = cost
5.1.5. Кладем медоид на место (в m)
6.Делаем наилучшую замену из всех найденных (то есть внутри одного кластера меняем один
медоид)
7.Повторяем пп. (4)-(5) до тех пор, пока медоиды не стабилизируются
22. k-medoids: новая эвристика
1.While True:
1.1.Для каждого медоида m:
1.1.1. Случайно выбираем s точек внутри кластера с центром в m
1.1.2. Для каждой вершины v из s:
1.1.2.1. Перемещаем медоид в v
1.1.2.2. Перераспределяем все вершины между новыми медоидами
1.1.2.3. cost = функция потерь по всему графу
1.1.2.4. Если cost < minCost:
1.1.2.4.1. Запоминаем медоиды
1.1.2.4.2. minCost = cost
1.1.2.5. Кладем медоид на место (в m)
1.1.3. Если наилучшая замена из s улучшает функцию потерь:
1.1.3.1. Производим эту замену
1.1.3.2. StableSequence = 0
1.1.4. Иначе:
1.1.4.1. StableSequence += 1
1.1.4.2. Если StableSequence > порога:
1.1.4.2.1. Возвращаем текущую конфигурацию
23. k-medoids: clara
• «Bagging» для кластеризации графов
• Выбирается случайная подвыборка и кластеризуется
• Оставшиеся узлы просто присоединяются в самом конце к
ближайшим медоидам
• Прогоняется несколько раз, и выбирается лучший вариант
• Ускорение только при сложности выше O(n)
• У PAM сложность O(k * n^2 * число_итераций)
• У новой эвристики сложность O(k * n * s * число итераций)
24. k-medoids для сегментов
DMP
• Строим граф доменов
• Данные: выборка пользователей, для каждого — set посещенных
доменов
• Пусть U_x — юзеры, посетившие домен x
• Вес ребра между доменами x и y:
• Отсечение шумов:
1. Порог для вершин (доменов) — хотя бы 15 посещений
2. Порог для ребер — аффинити хотя бы 20
affinity(x, y) =
|Ux ∩ Uy||U|
|Ux||Uy|
=
ˆp(x, y)
ˆp(x)ˆp(y)
25. Сколько данных? Сколько
кластеров?
• 30000 юзеров дают около 1200 доменов
и около 12 интерпретируемых сообществ
• 500000 юзеров: 10000 доменов, около 30
сообществ
26. Интерпретация картинки
• Размер узла — число посещений
• Цвет узла — сообщество
• Цвет ребра = цвету сообщества, если
оно внутреннее, иначе серый
• Толщина ребра — аффинити
• Для networkx слишком сложно!
• Недостатки визуализации в networkx:
1. Негибкая
2. Неинтерактивная
3. Неустойчивая
4. Медленная
• По возможности пользуйтесь graph-
tool!
33. Предобработка: Local
Sparsification
• Прореживаем граф, сохраняя структуру сообществ
• Алгоритмы быстрее, картинки красивее
• Вариант 1: Сортируем всех соседей по мере Жаккарда по
убыванию и удаляем хвост
• Плохо: плотные сообщества останутся нетронутыми, а
разреженные уничтожатся совсем
• Вариант 2: Для каждой вершины сортируем соседей и
оставляем ребер
• d_i — степень i, e от 0 до 1. При e=0,5 прорежение в 10 раз
• Сохраняется power law, почти сохраняется связность!
min{1,de
i }
35. Стабильные ядра
• Рандомизированные алгоритмы
нестабильны
• Разные прогоны — разные
результаты
• Добавление / удаление 2% узлов
может полностью поменять
кластеризацию
• Стабильные ядра: запускаем
алгоритм 100 раз и считаем
долю, сколько раз каждая пара
вершин попала в один и тот же
кластер
• Иерархическая кластеризация на
результате
36. Louvain
• Blondel et al, 2008
• Самый яркий представитель modularity-based алгоритмов
• Многоуровневые сообщества
• Очень быстрый
1. Инициализация: все вершины отдельно (n сообществ по 1 вершине)
2. Итеративно объединяем пары сообществ, дающих наибольший прирост
модулярности
3. Когда прирост закончится, представляем каждое сообщество как 1 узел в
новом графе
4. Повторяем пп. 2-3, пока не останется 2 сообщества
37. Louvain: иллюстрация
• Бельгийский мобильный
оператор
• 2,6 млн клиентов
• 260 сообществ больше
100 клиентов, 36 —
больше 10000
• 6 уровней сообществ
• Французский и
голландский сегменты
почти не соприкасаются
38. MCL
• Markov Cluster Algorithm (van Dongen, 1997-2000)
• Нормируем столбцы матрицы смежности:
• «Доля денег для каждого друга» или «Вероятность перехода случайного
блуждания»
• Итеративно повторяем 3 шага:
• Expand:
• Inflate: (больше r — больше кластеров)
• Prune: Обнулять самые маленькие элементы в каждом столбце
• Повторять пока M не сойдется
• Сложность ~ n * d^2 на первую итерацию (следующие — быстрее)
a flow matrix M, the ith
column contains the flows out of nod
correspondingly the ith
row contains the in-flows. Note that wh
out-flows) sum to 1, the rows (or in-flows) are not required to
The most common way of deriving a column-stochastic tran
graph is to simply normalize the columns of the adjacency ma
M(i, j) =
A(i, j)
n
k=1 A(k, j)
In matrix notation, M := AD−1
, where D is the diagonal de
D(i, i) = n
j=1 A(j, i). We will refer to this particular transitio
29
Markov Clustering (MCL) Algorithm
next describe the Markov Clustering (MCL) algorithm for clustering graphs,
d by Stijn van Dongen [41], in some detail as it is relevant to understanding
n method.
MCL algorithm is an iterative process of applying two operators - expansion
flation - on an initial stochastic matrix M, in alternation, until convergence.
xpansion and inflation are operators that map the space of column-stochastic
s onto itself. Additionally, a prune step is performed at the end of each
n step in order to save memory. Each of these steps is defined below:
d: Input M , output Mexp.
Mexp = Expand(M)
def
= M ∗ M
column of Mexp can be interpreted as the final distribution of a random walk of
2 starting from vertex vi, with the transition probabilities of the random walk
y M. One can take higher powers of M instead of a square (corresponding to
andom walks), but this gets computationally prohibitive very quickly.
: Input M and inflation parameter r, output Minf .
ansion and inflation are operators that map the space of column-stochastic
onto itself. Additionally, a prune step is performed at the end of each
tep in order to save memory. Each of these steps is defined below:
Input M , output Mexp.
Mexp = Expand(M)
def
= M ∗ M
lumn of Mexp can be interpreted as the final distribution of a random walk of
tarting from vertex vi, with the transition probabilities of the random walk
M. One can take higher powers of M instead of a square (corresponding to
ndom walks), but this gets computationally prohibitive very quickly.
nput M and inflation parameter r, output Minf .
Minf (i, j)
def
=
M(i, j)r
n
k=1 M(k, j)r
esponds to raising each entry in the matrix M to the power r and then
ng the columns to sum to 1. By default r = 2. Because the entries in the
e all guaranteed to be less than or equal to 1, this operator has the effect of
ing the inhomogeneity in each column (as long as r > 1). In other words,
39. MCL: пример
ging to one cluster.
y example
simple example of the MCL process in action for the graph in Fig-
initial stochastic matrix M0 obtained by adding self-loops to the graph
ng each column is given below
M0 =
⎛
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎝
0.33 0.33 0.25 0 0 0
0.33 0.33 0.25 0 0 0
0.33 0.33 0.25 0.25 0 0
0 0 0.25 0.25 0.33 0.33
0 0 0 0.25 0.33 0.33
0 0 0 0.25 0.33 0.33
⎞
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎠
32
t of applying one iteration of Expansion, Inflation and the Prune steps
w:
M1 =
⎛
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎝
0.33 0.33 0.2763 0 0 0
0.33 0.33 0.2763 0 0 0
0.33 0.33 0.4475 0 0 0
0 0 0 0.4475 0.33 0.33
0 0 0 0.2763 0.33 0.33
0 0 0 0.2763 0.33 0.33
⎞
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎠
e flow along the lone inter-cluster edge (M0(4, 3)) has evaporated to 0.
e more iteration results in convergence.
⎛
0 0 0 0 0 0
⎞
The result of applying one iteration of Expansion, Inflation and the P
is given below:
M1 =
⎛
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎝
0.33 0.33 0.2763 0 0 0
0.33 0.33 0.2763 0 0 0
0.33 0.33 0.4475 0 0 0
0 0 0 0.4475 0.33 0.33
0 0 0 0.2763 0.33 0.33
0 0 0 0.2763 0.33 0.33
⎞
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎠
Note that the flow along the lone inter-cluster edge (M0(4, 3)) has evapo
Applying one more iteration results in convergence.
M2 =
⎛
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎜
⎝
0 0 0 0 0 0
0 0 0 0 0 0
1 1 1 0 0 0
0 0 0 1 1 1
0 0 0 0 0 0
0 0 0 0 0 0
⎞
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎟
⎠
Hence, vertices 1, 2 and 3 flow completely to vertex 3, where as the vertic
6 flow completely to vertex 4. Hence, we group 1, 2 and 3 together with 3
“attractor” of the cluster, and similarly for 4, 5 and 6.
41. MCL: проблемы и решения
• Проблемы:
• Слишком много кластеров
• Уменьшение «learning rate» r: меньше кластеров, но медленнее
работает
• Несбалансированные кластеры: один огромный и куча по 2-3 вершины
• Все дело в переобучении!
• Стараемся, чтобы распределение потока из соседних вершин было
похожим
• «Регуляризация» (R-MCL): Mexp = M ∗ M0
42. SCD: шаг 1
• Приближенная максимизация WCC
• Сначала считаем треугольники
• Удаляем все ребра, не формирующие
треугольников
• Грубое разбиение (algorithm 1):
1. Сортируем вершины по локальному
кластерному коэффициенту
2. Первое сообщество: Первая вершина + все
ее соседи
3. Второе сообщество: Первая вершина из
оставшихся (еще не посещенных) + все ее
соседи
4. …
• Сложность: O(n*d^2 + n*log(n))
43. SCD: шаг 2
• Итеративно улучшаем результат
algorithm 1, пока WCC не перестанет
улучшаться (algorithm 2)
• Для каждой вершины ищем
bestMovement (MapReduce)
• bestMovement: добавить / удалить /
переместить
• Выполняем bestMovement
одновременно для всех вершин
• Сложность: О(1) на один
bestMovement, O(d+1) для одной
вершины, O(m) — для всего графа
• Весь алгоритм: O(m*log(n))
45. Spinner
• На основе label propagation
• Реализовано в Okapi (Mahout) компанией Telefonica
• Симметризуем исходный граф D: вес w(u,v) = 1, если ребро было
в одну сторону, и 2, если в обе.
• Регулируем баланс: задаем максимальное число ребер,
возможное в сообществе (с можно менять от 1 до 10-15):
• Загруженность сообщества l — текущее количество ребер в
сообществе l:
• Относительная загруженность:
• Заранее задаем число кластеров k, как в k-medoids; c = 1, …, k.
• Какой лейбл присвоить вершине v? Тот, который чаще
встречается среди соседей v:
• Поправка на сбалансированность:
p the current label if it is among them.
s convergence speed [6], and in our dis-
uces unnecessary network communica-
lgorithm halts when no vertex updates
ormulation of LPA assumes undirected
en graphs are directed (e.g. the Web).
stems like Pregel allow directed graphs,
re aware of graph directness, like PageR-
would need to convert a graph to undi-
would be to create an undirected edge
henever at least one directed edge exists
he directed graph.
agnostic to the communication patterns
on top. Consider the example graph in
tition to 3 parts. In the undirected graph
cut edges. At this point, according to the
agnostic of the directness of the original
ertex to another partition is as likely, and
dge less.
the directness of the edges in the orig-
ns are equally beneficial. In fact, either
n 1 or vertex 1 to partition 3 would in
edges in the directed graph. Once the
stem and messages are sent across the
decision results in less communication
straint, only encouraging a similar number of edges across
ferent partitions. As we will show, this decision allows a fu
centralized algorithm. While in this work we focus on the pr
tion and evaluation of the more system-related aspects of S
we plan to investigate theoretical justifications and guarant
hind our approach in future work.
Here, we consider the case of a homogeneous system,
each machine has equal resources. This setup is often pr
in synchronous graph processing systems like Pregel, to m
the time spent by faster machines waiting at the synchron
barrier for stragglers.
We define the capacity C of a partition as the maximum
of edges it can have so that partitions are balanced:
C = c·
|E|
k
Parameter c > 1 ensures additional capacity to each part
available for migrations. We define the load of a partition
actual number of edges in that partition:
B(l) = Â
v2G
deg(v)d(a(v),l)
A larger value of c increases the number of migrations
partition allowed at each iteration, possibly speeding up
gence, but it may increase unbalance, as more edges are allo
be assigned to each partition over the ideal value
|E|
.
entation reduces unnecessary network communica-
n 4). The algorithm halts when no vertex updates
e original formulation of LPA assumes undirected
er, very often graphs are directed (e.g. the Web).
models of systems like Pregel allow directed graphs,
ithms that are aware of graph directness, like PageR-
A as is, we would need to convert a graph to undi-
ve approach would be to create an undirected edge
s u and v whenever at least one directed edge exists
u and v in the directed graph.
h, though, is agnostic to the communication patterns
ons running on top. Consider the example graph in
e want to partition to 3 parts. In the undirected graph
e initially 3 cut edges. At this point, according to the
n, which is agnostic of the directness of the original
ation of a vertex to another partition is as likely, and
e one cut edge less.
we consider the directness of the edges in the orig-
all migrations are equally beneficial. In fact, either
2 to partition 1 or vertex 1 to partition 3 would in
e less cut edges in the directed graph. Once the
into the system and messages are sent across the
this latter decision results in less communication
k.
centralized algorithm. While in this work we focus o
tion and evaluation of the more system-related aspe
we plan to investigate theoretical justifications and
hind our approach in future work.
Here, we consider the case of a homogeneous
each machine has equal resources. This setup is o
in synchronous graph processing systems like Prege
the time spent by faster machines waiting at the s
barrier for stragglers.
We define the capacity C of a partition as the max
of edges it can have so that partitions are balanced:
C = c·
|E|
k
Parameter c > 1 ensures additional capacity to ea
available for migrations. We define the load of a p
actual number of edges in that partition:
B(l) = Â
v2G
deg(v)d(a(v),l)
A larger value of c increases the number of mig
partition allowed at each iteration, possibly speed
gence, but it may increase unbalance, as more edges
be assigned to each partition over the ideal value
|E|
k
3
We introduce a penalty function to discourage assigning vertices
to nearly full partitions. Given a partition indicated by label l, the
penalty function p(l) is defined as follows:
p(l) =
B(l)
C
(7)
To integrate the penalty function we normalize (4) first, and re-
formulate the score function as follows:
score00
(v,l) = Â
u2N(v)
w(u,v)d(a(u),l)
Âu2N(v) w(u,v)
p(l) (8)
3.3 Convergence and Halting
is to “push” the cu
it converged to, tow
sult, we restart the
look for a new loca
score, possibly dec
rithm continues as
concerned, we assi
The number of
state depends on th
Clearly, not every
times, no iteration
may not affect any
We introduce a penalty function to discourage assigning vertices
to nearly full partitions. Given a partition indicated by label l, the
penalty function p(l) is defined as follows:
p(l) =
B(l)
C
(7)
To integrate the penalty function we normalize (4) first, and re-
formulate the score function as follows:
score00
(v,l) = Â
u2N(v)
w(u,v)d(a(u),l)
Âu2N(v) w(u,v)
p(l) (8)
is
it
s
lo
s
r
c
s
C
ti
V is the set of vertices in the graph and E is the set of
that an edge e 2 E is a pair (u,v) with u,v 2 V. We
N(v) = {u: u 2 V,(u,v) 2 E} the neighborhood of a ve
by deg(v) = |N(v)| the degree of v. In a k-way partit
define L as a set of labels L = {l1,...,lk} that essentially c
to the k partitions. a is the labeling function a : V ! L
a(v) = lj if label lj is assigned to vertex v.
The end goal of Spinner is to assign partitions, or labe
vertex such that it maximizes edge locality and partitio
anced.
3.1 K-way Label Propagation
We first describe how to use basic LPA to maximize ed
and then extend the algorithm to achieve balanced part
tially, each vertex in the graph is assigned a label li at ran
0 < i k. Subsequently, every vertex iteratively propag
bel to its neighbors. During this iterative process, a verte
the label that is more frequent among its neighbors. Eve
assigns a different score for a particular label l which is e
number of neighbors assigned to label l. A vertex shows
to labels with high score. More formally:
score(v,l) = Â
u2N(v)
d(a(u),l)
where d is the Kronecker delta. The vertex updates its l
label lv that maximizes its score according to the update
46. Spinner: Масштабируемость
• Вычисление в парадигме Pregel — идеально для label propagation
• Легко добавлять / убирать кластеры (1 кластер — один воркер)
• Легко пересчитывать при добавлении / удалении узлов
• Масштабируемость Spinner при кластеризации случайного графа (Watts-Strogatz):
• Экономия ресурсов при добавлении новых ребер или новых ссобществ (воркеров):
(a) Partitioning of the Twitter graph. (b) Partitioning of the Yahoo! graph.
Figure 4: Partitioning of (a) the Twitter graph across 256 partitions and (b) the Yahoo! web graph across 115 partitions. The figure
shows the evolution of metrics f, r, and score(G) across iterations.
(a) Runtime vs. graph size (b) Runtime vs. cluster size (c) Runtime vs. k
Figure 5: Scalability of Spinner. (a) Runtime as a function of the number of vertices, (b) runtime as a function of the number of
workers, (c) runtime as a function of the number of partitions.
supersteps. This approach allows us to factor out the runtime of al-
gorithm as a function the number of vertices and edges.
Figure 5.2 presents the results of the experiments, executed on
a AWS Hadoop cluster consisting of 116 m2.4xlarge machines. In
the first experiment, presented in Figure 5(a), we focus on the scal-
ability of the algorithm as a function of the number of vertices and
edges in the graph. For this, we fix the number of outgoing edges
per vertex to 40. We connect the vertices following a ring lattice
topology, and re-wire 30% of the edges randomly as by the func-
tion of the beta (0.3) parameter of the Watts-Strogatz model. We
execute each experiment with 115 workers, for an exponentially
increasing number of vertices, precisely from 2 to 1024 million
vertices (or one billion vertices) and we divide each graph in 64
partitions. The results, presented in a loglog plot, show a linear
trend with respect to the size of the graph. Note that for the first
data points the size of the graph is too small for such a large clus-
ter, and we are actually measuring the overhead of Giraph.
(a) Cost savings (b) Partitioning stability
Figure 6: Adapting to dynamic graph changes. We vary the
percentage of new edges in the graph and compare our adap-
tive re-partitioning approach and re-partitioning from scratch
with respect to (a) the savings in processing time and messages
exchanged, and (b) the fraction of vertices that have to move
upon re-partitioning.
(b) Partitioning of the Yahoo! graph.
ns and (b) the Yahoo! web graph across 115 partitions. The figure
s.
vs. cluster size (c) Runtime vs. k
he number of vertices, (b) runtime as a function of the number of
(a) Cost savings (b) Partitioning stability
Figure 6: Adapting to dynamic graph changes. We vary the
(a) Cost savings (b) Partitioning stability
Figure 7: Adapting to resource changes. We vary the num-
o
t
m
A
t
o
f
p
s
47. Инструменты
• NetworkX: клики, k-cores, blockmodels
• graph-tool: очень быстрый blockmodels, визуализация
• okapi (mahout): k-cores, Spinner
• GraphX (spark): пока ничего
• Gephi: MCL, Girvan-Newman, Chinese Whispers
• micans.org : MCL от создателя
• mapequation.org : Infomap
• sites.google.com/site/findcommunities/ : Louvain от создателей (C++)
• pycluster (coming soon): k-medoids
48. Литература
• Mining of Massive Datasets (ch.10 «Mining social
networks graphs», pp 343-402)
• Data Clustering Algorithms and Applications (ch 17
«Network clustering», pp 415-443)
• Курс на Coursera по SNA: www.coursera.org/course/sna
• Отличный обзор по нахождению сообществ:
snap.stanford.edu/class/cs224w-readings/
fortunato10community.pdf
• Статьи с разобранными методами и кейсами с ними
(пришлю)