人工知能学習:Pythonは一貫したコスト検索アルゴリズムを実現します

人工知能学習:Pythonは一貫したコスト検索アルゴリズムを実現します


この記事のブログリンク:http://blog.csdn.net/jdh99、作者:jdh、転載を明記してください。

 

周囲:

ホスト:WIN10

Pythonバージョン:3.5

開発環境:pyCharm


説明:

一貫性のあるコスト検索は、幅検索の進化版です。このアルゴリズムが最適なアルゴリズムです。

このアルゴリズムが拡張されるたびに、現在のパス最小のg(n)を持つノードnを消費します

 


 

 

アルゴリズムフロー分析:

データ構造:

  • フロンティア:エッジ。拡張されていないノードを保存します。パス消費順に並べられた優先キュー
  • 探索:セットを探索します。状態が保存されます

処理する:

  • エッジが空の場合、失敗を返します。操作:空?(フロンティア)
  • それ以外の場合は、エッジからリーフノードを選択します。操作:POP(フロンティア)
  • ターゲットテスト:リターンに合格します。それ以外の場合は、リーフノードの状態を探索セットに入れます。
  • リーフノードのすべてのアクションをトラバースします
    • 各アクションは子ノードを生成します
    • 子ノードの状態が探索セットまたはエッジにない場合は、エッジセットに挿入されます。操作:INSERT(、フロンティア)
    • それ以外の場合、この状態がエッジセットに存在し、パスの消費量が多い場合、子ノードがエッジセットの状態を置き換えます。

 

 

最適性の分析:

 

 

Aが開始点で、Cが終了点です。

一貫したコスト検索アルゴリズムの実行:

  • プットフロンティア
  • ---最初の1
  • frontier中取出A(此时路径消耗最小)检测发现不是目标
  • A放入explored
  • 遍历A的子节点,DB放入frontier
  • ---2
  • frontier中取出D(此时路径消耗最小)检测发现不是目标
  • D放入explored
  • 遍历D的子节点,C放入frontier
  • ---3
  • frontier中取出B(此时路径消耗最小)检测发现不是目标
  • B放入explored
  • 遍历B的子节点,E放入frontier
  • ---4
  • frontier中取出E(此时路径消耗最小)检测发现不是目标
  • E放入explored
  • 遍历E的子节点,C准备放入frontier,发现此时frontier已有C,但路径消耗为8大于7,则替代frontier中的C
  • ---5
  • frontier中取出C(此时路径消耗最小)检测发现是目标,成功
  • 最优路径:A->B->E->C

 

从上例可以看出,一致代价搜索具有最优性,关键在于frontier中存储是按路径消耗顺序来排序的。

 

 

算法性能分析:

  • 完备的
  • 不是最优的
  • 时间/空间复杂度



源码中的罗马尼亚城市地图与 《人工智能学习:python实现宽度优先搜索算法》中的地图一致。

源码:
import pandas as pd
from pandas import Series, DataFrame

# 城市信息:city1 city2 path_cost
_city_info = None

# 按照路径消耗进行排序的FIFO,低路径消耗在前面
_frontier_priority = []


# 节点数据结构
class Node:
    def __init__(self, state, parent, action, path_cost):
        self.state = state
        self.parent = parent
        self.action = action
        self.path_cost = path_cost


def main():
    global _city_info
    import_city_info()

    while True:
        src_city = input('input src city\n')
        dst_city = input('input dst city\n')
        # result = breadth_first_search(src_city, dst_city)
        result = uniform_cost_search(src_city, dst_city)
        if not result:
            print('from city: %s to city %s search failure' % (src_city, dst_city))
        else:
            print('from city: %s to city %s search success' % (src_city, dst_city))
            path = []
            while True:
                path.append(result.state)
                if result.parent is None:
                    break
                result = result.parent
            size = len(path)
            for i in range(size):
                if i < size - 1:
                    print('%s->' % path.pop(), end='')
                else:
                    print(path.pop())


def import_city_info():
    global _city_info
    data = [{'city1': 'Oradea', 'city2': 'Zerind', 'path_cost': 71},
            {'city1': 'Oradea', 'city2': 'Sibiu', 'path_cost': 151},
            {'city1': 'Zerind', 'city2': 'Arad', 'path_cost': 75},
            {'city1': 'Arad', 'city2': 'Sibiu', 'path_cost': 140},
            {'city1': 'Arad', 'city2': 'Timisoara', 'path_cost': 118},
            {'city1': 'Timisoara', 'city2': 'Lugoj', 'path_cost': 111},
            {'city1': 'Lugoj', 'city2': 'Mehadia', 'path_cost': 70},
            {'city1': 'Mehadia', 'city2': 'Drobeta', 'path_cost': 75},
            {'city1': 'Drobeta', 'city2': 'Craiova', 'path_cost': 120},
            {'city1': 'Sibiu', 'city2': 'Fagaras', 'path_cost': 99},
            {'city1': 'Sibiu', 'city2': 'Rimnicu Vilcea', 'path_cost': 80},
            {'city1': 'Rimnicu Vilcea', 'city2': 'Craiova', 'path_cost': 146},
            {'city1': 'Rimnicu Vilcea', 'city2': 'Pitesti', 'path_cost': 97},
            {'city1': 'Craiova', 'city2': 'Pitesti', 'path_cost': 138},
            {'city1': 'Fagaras', 'city2': 'Bucharest', 'path_cost': 211},
            {'city1': 'Pitesti', 'city2': 'Bucharest', 'path_cost': 101},
            {'city1': 'Bucharest', 'city2': 'Giurgiu', 'path_cost': 90},
            {'city1': 'Bucharest', 'city2': 'Urziceni', 'path_cost': 85},
            {'city1': 'Urziceni', 'city2': 'Vaslui', 'path_cost': 142},
            {'city1': 'Urziceni', 'city2': 'Hirsova', 'path_cost': 98},
            {'city1': 'Neamt', 'city2': 'Iasi', 'path_cost': 87},
            {'city1': 'Iasi', 'city2': 'Vaslui', 'path_cost': 92},
            {'city1': 'Hirsova', 'city2': 'Eforie', 'path_cost': 86}]

    _city_info = DataFrame(data, columns=['city1', 'city2', 'path_cost'])
    # print(_city_info)


def breadth_first_search(src_state, dst_state):
    global _city_info

    node = Node(src_state, None, None, 0)
    # 目标测试
    if node.state == dst_state:
        return node
    frontier = [node]
    explored = []

    while True:
        if len(frontier) == 0:
            return False
        node = frontier.pop(0)
        explored.append(node.state)
        if node.parent is not None:
            print('deal node:state:%s\tparent state:%s\tpath cost:%d' % (node.state, node.parent.state, node.path_cost))
        else:
            print('deal node:state:%s\tparent state:%s\tpath cost:%d' % (node.state, None, node.path_cost))

        # 遍历子节点
        for i in range(len(_city_info)):
            dst_city = ''
            if _city_info['city1'][i] == node.state:
                dst_city = _city_info['city2'][i]
            elif _city_info['city2'][i] == node.state:
                dst_city = _city_info['city1'][i]
            if dst_city == '':
                continue
            child = Node(dst_city, node, 'go', node.path_cost + _city_info['path_cost'][i])
            print('\tchild node:state:%s path cost:%d' % (child.state, child.path_cost))
            if child.state not in explored and not is_node_in_frontier(frontier, child):
                # 目标测试
                if child.state == dst_state:
                    print('\t\t this child is goal!')
                    return child
                frontier.append(child)
                print('\t\t add child to child')


def is_node_in_frontier(frontier, node):
    for x in frontier:
        if node.state == x.state:
            return True
    return False


def uniform_cost_search(src_state, dst_state):
    global _city_info, _frontier_priority

    node = Node(src_state, None, None, 0)
    frontier_priority_add(node)
    explored = []

    while True:
        if len(_frontier_priority) == 0:
            return False
        node = _frontier_priority.pop(0)
        if node.parent is not None:
            print('deal node:state:%s\tparent state:%s\tpath cost:%d' % (node.state, node.parent.state, node.path_cost))
        else:
            print('deal node:state:%s\tparent state:%s\tpath cost:%d' % (node.state, None, node.path_cost))

        # 目标测试
        if node.state == dst_state:
            print('\t this node is goal!')
            return node
        explored.append(node.state)

        # 遍历子节点
        for i in range(len(_city_info)):
            dst_city = ''
            if _city_info['city1'][i] == node.state:
                dst_city = _city_info['city2'][i]
            elif _city_info['city2'][i] == node.state:
                dst_city = _city_info['city1'][i]
            if dst_city == '':
                continue
            child = Node(dst_city, node, 'go', node.path_cost + _city_info['path_cost'][i])
            print('\tchild node:state:%s path cost:%d' % (child.state, child.path_cost))

            if child.state not in explored and not is_node_in_frontier(_frontier_priority, child):
                frontier_priority_add(child)
                print('\t\t add child to frontier')
            elif is_node_in_frontier(_frontier_priority, child):
                # 替代为路径消耗少的节点
                frontier_priority_replace_by_priority(child)


def frontier_priority_add(node):
    """

    :param Node node:
    :return:
    """
    global _frontier_priority
    size = len(_frontier_priority)
    for i in range(size):
        if node.path_cost < _frontier_priority[i].path_cost:
            _frontier_priority.insert(i, node)
            return
    _frontier_priority.append(node)


def frontier_priority_replace_by_priority(node):
    """

    :param Node node:
    :return:
    """
    global _frontier_priority
    size = len(_frontier_priority)
    for i in range(size):
        if _frontier_priority[i].state == node.state and _frontier_priority[i].path_cost > node.path_cost:
            print('\t\t replace state: %s old cost:%d new cost:%d' % (node.state, _frontier_priority[i].path_cost,
                                                                      node.path_cost))
            _frontier_priority[i] = node
            return


if __name__ == '__main__':
    main()


运行实例:

input src city

Zerind

input dst city

Urziceni

dealnode:state:Zerind        parentstate:None        path cost:0

childnode:state:Oradea path cost:71

 add child to frontier

childnode:state:Arad path cost:75

 add child to frontier

dealnode:state:Oradea        parentstate:Zerind        path cost:71

childnode:state:Zerind path cost:142

childnode:state:Sibiu path cost:222

 add child to frontier

dealnode:state:Arad        parentstate:Zerind        path cost:75

childnode:state:Zerind path cost:150

childnode:state:Sibiu path cost:215

 replace state: Sibiu old cost:222 new cost:215

childnode:state:Timisoara path cost:193

 add child to frontier

dealnode:state:Timisoara        parentstate:Arad        path cost:193

childnode:state:Arad path cost:311

childnode:state:Lugoj path cost:304

 add child to frontier

dealnode:state:Sibiu        parentstate:Arad        path cost:215

childnode:state:Oradea path cost:366

childnode:state:Arad path cost:355

childnode:state:Fagaras path cost:314

 add child to frontier

childnode:state:Rimnicu Vilcea path cost:295

 add child to frontier

dealnode:state:Rimnicu Vilcea        parentstate:Sibiu        path cost:295

childnode:state:Sibiu path cost:375

childnode:state:Craiova path cost:441

 add child to frontier

childnode:state:Pitesti path cost:392

 add child to frontier

dealnode:state:Lugoj        parentstate:Timisoara        path cost:304

childnode:state:Timisoara path cost:415

childnode:state:Mehadia path cost:374

 add child to frontier

dealnode:state:Fagaras        parentstate:Sibiu        path cost:314

childnode:state:Sibiu path cost:413

childnode:state:Bucharest path cost:525

 add child to frontier

dealnode:state:Mehadia        parentstate:Lugoj        path cost:374

childnode:state:Lugoj path cost:444

childnode:state:Drobeta path cost:449

 add child to frontier

dealnode:state:Pitesti        parentstate:Rimnicu Vilcea        pathcost:392

childnode:state:Rimnicu Vilcea path cost:489

childnode:state:Craiova path cost:530

childnode:state:Bucharest path cost:493

 replace state: Bucharest old cost:525 newcost:493

dealnode:state:Craiova        parentstate:Rimnicu Vilcea        pathcost:441

childnode:state:Drobeta path cost:561

childnode:state:Rimnicu Vilcea path cost:587

childnode:state:Pitesti path cost:579

dealnode:state:Drobeta        parentstate:Mehadia        path cost:449

childnode:state:Mehadia path cost:524

childnode:state:Craiova path cost:569

dealnode:state:Bucharest        parentstate:Pitesti        path cost:493

childnode:state:Fagaras path cost:704

childnode:state:Pitesti path cost:594

childnode:state:Giurgiu path cost:583

 add child to frontier

childnode:state:Urziceni path cost:578

 add child to frontier

dealnode:state:Urziceni        parentstate:Bucharest        path cost:578

 this node is goal!

from city: Zerind tocity Urziceni search success

Zerind->Arad->Sibiu->RimnicuVilcea->Pitesti->Bucharest->Urziceni

 

可见,本算法能找出最优解。在导航过程中,用Zerind->Arad->Sibiu替代了Zerind->Oradea->Sibiu,用Sibiu->Rimnicu Vilcea->Pitesti->Bucharest替代了Sibiu->Rimnicu Vilcea->Pitesti->Bucharest。








おすすめ

転載: blog.csdn.net/jdh99/article/details/80872364