Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

212 lines
9.1 KiB

  1. Graph algorithms!!!
  2. Working with graphs can be a great deal of fun, but sometimes we just want some cold hard vectors to do some good old-fashioned machine learning.
  3. This post looks at the famous [node2vec](https://cs.stanford.edu/~jure/pubs/node2vec-kdd16.pdf) algorithm used to quantize graph data.
  4. The example I'm giving in this blog post uses data from my recently resurrected [steam graph project](https://jrtechs.net/projects/steam-friends-graph).
  5. If you live under a rock, [Steam](https://store.steampowered.com/) is a platform where users can purchase, manage, and play games with friends.
  6. Although there is a ton of data within the Steam network, I am only interested in the graphs formed connecting users, friends, and games.
  7. My updated visualization to show a friendship network looks like this:
  8. ![media](media/steamNode2vec/friends.png)
  9. I'm also working on visualizations to show both friends and their games.
  10. ![media](media/steamNode2vec/games.png)
  11. The issue that I'm currently running into is that these graphs quickly become egregiously large. Players on Steam frequently have 100+ friends and own over 50 games-- one person I indexed somehow had over 400 games!
  12. The size of this graph balloons exponentially with traversal depth.
  13. The sheer scale of the graph data makes it challenging to visualize concisely.
  14. Visualization of graph data brings us to our topic today:
  15. # Node2Vec
  16. Node2Vec is an embedding algorithm inspired by [word2vec](https://jrtechs.net/data-science/word-embeddings).
  17. This algorithm aims to covert every node in a graph into a vectorized output where points close in the latent space correspond to related nodes.
  18. Simplifying a few things: node2vec uses the notion of a biased random walk through the graph.
  19. Two hyperparameters(P and Q) defines whether we want to favor a BFS vs. a DFS traversal. A BFS search will give us a better local view of the network, where a DFS traversal will provide us with a more global view of the graph. After applying some maths to the random walker outputs, distance in this embedding space is correlated to the probability that two nodes co-occur on the same random walk over the network.
  20. If you have the time, I urge you to watch [Jure Leskovec's](https://scholar.google.com/citations?user=Q_kKkIUAAAAJ&hl=en) Stanford lectures on graph learning on Youtube:
  21. <youtube src="YrhBZUtgG4E" />
  22. Additionally, if you want to dive deeper into graph learning, I suggest that you dig through the Stanford [CS-224 course page on Github](https://github.com/jrtechs/cs224w-notes).
  23. # Python Node2Vec Code
  24. I'm using a simple implementation of Node2Vec that I found on GitHub: [aditya-grover/node2vec](https://github.com/aditya-grover/node2vec).
  25. I'm using this package because it is a faithful implementation of the original paper and doesn't require you to install too many dependencies. This project was written in Python 2, so to get Python 3 support, you will need to merge in changes from someone's fork because the maintainer is not reviewing any of the pull requests.
  26. ```
  27. git clone https://github.com/aditya-grover/node2vec
  28. git remote add python3 https://github.com/mcwehner/node2vec
  29. git pull python3 master
  30. git pull python3 updated_requirements
  31. ```
  32. Pip makes installing the dependencies easy using a requirements file.
  33. ```python
  34. !pip install -r node2vec/requirements.txt
  35. ```
  36. Before we run this algorithm, we need to generate some data.
  37. An example edge list is in the [git repo](https://github.com/aditya-grover/node2vec/blob/master/graph/karate.edgelist).
  38. Using the JanusGraph database I'm using for the [Steam graphs project](https://github.com/jrtechs/SteamFriendsGraph), I generated an edge list of a single player's network.
  39. The code is straightforward; first, I pull the steam ids of the people we want in our embedding graph.
  40. Second, I pull all the friend connections for the people we want in the graph and filter out any players that are not already in the network.
  41. Finally, I take all the friend relationships and generate the edge pairs and save them to a file. If you are not familiar with Java's data streaming, I suggest that you check out my [last blog post on functional programming in Java](https://jrtechs.net/java/fun-with-functional-java).
  42. ```java
  43. Set<String> importantEdges = graph
  44. .getPlayer(baseID)
  45. .getFriends()
  46. .parallelStream()
  47. .map(Player::getId)
  48. .collect(Collectors.toSet());
  49. Map<String, Set<String>> edgeList = new HashMap<String, Set<String>>()
  50. {{
  51. importantEdges.forEach(f ->
  52. put(f,
  53. graph.getPlayer(f)
  54. .getFriends()
  55. .parallelStream()
  56. .map(Player::getId)
  57. .filter(importantEdges::contains)
  58. .collect(Collectors.toSet()))
  59. );
  60. }};
  61. List<String> edges = edgeList.keySet()
  62. .parallelStream().map(k ->
  63. edgeList.get(k)
  64. .stream()
  65. .map(k2 -> k + " " + k2)
  66. .collect(Collectors.toList()))
  67. .flatMap(Collection::stream)
  68. .collect(Collectors.toList());
  69. WrappedFileWriter.writeToFileFromList(edges, outFile);
  70. ```
  71. Using the edge list generated in the prior script, I feed it into the node2vec program.
  72. ```python
  73. !python node2vec/src/main.py --input jrtechs.edgelist --output output/jrtechs2.emd --num-walks=40 --dimensions=50
  74. output:
  75. Walk iteration:
  76. 1 / 40
  77. ...
  78. 40 / 40
  79. ```
  80. Once we have our embedding file, we can load it into Python to do machine learning or visualization.
  81. The node2vec algorithm's output is a sequence of lines where each line starts with the node label, and the rest of the line is the embedding vector.
  82. ```python
  83. labels=[]
  84. vectors=[]
  85. with open("output/jrtechs2.emd") as fp:
  86. for line in fp:
  87. l_list = list(map(float, line.split()))
  88. vectors.append(l_list[1::])
  89. labels.append(line.split()[0])
  90. ```
  91. Right now, I am interested in visualizing the output. However, that is impractical since it has 50 dimensions! Using the TSNE method, we can reduce the dimensionality so that we can visualize it. Alternatively, we could use another algorithm like Principal Component Analysis (PCA).
  92. ```python
  93. from sklearn.decomposition import IncrementalPCA # inital reduction
  94. from sklearn.manifold import TSNE # final reduction
  95. import numpy as np
  96. def reduce_dimensions(labels, vectors, num_dimensions=2):
  97. # convert both lists into numpy vectors for reduction
  98. vectors = np.asarray(vectors)
  99. labels = np.asarray(labels)
  100. # reduce using t-SNE
  101. vectors = np.asarray(vectors)
  102. tsne = TSNE(n_components=num_dimensions, random_state=0)
  103. vectors = tsne.fit_transform(vectors)
  104. x_vals = [v[0] for v in vectors]
  105. y_vals = [v[1] for v in vectors]
  106. return x_vals, y_vals, labels
  107. x_vals, y_vals, labels = reduce_dimensions(labels, vectors)
  108. ```
  109. Before we visualize our data, we will want to grab the steam users' name because right now, all we have is their steam id, which is just a unique number.
  110. Back in our JanusGraph, we can quickly export the steam ids mapped to the players' names.
  111. ```java
  112. Player player = graph.getPlayer(id);
  113. List<String> names = new ArrayList<String>()
  114. {{
  115. add(id + " " + player.getName());
  116. addAll(
  117. player.getFriends()
  118. .stream()
  119. .map(p -> p.getId() + " " + p.getName())
  120. .collect(Collectors.toList())
  121. );
  122. }};
  123. WrappedFileWriter.writeToFileFromList(names, "friendsMap.map");
  124. ```
  125. We then just create a map in Python linking the steam id to the player ID.
  126. ```python
  127. name_map = {}
  128. with open("friendsMap.map") as fp:
  129. for line in fp:
  130. name_map[line.split()[0]] = line.split()[1]
  131. ```
  132. ```Python
  133. name_map
  134. {'76561198188400721': 'jrtechs',
  135. '76561198049526995': 'Noosh',
  136. ...
  137. '76561198065642391': 'Therefore',
  138. '76561198121369685': 'DataFrogman'}
  139. ```
  140. Using the TSNE dimensionality reduction output, we can view all the nodes on a single plot. To make the graph look more delightful, we only label a fraction of the nodes.
  141. ```python
  142. import matplotlib.pyplot as plt
  143. import random
  144. def plot_with_matplotlib(x_vals, y_vals, labels, num_to_label):
  145. plt.figure(figsize=(5, 5))
  146. plt.scatter(x_vals, y_vals)
  147. plt.title("Embedding Space")
  148. indices = list(range(len(labels)))
  149. selected_indices = random.sample(indices, num_to_label)
  150. for i in selected_indices:
  151. plt.annotate(name_map[labels[i]], (x_vals[i], y_vals[i]))
  152. plt.savefig('ex.png')
  153. plot_with_matplotlib(x_vals, y_vals, labels, 12)
  154. ```
  155. ![algorithm output showing embedding](media/steamNode2vec/output_9_0.png)
  156. This graph may not look exciting, but I assure you that it is.
  157. I can notice that my high school friends and college friends are in different graphical regions, just from eyeballing it.
  158. Moving forward with this, I plan on incorporating game data.
  159. With the graph data vectorized in this fashion, it becomes possible to start employing classification and link prediction algorithms.
  160. Some steam network examples could be a friend or game recommendation system, or even a community detection algorithm.
  161. Although this post only went over a shallow encoder, future work may use a Graph Convolutional Neural Network (GCN) to incorporate user features.