You can download this code by clicking the button below.
This code is now available for download.
This function implements a random walk algorithm on a graph. It starts from a specified starting node and performs a random walk for a given number of steps, with the probability of moving to a neighboring node proportional to its degree.
Technology Stack : Igraph
Code Type : Function
Code Difficulty : Intermediate
def random_walk(graph, start_node, steps=5):
"""
Perform a random walk on the graph starting from the start_node for a given number of steps.
:param graph: igraph.Graph object representing the network
:param start_node: int, the starting node for the random walk
:param steps: int, the number of steps to take in the random walk (default is 5)
:return: list, the sequence of nodes visited in the random walk
"""
walk = [start_node]
for _ in range(steps):
current_node = walk[-1]
neighbors = graph.neighbors(current_node)
if neighbors:
next_node = neighbors[graph.vs[neighbors]['degree'].sample(1)[0]]
walk.append(next_node)
else:
break
return walk