Skip to content

Instantly share code, notes, and snippets.

@gulshanbaraik01
Created June 21, 2020 11:14
Show Gist options
  • Select an option

  • Save gulshanbaraik01/02baf63c0225ae9c2f434b3ec2d57131 to your computer and use it in GitHub Desktop.

Select an option

Save gulshanbaraik01/02baf63c0225ae9c2f434b3ec2d57131 to your computer and use it in GitHub Desktop.
Random Walk Method - Page Rank Algorithm using networkx
# Importing the necessary libraries to execute the "Random Walk Method"
import networkx as nx
import random
import matplotlib.pyplot as plt
import operator
#select random graph using gnp_random_graph() function of networkx
Graph = nx.gnp_random_graph(10, 0.5, directed=True)
nx.draw(Graph, with_labels=True, node_color='green') #draw the network graph
plt.figure(figsize=(15,10))
plt.show() #to show the graph by plotting it
# random_node is the start node selected randomly
random_node = random.choice([i for i in range(Graph.number_of_nodes())])
dict_counter = {} #initialise the value for all nodes as 0
for i in range(Graph.number_of_nodes()):
dict_counter[i] = 0
# increment by traversing through all neighbors nodes
dict_counter[random_node] = dict_counter[random_node]+1
#Traversing through the neighbors of start node
for i in range(100):
list_for_nodes = list(Graph.neighbors(random_node))
if len(list_for_nodes)==0:# if random_node having no outgoing edges
random_node = random.choice([i for i in range(Graph.number_of_nodes())])
dict_counter[random_node] = dict_counter[random_node]+1
else:
random_node = random.choice(list_for_nodes) #choose a node randomly from neighbors
dict_counter[random_node] = dict_counter[random_node]+1
# using pagerank() method to provide ranks for the nodes
rank_node = nx.pagerank(Graph)
#sorting the values of rank and random walk of respective nodes
sorted_rank = sorted(rank_node.items(), key=operator.itemgetter(1))
sorted_random_walk = sorted(dict_counter.items(), key=operator.itemgetter(1))
print(sorted_rank)
print(sorted_random_walk)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment