0


利用强化学习Q-Learning实现最短路径算法

如果你是一名计算机专业的学生,有对图论有基本的了解,那么你一定知道一些著名的最优路径解,如Dijkstra算法、Bellman-Ford算法和a*算法(A-Star)等。

这些算法都是大佬们经过无数小时的努力才发现的,但是现在已经是人工智能的时代,强化学习算法能够为我们提出和前辈一样好的解决方案吗?

本文中我们将尝试找出一种方法,在从目的地a移动到目的地B时尽可能减少遍历路径。我们使用自己的创建虚拟数据来提供演示,下面代码将创建虚拟的交通网格:

  1. importnetworkxasnx
  2. # Create the graph object
  3. G=nx.Graph()
  4. # Define the nodes
  5. nodes= ['New York, NY', 'Los Angeles, CA', 'Chicago, IL', 'Houston, TX', 'Phoenix, AZ', 'Dallas, TX', 'Miami, FL']
  6. # Add the nodes to the graph
  7. G.add_nodes_from(nodes)
  8. # Define the edges and their distances
  9. edges= [('New York, NY', 'Chicago, IL', {'distance': 790}),
  10. ('New York, NY', 'Miami, FL', {'distance': 1300}),
  11. ('Chicago, IL', 'Dallas, TX', {'distance': 960}),
  12. ('Dallas, TX', 'Houston, TX', {'distance': 240}),
  13. ('Houston, TX', 'Phoenix, AZ', {'distance': 1170}),
  14. ('Phoenix, AZ', 'Los Angeles, CA', {'distance': 380}),
  15. ('Los Angeles, CA', 'Dallas, TX', {'distance': 1240}),
  16. ('Los Angeles, CA', 'Chicago, IL', {'distance': 2010})]
  17. # Add the edges to the graph
  18. G.add_edges_from(edges)

运行起来没有报错,但是我们不知道数据是什么样子的,所以让我们先进行可视化,了解数据:

  1. importmatplotlib.pyplotasplt
  2. # set positions for the nodes (optional)
  3. pos=nx.spring_layout(G)
  4. # draw the nodes and edges
  5. nx.draw_networkx_nodes(G, pos, node_color='lightblue', node_size=500)
  6. nx.draw_networkx_edges(G, pos, edge_color='gray', width=2)
  7. # draw edge labels
  8. edge_labels=nx.get_edge_attributes(G, 'weight')
  9. nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)
  10. # draw node labels
  11. node_labels= {node: node.split(',')[0] fornodeinG.nodes()}
  12. nx.draw_networkx_labels(G, pos, labels=node_labels)
  13. # show the plot
  14. plt.axis('off')
  15. plt.show()

我们有了一个基本的节点网络。但是这感觉太简单了。对于一个强化学习代理来说,这基本上没有难度,所以我们增加更多的节点:

这样就复杂多了,但是它看起来很混乱,比如从New York 到 Arizona就可能是一个挑战。

我们这里使用最常见且通用的Q-Learning来解决这个问题,因为它有动作-状态对矩阵,可以帮助确定最佳的动作。在寻找图中最短路径的情况下,Q-Learning可以通过迭代更新每个状态-动作对的q值来确定两个节点之间的最优路径。

上图为q值的演示。

下面我们开始实现自己的Q-Learning

  1. importnetworkxasnx
  2. importnumpyasnp
  3. defq_learning_shortest_path(G, start_node, end_node, learning_rate=0.8, discount_factor=0.95, epsilon=0.2, num_episodes=1000):
  4. """
  5. Calculates the shortest path in a graph G using Q-learning algorithm.
  6. Parameters:
  7. G (networkx.Graph): the graph
  8. start_node: the starting node
  9. end_node: the destination node
  10. learning_rate (float): the learning rate (default=0.8)
  11. discount_factor (float): the discount factor (default=0.95)
  12. epsilon (float): the exploration factor (default=0.2)
  13. num_episodes (int): the number of episodes (default=1000)
  14. Returns:
  15. A list with the shortest path from start_node to end_node.
  16. """

我们的输入是整个的图,还有开始和结束的节点,首先就需要提取每个节点之间的距离,将其提供给Q-learning算法。

  1. # Extract nodes and edges data
  2. nodes=list(G.nodes())
  3. num_nodes=len(nodes)
  4. edges=list(G.edges(data=True))
  5. num_edges=len(edges)
  6. edge_distances=np.zeros((num_nodes, num_nodes))
  7. fori, j, datainedges:
  8. edge_distances[nodes.index(i), nodes.index(j)] =data['weight']
  9. edge_distances[nodes.index(j), nodes.index(i)] =data['weight']

创建一个Q-table ,这样我们就可以在不断更新模型的同时更新值。

  1. # Initialize Q-values table
  2. q_table=np.zeros((num_nodes, num_nodes))
  3. # Convert start and end node to node indices
  4. start_node_index=nodes.index(start_node)
  5. end_node_index=nodes.index(end_node)

下面就是强化学习算法的核心!

  1. # Q-learning algorithm
  2. forepisodeinrange(num_episodes):
  3. current_node=start_node_index
  4. print(episode)
  5. whilecurrent_node!=end_node_index:
  6. # Choose action based on epsilon-greedy policy
  7. ifnp.random.uniform(0, 1) <epsilon:
  8. # Explore
  9. possible_actions=np.where(edge_distances[current_node,:] >0)[0]
  10. iflen(possible_actions) ==0:
  11. break
  12. action=np.random.choice(possible_actions)
  13. else:
  14. # Exploit
  15. possible_actions=np.where(q_table[current_node,:] ==np.max(q_table[current_node,:]))[0]
  16. iflen(possible_actions) ==0:
  17. break
  18. action=np.random.choice(possible_actions)
  19. # Calculate reward and update Q-value
  20. next_node=action
  21. reward=-edge_distances[current_node, next_node]
  22. q_table[current_node, next_node] = (1-learning_rate) *q_table[current_node, next_node] +learning_rate* (reward+discount_factor*np.max(q_table[next_node, :]))
  23. # Move to next node
  24. current_node=next_node
  25. ifcurrent_node==end_node_index:
  26. break
  27. print(q_table)

这里需要注意的事情是,我们鼓励模型探索还是利用一个特定的路径。

大多数强化算法都是基于这种简单的权衡制定的。 过多的探索的问题在于它可能导致代理花费太多时间探索环境,而没有足够的时间利用它已经学到的知识,可能导致代理采取次优行动并最终无法实现其目标。 如果探索率设置得太高,代理可能永远不会收敛到最优策略。但是如果探索率设置得太低,代理可能会陷入次优策略。 所以,需要在探索和利用之间取得平衡,确保代理进行足够的探索以了解环境,同时利用其知识来最大化回报。

而强化学习中过多利用的问题会使代理陷入次优策略,无法发现可能更好的动作或状态。 即使有更好的选择,代理也可能对其当前的政策过于自信。 这被称为“漏洞利用陷阱”或“局部最优”问题,代理无法从次优解决方案中逃脱。 在这种情况下,探索有助于发现更好的策略和避免“局部最优”。

回到我们的代码,我们需要检查Q-table ,并确保可以从中提取出最短路径。

  1. # Extract shortest path from Q-values table
  2. shortest_path= [start_node]
  3. current_node=start_node_index
  4. whilecurrent_node!=end_node_index:
  5. next_node=np.argmax(q_table[current_node, :])
  6. shortest_path.append(nodes[next_node])
  7. current_node=next_node
  8. shortest_path.append(end_node)
  9. returnshortest_path

最后,使用函数来检查否能够得到所需的输出。

  1. shortest_path=q_learning_shortest_path(G, 'New York, NY', 'Phoenix, AZ')
  2. print(shortest_path)

输出结果如下:

这就是我们数据中从New York, NY到Phoenix, AZ的最短路径!

如果你感兴趣或者想了解更多,可以在这个链接中查看完整的代码。

https://github.com/amos-eda-97/Q-learning-based-optimal-path

作者:Amos Eda

“利用强化学习Q-Learning实现最短路径算法”的评论:

还没有评论