决策树在Python中的应用

Decision Tree in Python(决策树在Python中的应用)

本文介绍了决策树在Python中的应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中实现DecisionTree的思想。 在TicTacToe游戏中。每个GameState字符串代表当前情况

  • 0为空,1为玩家1移动,2为玩家2移动
    因此,3x3板的单个ameState看起来像'000200000'
    游戏从头到尾的MovesTree看起来像
['000200000', '000210000', '002210000', '002211000', '002211020', '102211020', '102211022', '112211022', '112211222']  

问题:
如何在DecisionTree中添加这些移动(假设来自1000个随机游戏),以便在任何阶段某个树中存在一个GameState,则后续移动将作为下一个分支附加到该节点。
PS.我的目标是找到Tictactoe游戏的所有可能的游戏路径,并将它们保存到文件中。在重新加载时,文件被加载以重新生成决策树,在游戏期间,计算机可以使用它来决定人类玩家是否进行了移动。

  • 列表速度较慢,因为预计将有9!>;362880步棋,除非游戏在所有9步棋都走完之前结束
  • 以每次后续移动为关键字,以后续移动为关键字,后续移动为关键字似乎是最符合逻辑的,但我无法实现搜索、添加方法

推荐答案

我能够按如下方式实现它

def addGameMovesTreeToDataBaseTree(givenMovesTree:list):
    # Get global DataBaseTress
    global DataBaseTree
    # Get local copy of givenMovesTree
    MT = list()
    MT = givenMovesTree.copy() # Populate local MT from given givenMovesTree
    if len(MT) == 0: # Check if givenMovesTree is empty
        return
    elif len(MT) == 1: # Check if givenMovesTree has only last move
        Key = MT[0]
        if MT[0] in DataBaseTree.keys(): # Selected move exist as key in DataBaseTree
            pass # Dont do any thing
        else: # Selected move does not exisit in DataBaseTree
            Key = MT[0] # Store that move as Key
            DataBaseTree[Key] = [] # Add the key with value of empty list
    else: # Check if givenMovesTree has many moves
        if MT[0] in DataBaseTree.keys(): # Selected move exist as key in DataBaseTree
            Key = MT[0] # Store the move as Key
            if MT[1] in DataBaseTree[Key]: # Check if Next move exist in that Keys value
                MT.pop(0) # Remove the top move
                addGameMovesTreeToDataBaseTree(MT) # Go in deeper
            else:
                DataBaseTree[Key].append(MT[1]) # Add next move to value of Key
                MT.pop(0)
                addGameMovesTreeToDataBaseTree(MT) # Go in deeper
        else: # Selected move does not exist as key in DataBaseTree
            Key = MT[0] # Store the move as Key
            DataBaseTree[Key] = [MT[1]] # Add the key with value of next move
            MT.pop(0) # Remove the top move
            addGameMovesTreeToDataBaseTree(MT) # Go in deeper

现在我可以将其发送到JSON文件,甚至可以在下次程序启动时加载它

def saveToJSON(fileName:str):
    global DataBaseTree
    with open(fileName, mode='w', encoding='utf-8') as f:
        try:
            s = json.dumps(DataBaseTree, indent=2)
            f.write(s)
        except Exception as e:
            print(e)

def loadFromJSON(fileName:str):
    global DataBaseTree
    with open(fileName, mode='r', encoding='utf-8') as f:
        try:
            DataBaseTree = json.load(f)
        except Exception as e:
            print(e)

这篇关于决策树在Python中的应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:决策树在Python中的应用