-
Notifications
You must be signed in to change notification settings - Fork 254
Expand file tree
/
Copy pathnode2vec.py
More file actions
198 lines (156 loc) · 8.39 KB
/
node2vec.py
File metadata and controls
198 lines (156 loc) · 8.39 KB
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
import os
import random
from collections import defaultdict
import gensim
import networkx as nx
import numpy as np
from .check_gensim import is_dated_gensim_version
from joblib import Parallel, delayed
from tqdm.auto import tqdm
from .parallel import parallel_generate_walks
class Node2Vec:
FIRST_TRAVEL_KEY = 'first_travel_key'
PROBABILITIES_KEY = 'probabilities'
NEIGHBORS_KEY = 'neighbors'
WEIGHT_KEY = 'weight'
NUM_WALKS_KEY = 'num_walks'
WALK_LENGTH_KEY = 'walk_length'
P_KEY = 'p'
Q_KEY = 'q'
def __init__(self, graph: nx.Graph, dimensions: int = 128, walk_length: int = 80, num_walks: int = 10, p: float = 1,
q: float = 1, weight_key: str = 'weight', workers: int = 1, sampling_strategy: dict = None,
quiet: bool = False, temp_folder: str = None, seed: int = None):
"""
Initiates the Node2Vec object, precomputes walking probabilities and generates the walks.
:param graph: Input graph
:param dimensions: Embedding dimensions (default: 128)
:param walk_length: Number of nodes in each walk (default: 80)
:param num_walks: Number of walks per node (default: 10)
:param p: Return hyper parameter (default: 1)
:param q: Inout parameter (default: 1)
:param weight_key: On weighted graphs, this is the key for the weight attribute (default: 'weight')
:param workers: Number of workers for parallel execution (default: 1)
:param sampling_strategy: Node specific sampling strategies, supports setting node specific 'q', 'p', 'num_walks' and 'walk_length'.
:param seed: Seed for the random number generator.
Use these keys exactly. If not set, will use the global ones which were passed on the object initialization
:param temp_folder: Path to folder with enough space to hold the memory map of self.d_graph (for big graphs); to be passed joblib.Parallel.temp_folder
"""
self.graph = graph
self.dimensions = dimensions
self.walk_length = walk_length
self.num_walks = num_walks
self.p = p
self.q = q
self.weight_key = weight_key
self.workers = workers
self.quiet = quiet
self.d_graph = defaultdict(dict)
if sampling_strategy is None:
self.sampling_strategy = {}
else:
self.sampling_strategy = sampling_strategy
self.temp_folder, self.require = None, None
if temp_folder:
if not os.path.isdir(temp_folder):
raise NotADirectoryError("temp_folder does not exist or is not a directory. ({})".format(temp_folder))
self.temp_folder = temp_folder
self.require = "sharedmem"
if seed is not None:
random.seed(seed)
np.random.seed(seed)
self._precompute_probabilities()
self.walks = self._generate_walks()
def _precompute_probabilities(self):
"""
Precomputes transition probabilities for each node.
"""
d_graph = self.d_graph
nodes_generator = self.graph.nodes() if self.quiet \
else tqdm(self.graph.nodes(), desc='Computing transition probabilities')
for source in nodes_generator:
# Init probabilities dict for first travel
if self.PROBABILITIES_KEY not in d_graph[source]:
d_graph[source][self.PROBABILITIES_KEY] = dict()
for current_node in self.graph.neighbors(source):
# Init probabilities dict
if self.PROBABILITIES_KEY not in d_graph[current_node]:
d_graph[current_node][self.PROBABILITIES_KEY] = dict()
unnormalized_weights = list()
d_neighbors = list()
# Calculate unnormalized weights
for destination in self.graph.neighbors(current_node):
p = self.sampling_strategy[current_node].get(self.P_KEY,
self.p) if current_node in self.sampling_strategy else self.p
q = self.sampling_strategy[current_node].get(self.Q_KEY,
self.q) if current_node in self.sampling_strategy else self.q
try:
if self.graph[current_node][destination].get(self.weight_key):
weight = self.graph[current_node][destination].get(self.weight_key, 1)
else:
## Example : AtlasView({0: {'type': 1, 'weight':0.1}})- when we have edge weight
edge = list(self.graph[current_node][destination])[-1]
weight = self.graph[current_node][destination][edge].get(self.weight_key, 1)
except:
weight = 1
if destination == source: # Backwards probability
ss_weight = weight * 1 / p
elif destination in self.graph[source]: # If the neighbor is connected to the source
ss_weight = weight
else:
ss_weight = weight * 1 / q
# Assign the unnormalized sampling strategy weight, normalize during random walk
unnormalized_weights.append(ss_weight)
d_neighbors.append(destination)
# Normalize
unnormalized_weights = np.array(unnormalized_weights)
d_graph[current_node][self.PROBABILITIES_KEY][
source] = unnormalized_weights / unnormalized_weights.sum()
# Calculate first_travel weights for source
first_travel_weights = []
for destination in self.graph.neighbors(source):
first_travel_weights.append(self.graph[source][destination].get(self.weight_key, 1))
first_travel_weights = np.array(first_travel_weights)
d_graph[source][self.FIRST_TRAVEL_KEY] = first_travel_weights / first_travel_weights.sum()
# Save neighbors
d_graph[source][self.NEIGHBORS_KEY] = list(self.graph.neighbors(source))
def _generate_walks(self) -> list:
"""
Generates the random walks which will be used as the skip-gram input.
:return: List of walks. Each walk is a list of nodes.
"""
flatten = lambda l: [item for sublist in l for item in sublist]
# Split num_walks for each worker
num_walks_lists = np.array_split(range(self.num_walks), self.workers)
walk_results = Parallel(n_jobs=self.workers, temp_folder=self.temp_folder, require=self.require)(
delayed(parallel_generate_walks)(self.d_graph,
self.walk_length,
len(num_walks),
idx,
self.sampling_strategy,
self.NUM_WALKS_KEY,
self.WALK_LENGTH_KEY,
self.NEIGHBORS_KEY,
self.PROBABILITIES_KEY,
self.FIRST_TRAVEL_KEY,
self.quiet) for
idx, num_walks
in enumerate(num_walks_lists, 1))
walks = flatten(walk_results)
return walks
def fit(self, **skip_gram_params) -> gensim.models.Word2Vec:
"""
Creates the embeddings using gensim's Word2Vec.
:param skip_gram_params: Parameters for gensim.models.Word2Vec - do not supply 'size' / 'vector_size' it is
taken from the Node2Vec 'dimensions' parameter
:type skip_gram_params: dict
:return: A gensim word2vec model
"""
if 'workers' not in skip_gram_params:
skip_gram_params['workers'] = self.workers
# Figure out gensim version, naming of output dimensions changed from size to vector_size in v4.0.0
size = 'size' if is_dated_gensim_version() else 'vector_size'
if size not in skip_gram_params:
skip_gram_params[size] = self.dimensions
if 'sg' not in skip_gram_params:
skip_gram_params['sg'] = 1
return gensim.models.Word2Vec(self.walks, **skip_gram_params)