mercury.graph.ml
mercury.graph.ml.LouvainCommunities(min_modularity_gain=0.001, max_pass=2, max_iter=10, resolution=1, all_partitions=True, verbose=True)
Bases: BaseClass
Class that defines the functions that run a PySpark implementation of the Louvain algorithm to find the partition that maximizes the modularity of an undirected graph (as in 1).
This version of the algorithm differs from 1 in that the reassignment of nodes to new communities is calculated in parallel, not sequentially. That is, all nodes are reassigned at the same time and conflicts (i.e., 1 -> C2 and 2 -> C1) are resolved with a simple tie-breaking rule. This version also introduces the resolution parameter gamma, as in 2.
Contributed by Arturo Soberon Cedillo, Jose Antonio Guzman Vazquez and Isaac Dodanim Hernandez Garcia.
-
Blondel V D, Guillaume J-L, Lambiotte R and Lefebvre E (2008). Fast unfolding of communities in large networks. Journal of Statistical Mechanics: Theory and Experiment, 2008. https://doi.org/10.1088/1742-5468/2008/10/p10008 ↩↩
-
Aynaud T, Blondel V D, Guillaume J-L and Lambiotte R (2013). Multilevel local optimization of modularity. Graph Partitioning (315--345), 2013. ↩
Parameters:
Name | Type | Description | Default |
---|---|---|---|
min_modularity_gain
|
float
|
Modularity gain threshold between each pass. The algorithm stops if the gain in modularity between the current pass and the previous one is less than the given threshold. |
0.001
|
max_pass
|
int
|
Maximum number of passes. |
2
|
max_iter
|
int
|
Maximum number of iterations within each pass. |
10
|
resolution
|
float
|
The resolution parameter gamma. Its value must be greater or equal to zero. If resolution is less than 1, modularity favors larger communities, while values greater than 1 favor smaller communities. |
1
|
all_partitions
|
bool
|
If True, the function will return all the partitions found at each step of the algorithm (i.e., pass0, pass1, pass2, ..., pass20). If False, only the last (and best) partition will be returned. |
True
|
verbose
|
bool
|
If True, print progress information during the Louvain algorithm execution. Defaults to True. |
True
|
Source code in mercury/graph/ml/louvain.py
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
|
_calculate_m(edges)
Get the weighted size of an undirected graph (where \(m\) is defined as \(m = \frac{1}{2} \sum_{ij} A_{ij}\))).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
edges
|
DataFrame
|
A pyspark dataframe representing the edges of an undirected graph.
It must have |
required |
Returns:
Type | Description |
---|---|
int
|
Returns the weighted size of the graph. |
Source code in mercury/graph/ml/louvain.py
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
|
_calculate_modularity(edges, partition, m=None)
This function calculates the modularity of a partition.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
edges
|
DataFrame
|
A pyspark dataframe representing the edges of an undirected graph.
It must have |
required |
partition
|
DataFrame
|
A pyspark dataframe representing the partition of an undirected
graph (i.e., a table that indicates the community that each node
belongs to). The dataframe must have columns |
required |
m
|
int
|
The weighted size of the graph (the output of |
None
|
Returns:
Type | Description |
---|---|
float
|
Bound between -1 and 1 representing the modularity of a
partition. The output may exceed these bounds depending on the value of
|
Source code in mercury/graph/ml/louvain.py
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 |
|
_label_degrees(edges, partition)
This function uses the edges of a graph to calculate the weighted degrees of each node and joins the result with the partition passed by the user.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
edges
|
DataFrame
|
A pyspark dataframe representing the edges of an undirected graph.
It must have |
required |
partition
|
DataFrame
|
A pyspark dataframe representing the partition of an undirected
graph (i.e., a table that indicates the community that each node
belongs to). The dataframe must have columns |
required |
Returns:
Type | Description |
---|---|
Dataframe
|
This function returns a dataframe with columns |
Source code in mercury/graph/ml/louvain.py
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 |
|
_label_edges(edges, partition)
This function uses partition
to add two columns to edges
. The added
columns cSrc
and cDst
indicate the community that the source and
destination nodes belong to.
Args:
edges (pyspark.sql.dataframe.DataFrame):
A pyspark dataframe representing the edges of an undirected graph.
It must have `src` and `dst` as its columns. The user may also
specify the weight of each edge via the additional `weight` column
(optional).
partition (pyspark.sql.dataframe.DataFrame):
A pyspark dataframe representing the partition of an undirected
graph (i.e., a table that indicates the community that each node
belongs to). The dataframe must have columns `id` (indicating each
node's ID) and `c` (indicating each node's assigned community).
Returns:
Type | Description |
---|---|
DataFrame
|
This function returns |
Source code in mercury/graph/ml/louvain.py
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 |
|
_last_pass(df)
Returns the column name of the last pass.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df
|
DataFrame
|
A pyspark dataframe representing the series of partitions made by
|
required |
Source code in mercury/graph/ml/louvain.py
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
|
_reassign_all(edges, partition, m=None)
This function simultaneously reassigns all the nodes in a graph to their corresponding optimal neighboring communities.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
edges
|
DataFrame
|
A pyspark dataframe representing the edges of an undirected graph.
It must have |
required |
partition
|
DataFrame
|
A pyspark dataframe representing the partition of an undirected
graph (i.e., a table that indicates the community that each node
belongs to). The dataframe must have columns |
required |
m
|
int
|
The weighted size of the graph (the output of |
None
|
Returns:
Type | Description |
---|---|
DataFrame
|
A pyspark dataframe with the same number of rows as there are vertices.
Columns |
Source code in mercury/graph/ml/louvain.py
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 |
|
_sort_passes(res)
Takes the output of LouvainCommunities
and returns a list containing
its columns ordered by their integer part in ascending order.
For example, if the columns returned by LouvainCommunities are
['pass2', 'id', 'pass1', 'pass0'], this function will turn the list to
['id', 'pass0', 'pass1', 'pass2'].
This function also supports cases where
max_pass > 10`.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
res
|
DataFrame
|
A pyspark dataframe representing the output of |
required |
Source code in mercury/graph/ml/louvain.py
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 |
|
_verify_data(df, expected_cols_grouping, expected_cols_others)
Checks if edges
meets the format expected by LouvainCommunities
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
df
|
DataFrame
|
A pyspark dataframe representing the edges of an undirected graph.
It must have |
required |
expected_cols_grouping
|
list
|
A list of strings representing the columns that must be present in
|
required |
expected_cols_others
|
list
|
A list of strings representing the columns that must be present in
|
required |
Source code in mercury/graph/ml/louvain.py
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 |
|
fit(g)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
g
|
Graph
|
A mercury graph structure. |
required |
Returns:
Type | Description |
---|---|
self
|
Fitted self (or raises an error). |
Source code in mercury/graph/ml/louvain.py
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 |
|
mercury.graph.ml.SparkRandomWalker(num_epochs=10, batch_size=1, n_sampling_edges=None)
Bases: BaseClass
Class to perform random walks from a specific source_id node within a given Graph
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_epochs
|
int
|
Number of epochs. This is the total number of steps the iteration goes through. |
10
|
batch_size
|
int
|
This forces caching the random walks computed so far and breaks planning each time this number of epochs is reached. The default value is a high number to avoid this entering at all. In really large jobs, you may want to set this parameter to avoid possible overflows even if it can add some extra time to the process. Note that with a high number of epochs and nodes resource requirements for the active part of your random walks can be high. This allows to "cache a continue" so to say. |
1
|
n_sampling_edges
|
int
|
by setting this parameter you can limit at each timestep the number of new paths opened from each node.
This is useful when the graph contains nodes with very high out-degree, where running the algorithm several epochs is
not feasible. When using this parameter, the graph will consider only at most |
None
|
Source code in mercury/graph/ml/spark_randomwalker.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
fit(G, source_id)
Perform random walks from a specific source_id node within a given Graph
Parameters:
Name | Type | Description | Default |
---|---|---|---|
G
|
mercury.graph Graph asset
|
A |
required |
source_id
|
int / str / list
|
the source vertex or list for vertices to start the random walks. |
required |
Returns:
Type | Description |
---|---|
self
|
Fitted self (or raises an error) |
Attribute paths_
contains a Spark Dataframe with a columns random_walks
containing an array of the elements
of the path walked and another column with the corresponding weights. The weights represent the probability of
following that specific path starting from source_id.
Source code in mercury/graph/ml/spark_randomwalker.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
|
mercury.graph.ml.SparkSpreadingActivation(attribute='influence', spreading_factor=0.2, transfer_function='weighted', steps=1, influenced_by=False)
Bases: BaseClass
This class is a model that represents a “word-of-mouth” scenario where a node influences his neighbors, from where the influence spreads to other neighbors, and so on.
At the end of the diffusion process, we inspect the amount of influence received by each node. Using a threshold-based technique, a node that is currently not influenced can be declared to be a potential future one, based on the influence that has been accumulated.
The diffusion model is based on Spreading Activation (SPA) techniques proposed in cognitive psychology and later used for trust metric computations. For more details, please see paper entitled "Social Ties and their Relevance to Churn in Mobile Telecom Networks"
Parameters:
Name | Type | Description | Default |
---|---|---|---|
attribute
|
str
|
Column name which will store the amount of influence spread |
'influence'
|
spreading_factor
|
float
|
Percentage of influence to distribute. Low values favor influence proximity to the source of injection, while high values allow the influence to also reach nodes which are further away. It must be a value in the range (0,1). Default value is 0.2 |
0.2
|
transfer_function
|
str
|
Allowed values: "weighted" or "unweighted".
Once a node decides what fraction of energy to distribute, the next step is to decide what fraction of the energy is transferred
to each neighbor. This is controlled by the Transfer Function. If "weighted" then the energy distributed along the directed
edge |
'weighted'
|
steps
|
int
|
Number of steps to perform |
1
|
influenced_by
|
bool
|
if True, and extra column "influenced_by" is calculated which contains the seed nodes that have spread some influence to a given node. When True, the ids of the nodes cannot contain commas ",". Note that seed_nodes will have at least their own (remaining) influence |
False
|
Source code in mercury/graph/ml/spark_spreadactivation.py
63 64 65 66 67 68 69 70 71 72 73 74 75 |
|
_compute_degrees(g)
Compute weighted and unweighted in and out degrees in graph. Re-declares graph to add the following attributes: inDegree, outDegree, w_inDegree, w_outDegree.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
g
|
Graph
|
graphframe object, network |
required |
Source code in mercury/graph/ml/spark_spreadactivation.py
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 |
|
_set_seed_nodes(g, seed_nodes=None)
Set seed nodes which are the source of influence using pyspark dataframe.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
g
|
Graph
|
A |
required |
seed_nodes
|
Union[List, DataFrame]
|
Collection of nodes that are the source to spread the influence. It must be pyspark dataframe with column 'id' or python list. |
None
|
Source code in mercury/graph/ml/spark_spreadactivation.py
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 |
|
_spread_activation_step(g)
One step in the spread activation model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
g
|
Graph
|
graphframe object, network |
required |
Returns:
Type | Description |
---|---|
Graphframe
|
new network with updated new calculation of attribute in vertices |
Source code in mercury/graph/ml/spark_spreadactivation.py
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 |
|
fit(g, seed_nodes)
Perform all iterations of spread_activation
Parameters:
Name | Type | Description | Default |
---|---|---|---|
g
|
Graph
|
A |
required |
seed_nodes
|
Union[List, DataFrame]
|
Collection of nodes that are the "seed" or are the source to spread the influence. It must be pyspark dataframe with column 'id' or python list |
required |
Returns:
Type | Description |
---|---|
self
|
Fitted self |
Source code in mercury/graph/ml/spark_spreadactivation.py
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 |
|
mercury.graph.ml.SpectralClustering(n_clusters=2, mode='networkx', max_iterations=10, random_state=0)
Bases: BaseClass
Implementation of the spectral clustering algorithm which detect communities inside a graph.
Contributed by Gibran Gabriel Otazo Sanchez.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
n_clusters
|
int
|
The number of clusters that you want to detect. |
2
|
random_state
|
int
|
Seed for reproducibility |
0
|
mode
|
str
|
Calculation mode. Pass 'networkx' for using pandas + networkx or 'spark' for spark + graphframes |
'networkx'
|
max_iterations
|
int
|
Max iterations parameter (only used if mode==spark) |
10
|
Source code in mercury/graph/ml/spectral.py
32 33 34 35 36 37 38 39 40 41 |
|
_fit_networkx(graph)
Spectral clustering but using networkx (local mode implementation)
Parameters:
Name | Type | Description | Default |
---|---|---|---|
graph
|
Graph
|
A mercury graph structure. |
required |
Returns:
Type | Description |
---|---|
self
|
Fitted self (or raises an error) |
Source code in mercury/graph/ml/spectral.py
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 |
|
_fit_spark(graph)
Spectral clustering but using pyspark
Parameters:
Name | Type | Description | Default |
---|---|---|---|
graph
|
Graph
|
A mercury graph structure. |
required |
Returns:
Type | Description |
---|---|
self
|
Fitted self (or raises an error) |
Source code in mercury/graph/ml/spectral.py
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 |
|
_spark_modularity(edges, degrees, resolution=1)
Computes modularity using the same approximation as networkx: https://networkx.org/documentation/stable/reference/algorithms/generated/networkx.algorithms.community.quality.modularity.html
Source code in mercury/graph/ml/spectral.py
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 |
|
fit(graph)
Find the optimal clusters of a given graph. The function returns nothing, but saves the clusters and the modularity in the object self.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
graph
|
Graph
|
A mercury graph structure. |
required |
Returns:
Type | Description |
---|---|
self
|
Fitted self (or raises an error) |
Source code in mercury/graph/ml/spectral.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
|
mercury.graph.ml.Transition()
Bases: BaseClass
Create an interface class to manage the adjacency matrix of a directed graph as a transition matrix. This enables computing distributions of probabilities over the nodes after a given number of iterations.
Source code in mercury/graph/ml/transition.py
18 19 |
|
fit(G)
Converts the adjacency matrix into a transition matrix. Transition matrices are used to compute the distribution of probability of being in each of the nodes (or states) of a directed graph (or Markov process). The distribution for state s is:
- \(s_t = T*s_{t-1}\)
Where:
T is the transition matrix. After calling.fit(), the adjacency matrix is the transition matrix. You can use .to_pandas() to see it. \(s_{t-1}\) is the previous state.
What .fit() does is scaling the non-zero rows to make them sum 1 as they are probability distributions and make the zero rows recurrent states. A recurrent state is a final state, a state whose next state is itself.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
G
|
Graph
|
A |
required |
Returns:
Type | Description |
---|---|
self
|
Fitted self (or raises an error). |
Note
If created using NetworkX directly, the name of the weight must be 'weight' and must be positive. The recommended way to create the graph is using .set_row() which will always name the weight as 'weight' but does not check the value.
Source code in mercury/graph/ml/transition.py
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 |
|
to_pandas(num_iterations=1)
Returns the adjacency (which is the transition matrix after fit()
was called) for a given number of iterations as a pandas
dataframe with labeled rows and columns.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
num_iterations
|
int
|
If you want to compute the matrix for a different number of iterations, k, you can use this argument to raise the matrix to any non negative integer, since \(s_{t+k} = T^k*s_t\) |
1
|
Returns:
Type | Description |
---|---|
DataFrame
|
The transition matrix for num_iterations. |
Note
This method does not automatically call fit()
. This allows inspecting the adjacency matrix as a pandas dataframe.
The result of computing num_iterations will not make sense if fit()
has not been called before to_pandas()
.
Source code in mercury/graph/ml/transition.py
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 |
|