从两个列表构建决策树

时间:2018-01-02 13:30:32

标签: python list tree binary-tree decision-tree

我正在尝试通过我拥有的两个列表来构建这个决策树。

输入:

records= ['dead','healthy','cold','influenza']
symptoms= ['cough','sneezing','fever']

(并不总是必须是这个精确的列表可以是不同的长度等..)

记录列表代表树中的叶子

输出:

                                      cough
                      Yes /                            \ No
                   sneezing                        sneezing
               Yes /       \ No                Yes /       \ No
             fever         fever               fever         fever
       Yes /    \ No    Yes/     \No       Yes /    \ No    Yes/     \No
       dead   cold   influenza   cold      dead   influenza cold   healthy

我的代码:

def buildtree(symptoms,record):

    if len(record)==0:
        return Node(symptoms[0])
    else:
        withelt=buildtree(symptoms+[record[0]],record[1:])
        withoutelt=buildtree(symptoms,record[1:])
        here=Node(symptoms[0],withelt,withoutelt)
        return here

def get_leafs_from_records(records):

    optimal_illness = {}
    list_of_illnesses = []
    illness_in_records=[]
    for record in records:
        if diagnoser.diagnose(record.symptoms) == record.illness:
            list_of_illnesses.append(record.illness)

    for illness in list_of_illnesses:
        if illness in optimal_illness:
            optimal_illness[illness] += 1
        else:
            optimal_illness[illness] = 1

    for illness in optimal_illness:
        illness_in_records.append(illness)
    return illness_in_records

def build_tree(records, symptoms):

    records = get_leafs_from_records(records)

    return buildtree(symptoms,records)

节点类:

class Node:
    def __init__(self, data="", pos=None, neg=None):
       self.data = data
       self.positive_child = pos
       self.negative_child = neg

我的get_leafs_from_records(records)函数就是把它作为我在输入中输入的列表你可以忽略它。

我的代码没有工作,因为它认为它没有像它所假设的那样构建树它只是建立第一个节点的任何想法?

如果还有其他不清楚的地方,请告诉我。

0 个答案:

没有答案